Hono client side logic

Author

pherus

Step-by-step guide: Adding client-side logic to your Hono app

Hono is a great framework to build serverless apps with familiar APIs using Web Standards. It comes with a ton of features out of the box.

One of these features is the ability to compose & render HTML server-side, which is great for static content.
But what if you want to add some client-side logic to your app? You can do so by using the hooks provided by Hono. However, they might not work in your browser — that’s because we’re not shipping any JavaScript to the browser!

Note

We’ll achieve this with client-side hydration. The app gets rendered server-side first, and then the client-side script takes over. The React docs describe it well:

[It] will “attach” your components’ logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser.

In this guide we’ll go over how to build an Hono app with client-side logic, unlocking the full potential of your projects.

What are we building?

We’re building a simple app that renders a counter component server-side and hydrates it client-side.
It runs in Cloudflare Workers, leveraging its static asset bindings - though the same principles apply to the other supported environments as well.

Using Vite we’ll set up two build steps: one for the client-side logic and one for the server-side logic.

2024-12-06-client-side-guide-hydrated.B6EOhtpN.mov

The final result: a counter component that increments a count when a button is clicked!

Let’s build!

First, let’s get started with scaffolding a new Hono app.

pnpm create hono hono-client

Note
Make sure to select the cloudflare-workers template when prompted.

The src directory contains a single index.ts file with a simple Hono app. We’re adding a client directory with an index and component:

Directorysrc
index.ts
Directoryclient
index.tsxlogic to mount the app on the client
Counter.tsxcomponent to demonstrate client-side logic

Adding the component & mounting point

Let’s start by setting up a simple counter component that increments a count when a button is clicked:

src/client/Counter.tsx

1import { useState } from "hono/jsx";
2
3export function Counter() {
4 const [count, setCount] = useState(0);
5 return (
6 <div>
7 <button onClick={() => setCount((c) => c + 1)} type="button">
8 Increase count
9 </button>
10 <span>Count: {count}</span>
11 </div>
12 );
13}

Then we import the component & hydrate it in the client entry file:

src/client/index.tsx

1import { StrictMode } from "hono/jsx";
2import { hydrateRoot } from "hono/jsx/dom/client";
3import { Counter } from "./Counter";
4
5const root = document.getElementById("root");
6if (!root) {
7 throw new Error("Root element not found");
8}
9
10hydrateRoot(
11 root,
12 <StrictMode>
13 <Counter />
14 </StrictMode>
15);

Note

We’re hydrating the app client-side as opposed to rendering it; the static HTML is rendered server-side by Hono. If you’re interested in client-side rendering only, check out the example on GitHub.

Your code editor might give you a hint that document is not defined. Given we added the client-side logic, we need to tell TypeScript that we’re running in a browser environment:

tsconfig.json

{

"compilerOptions": {

//...

"lib": [

"ESNext",

"DOM"

]

// ...

}

}

We’re going to add some JSX to the src/index.ts file, so we first need to change the file extension to .tsx. Once that’s done, we can add Hono’s JSX renderer middleware to the / route and return the statically rendered <Counter /> component:

src/index.tsx

1import { Hono } from "hono";
2import { jsxRenderer } from "hono/jsx-renderer";
3import { Counter } from "./client/Counter";
4
5const app = new Hono();
6app.use(
7 jsxRenderer(
8 ({ children }) => (
9 <html lang="en">
10 <head>
11 <meta charSet="utf-8" />
12 <meta content="width=device-width, initial-scale=1" name="viewport" />
13 <title>hono-client</title>
14 </head>
15 <div id="root">{children}</div>
16 </html>
17 ),
18 { docType: true }
19 )
20);
21
22app.get("/", (c) => {
23 return c.text("Hello Hono!");
24 return c.render(<Counter />);
25});
26
27export default app;

We’re almost there. If you run the app now with the dev script, you’ll get an error. Let’s fix that by adding the build steps!

Adding build steps and scripts

At this point, we have both server-side and client-side logic and need to add two build steps to our project. Let’s install Vite and two plugins to facilitate this.

Terminal window

pnpm add vite

pnpm add -D @hono/vite-build @hono/vite-dev-server

In the root of your project, create a vite.config.ts file. We’ll define the config for both the client-side build and the server-side build:

vite.config.ts

1import build from "@hono/vite-build/cloudflare-workers";
2import devServer from "@hono/vite-dev-server";
3import cloudflareAdapter from "@hono/vite-dev-server/cloudflare";
4
5import { defineConfig } from "vite";
6export default defineConfig(({ mode }) => {
7 if (mode === "client") {
8 return {
9 build: {
10 rollupOptions: {
11 input: "./src/client/index.tsx",
12 output: {
13 entryFileNames: "assets/[name].js"
14 }
15 },
16 outDir: "./public"
17 }
18 };
19 }
20
21 const entry = "./src/index.tsx";
22 return {
23 server: { port: 8787 },
24 plugins: [
25 devServer({ adapter: cloudflareAdapter, entry }),
26 build({ entry }) // shows an error but its fine no issue just eslint related error cast
27 ]
28 };
29});

Note

For the client build, the outDir is set to ./public. This is the directory where the Worker will find the client-side script.

Now we need to adjust the package.json scripts to facilitate the new build steps. Additionally, we set the type to module to allow for ESM imports:

package.json

{

"name": "hono-client",

"type": "module",

"scripts": {

"dev": "wrangler dev",

"dev": "vite dev",

"build": "vite build --mode client && vite build",

"deploy": "wrangler deploy --minify"

}

// ...

}

Tip

This would be a good moment to add the public directory to your .gitignore.

Running the app

If you run the app now with the dev script, you’ll see the counter component rendered server-side. The client-side script hasn’t been loaded yet, so the counter component won’t work.

Terminal window

pnpm dev

There’s only one step left to make the counter component work. We’re almost there!

Load the client-side script

As a final step we need to load the client-side script in the document’s head.

For the script that we’re loading we need to make a distinction between a development and production environment. Vite allows us to do this easily with its built-in env. For the dev environment we can load the client’s .tsx file; for production we have to read it from the public directory.

First we add the vite/client types to the TypeScript config:

tsconfig.json

{

"compilerOptions": {

//...

"types": [

// ...

"vite/client"

]

//...

}

}

Then we adjust the src/index.tsx file to load the client-side script, depending on the environment:

src/index.tsx

1// ...
2app.use(
3 jsxRenderer(
4 ({ children }) => (
5 <html lang="en">
6 <head>
7 <meta charSet="utf-8" />
8 <meta content="width=device-width, initial-scale=1" name="viewport" />
9 <title>hono-client</title>
10
11
12 <script
13 type="module"
14 src={
15 import.meta.env.PROD
16 ? "/assets/index.js"
17 : "/src/client/index.tsx"
18 }
19 />
20 </head>
21 <body>
22 <div id="root">{children}</div>
23 </body>
24 </html>
25 ),
26 { docType: true }
27 )
28);
29// ...


Run locally

Great! You can now run the app with the dev script and see the counter component in action.

Terminal window

pnpm dev

Deploying

To deploy the app to Cloudflare Workers we have to update wrangler.toml so it points to the correct worker build & resolves the public assets directory. Lastly, we update the deploy script.

wrangler.toml

name = "hono-client"

main = "src/index.ts"

main = "dist/index.js"


assets = { directory = "./public/" }

# ...

package.json

{

// ...

"scripts": {

"dev": "vite dev",

"build": "vite build --mode client && vite build",

"deploy": "wrangler deploy --minify",

"deploy": "$npm_execpath run build && wrangler deploy --no-bundle"

}

// ...

}

Note

Note that the wrangler deploy has the --no-bundle flag. The build is taken care of by the Vite build step. Wrangler’s task is merely to deploy it to the Cloudflare Workers platform.

Deploy your app

You can now deploy your app to Cloudflare Workers with the deploy script:

Terminal window

pnpm deploy

Conclusion

That’s it! You’ve built a simple Hono app with client-side logic. You can now extend your app with more complex client-side features, such as fetching data from an API route, adding a form to your project, or even building a full SPA.