This is the full developer documentation for Hono. # Start of Hono documentation # Hono Hono - _**means flameπŸ”₯ in Japanese**_ - is a small, simple, and ultrafast web framework built on Web Standards. It works on any JavaScript runtime: Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Netlify, AWS Lambda, Lambda@Edge, and Node.js. Fast, but not only fast. ```ts twoslash import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hono!')) export default app ``` ## Quick Start Just run this: ::: code-group ```sh [npm] npm create hono@latest ``` ```sh [yarn] yarn create hono ``` ```sh [pnpm] pnpm create hono@latest ``` ```sh [bun] bun create hono@latest ``` ```sh [deno] deno init --npm hono@latest ``` ::: ## Features - **Ultrafast** πŸš€ - The router `RegExpRouter` is really fast. Not using linear loops. Fast. - **Lightweight** πŸͺΆ - The `hono/tiny` preset is under 14kB. Hono has zero dependencies and uses only the Web Standards. - **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute, Deno, Bun, AWS Lambda, or Node.js. The same code runs on all platforms. - **Batteries Included** πŸ”‹ - Hono has built-in middleware, custom middleware, third-party middleware, and helpers. Batteries included. - **Delightful DX** πŸ˜ƒ - Super clean APIs. First-class TypeScript support. Now, we've got "Types". ## Use-cases Hono is a simple web application framework similar to Express, without a frontend. But it runs on CDN Edges and allows you to construct larger applications when combined with middleware. Here are some examples of use-cases. - Building Web APIs - Proxy of backend servers - Front of CDN - Edge application - Base server for a library - Full-stack application ## Who is using Hono? | Project | Platform | What for? | | ---------------------------------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------- | | [cdnjs](https://cdnjs.com) | Cloudflare Workers | A free and open-source CDN service. _Hono is used for the API server_. | | [Cloudflare D1](https://www.cloudflare.com/developer-platform/d1/) | Cloudflare Workers | Serverless SQL databases. _Hono is used for the internal API server_. | | [Cloudflare Workers KV](https://www.cloudflare.com/developer-platform/workers-kv/) | Cloudflare Workers | Serverless key-value database. _Hono is used for the internal API server_. | | [BaseAI](https://baseai.dev) | Local AI Server | Serverless AI agent pipes with memory. An open-source agentic AI framework for web. _API server with Hono_. | | [Unkey](https://unkey.dev) | Cloudflare Workers | An open-source API authentication and authorization. _Hono is used for the API server_. | | [OpenStatus](https://openstatus.dev) | Bun | An open-source website & API monitoring platform. _Hono is used for the API server_. | | [Deno Benchmarks](https://deno.com/benchmarks) | Deno | A secure TypeScript runtime built on V8. _Hono is used for benchmarking_. | | [Clerk](https://clerk.com) | Cloudflare Workers | An open-source User Management Platform. _Hono is used for the API server_. | And the following. - [Drivly](https://driv.ly/) - Cloudflare Workers - [repeat.dev](https://repeat.dev/) - Cloudflare Workers Do you want to see more? See [Who is using Hono in production?](https://github.com/orgs/honojs/discussions/1510). ## Hono in 1 minute A demonstration to create an application for Cloudflare Workers with Hono. ![A gif showing a hono app being created quickly with fast iteration.](/images/sc.gif) ## Ultrafast **Hono is the fastest**, compared to other routers for Cloudflare Workers. ``` Hono x 402,820 ops/sec Β±4.78% (80 runs sampled) itty-router x 212,598 ops/sec Β±3.11% (87 runs sampled) sunder x 297,036 ops/sec Β±4.76% (77 runs sampled) worktop x 197,345 ops/sec Β±2.40% (88 runs sampled) Fastest is Hono ✨ Done in 28.06s. ``` See [more benchmarks](/docs/concepts/benchmarks). ## Lightweight **Hono is so small**. With the `hono/tiny` preset, its size is **under 14KB** when minified. There are many middleware and adapters, but they are bundled only when used. For context, the size of Express is 572KB. ``` $ npx wrangler dev --minify ./src/index.ts ⛅️ wrangler 2.20.0 -------------------- ⬣ Listening at http://0.0.0.0:8787 - http://127.0.0.1:8787 - http://192.168.128.165:8787 Total Upload: 11.47 KiB / gzip: 4.34 KiB ``` ## Multiple routers **Hono has multiple routers**. **RegExpRouter** is the fastest router in the JavaScript world. It matches the route using a single large Regex created before dispatch. With **SmartRouter**, it supports all route patterns. **LinearRouter** registers the routes very quickly, so it's suitable for an environment that initializes applications every time. **PatternRouter** simply adds and matches the pattern, making it small. See [more information about routes](/docs/concepts/routers). ## Web Standards Thanks to the use of the **Web Standards**, Hono works on a lot of platforms. - Cloudflare Workers - Cloudflare Pages - Fastly Compute - Deno - Bun - Vercel - AWS Lambda - Lambda@Edge - Others And by using [a Node.js adapter](https://github.com/honojs/node-server), Hono works on Node.js. See [more information about Web Standards](/docs/concepts/web-standard). ## Middleware & Helpers **Hono has many middleware and helpers**. This makes "Write Less, do more" a reality. Out of the box, Hono provides middleware and helpers for: - [Basic Authentication](/docs/middleware/builtin/basic-auth) - [Bearer Authentication](/docs/middleware/builtin/bearer-auth) - [Body Limit](/docs/middleware/builtin/body-limit) - [Cache](/docs/middleware/builtin/cache) - [Compress](/docs/middleware/builtin/compress) - [Context Storage](/docs/middleware/builtin/context-storage) - [Cookie](/docs/helpers/cookie) - [CORS](/docs/middleware/builtin/cors) - [ETag](/docs/middleware/builtin/etag) - [html](/docs/helpers/html) - [JSX](/docs/guides/jsx) - [JWT Authentication](/docs/middleware/builtin/jwt) - [Logger](/docs/middleware/builtin/logger) - [Language](/docs/middleware/builtin/language) - [Pretty JSON](/docs/middleware/builtin/pretty-json) - [Secure Headers](/docs/middleware/builtin/secure-headers) - [SSG](/docs/helpers/ssg) - [Streaming](/docs/helpers/streaming) - [GraphQL Server](https://github.com/honojs/middleware/tree/main/packages/graphql-server) - [Firebase Authentication](https://github.com/honojs/middleware/tree/main/packages/firebase-auth) - [Sentry](https://github.com/honojs/middleware/tree/main/packages/sentry) - Others! For example, adding ETag and request logging only takes a few lines of code with Hono: ```ts import { Hono } from 'hono' import { etag } from 'hono/etag' import { logger } from 'hono/logger' const app = new Hono() app.use(etag(), logger()) ``` See [more information about Middleware](/docs/concepts/middleware). ## Developer Experience Hono provides a delightful "**Developer Experience**". Easy access to Request/Response thanks to the `Context` object. Moreover, Hono is written in TypeScript. Hono has "**Types**". For example, the path parameters will be literal types. ![A screenshot showing Hono having proper literal typing when URL parameters. The URL "/entry/:date/:id" allows for request parameters to be "date" or "id"](/images/ss.png) And, the Validator and Hono Client `hc` enable the RPC mode. In RPC mode, you can use your favorite validator such as Zod and easily share server-side API specs with the client and build type-safe applications. See [Hono Stacks](/docs/concepts/stacks). # Cloudflare Workers [Cloudflare Workers](https://workers.cloudflare.com) is a JavaScript edge runtime on Cloudflare CDN. You can develop the application locally and publish it with a few commands using [Wrangler](https://developers.cloudflare.com/workers/wrangler/). Wrangler includes transcompiler, so we can write the code with TypeScript. Let’s make your first application for Cloudflare Workers with Hono. ## 1. Setup A starter for Cloudflare Workers is available. Start your project with "create-hono" command. Select `cloudflare-workers` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move to `my-app` and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: ## 2. Hello World Edit `src/index.ts` like below. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Cloudflare Workers!')) export default app ``` ## 3. Run Run the development server locally. Then, access `http://localhost:8787` in your web browser. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm dev ``` ```sh [bun] bun run dev ``` ::: ### Change port number If you need to change the port number you can follow the instructions here to update `wrangler.toml` / `wrangler.json` / `wrangler.jsonc` files: [Wrangler Configuration](https://developers.cloudflare.com/workers/wrangler/configuration/#local-development-settings) Or, you can follow the instructions here to set CLI options: [Wrangler CLI](https://developers.cloudflare.com/workers/wrangler/commands/#dev) ## 4. Deploy If you have a Cloudflare account, you can deploy to Cloudflare. In `package.json`, `$npm_execpath` needs to be changed to your package manager of choice. ::: code-group ```sh [npm] npm run deploy ``` ```sh [yarn] yarn deploy ``` ```sh [pnpm] pnpm run deploy ``` ```sh [bun] bun run deploy ``` ::: That's all! ## Using Hono with other event handlers You can integrate Hono with other event handlers (such as `scheduled`) in _Module Worker mode_. To do this, export `app.fetch` as the module's `fetch` handler, and then implement other handlers as needed: ```ts const app = new Hono() export default { fetch: app.fetch, scheduled: async (batch, env) => {}, } ``` ## Serve static files If you want to serve static files, you can use [the Static Assets feature](https://developers.cloudflare.com/workers/static-assets/) of Cloudflare Workers. Specify the directory for the files in `wrangler.toml`: ```toml assets = { directory = "public" } ``` Then create theΒ `public`Β directory and place the files there. For instance, `./public/static/hello.txt` will be served as `/static/hello.txt`. ``` . β”œβ”€β”€ package.json β”œβ”€β”€ public β”‚Β Β  β”œβ”€β”€ favicon.ico β”‚Β Β  └── static β”‚Β Β  └── hello.txt β”œβ”€β”€ src β”‚Β Β  └── index.ts └── wrangler.toml ``` ## Types You have to install `@cloudflare/workers-types` if you want to have workers types. ::: code-group ```sh [npm] npm i --save-dev @cloudflare/workers-types ``` ```sh [yarn] yarn add -D @cloudflare/workers-types ``` ```sh [pnpm] pnpm add -D @cloudflare/workers-types ``` ```sh [bun] bun add --dev @cloudflare/workers-types ``` ::: ## Testing For testing, we recommend using `@cloudflare/vitest-pool-workers`. Refer to [examples](https://github.com/honojs/examples) for setting it up. If there is the application below. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Please test me!')) ``` We can test if it returns "_200 OK_" Response with this code. ```ts describe('Test the application', () => { it('Should return 200 response', async () => { const res = await app.request('http://localhost/') expect(res.status).toBe(200) }) }) ``` ## Bindings In the Cloudflare Workers, we can bind the environment values, KV namespace, R2 bucket, or Durable Object. You can access them in `c.env`. It will have the types if you pass the "_type definition_" for the bindings to the `Hono` as generics. ```ts type Bindings = { MY_BUCKET: R2Bucket USERNAME: string PASSWORD: string } const app = new Hono<{ Bindings: Bindings }>() // Access to environment values app.put('/upload/:key', async (c, next) => { const key = c.req.param('key') await c.env.MY_BUCKET.put(key, c.req.body) return c.text(`Put ${key} successfully!`) }) ``` ## Using Variables in Middleware This is the only case for Module Worker mode. If you want to use Variables or Secret Variables in Middleware, for example, "username" or "password" in Basic Authentication Middleware, you need to write like the following. ```ts import { basicAuth } from 'hono/basic-auth' type Bindings = { USERNAME: string PASSWORD: string } const app = new Hono<{ Bindings: Bindings }>() //... app.use('/auth/*', async (c, next) => { const auth = basicAuth({ username: c.env.USERNAME, password: c.env.PASSWORD, }) return auth(c, next) }) ``` The same is applied to Bearer Authentication Middleware, JWT Authentication, or others. ## Deploy from GitHub Actions Before deploying code to Cloudflare via CI, you need a Cloudflare token. You can manage it from [User API Tokens](https://dash.cloudflare.com/profile/api-tokens). If it's a newly created token, select the **Edit Cloudflare Workers** template. If you already have another token, make sure the token has the corresponding permissions. (Note: token permissions are not shared between Cloudflare Pages and Cloudflare Workers). then go to your GitHub repository settings dashboard: `Settings->Secrets and variables->Actions->Repository secrets`, and add a new secret with the name `CLOUDFLARE_API_TOKEN`. then create `.github/workflows/deploy.yml` in your Hono project root folder, paste the following code: ```yml name: Deploy on: push: branches: - main jobs: deploy: runs-on: ubuntu-latest name: Deploy steps: - uses: actions/checkout@v4 - name: Deploy uses: cloudflare/wrangler-action@v3 with: apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }} ``` then edit `wrangler.toml`, and add this code after `compatibility_date` line. ```toml main = "src/index.ts" minify = true ``` Everything is ready! Now push the code and enjoy it. ## Load env when local development To configure the environment variables for local development, create a `.dev.vars` file or a `.env` file in the root directory of the project. These files should be formatted using the [dotenv](https://hexdocs.pm/dotenvy/dotenv-file-format.html) syntax. For example: ``` SECRET_KEY=value API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 ``` > For more about this section you can find in the Cloudflare documentation: > https://developers.cloudflare.com/workers/wrangler/configuration/#secrets Then we use the `c.env.*` to get the environment variables in our code. ::: info By default, `process.env` is not available in Cloudflare Workers, so it is recommended to get environment variables from `c.env`. If you want to use it, you need to enable [`nodejs_compat_populate_process_env`](https://developers.cloudflare.com/workers/configuration/compatibility-flags/#enable-auto-populating-processenv) flag. You can also import `env` from `cloudflare:workers`. For details, please see [How to access `env` on Cloudflare docs](https://developers.cloudflare.com/workers/runtime-apis/bindings/#how-to-access-env) ::: ```ts type Bindings = { SECRET_KEY: string } const app = new Hono<{ Bindings: Bindings }>() app.get('/env', (c) => { const SECRET_KEY = c.env.SECRET_KEY return c.text(SECRET_KEY) }) ``` Before you deploy your project to Cloudflare, remember to set the environment variable/secrets in the Cloudflare Workers project's configuration. > For more about this section you can find in the Cloudflare documentation: > https://developers.cloudflare.com/workers/configuration/environment-variables/#add-environment-variables-via-the-dashboard # Vercel Vercel is the AI cloud, providing the developer tools and cloud infrastructure to build, scale, and secure a faster, more personalized web. Hono can be deployed to Vercel with zero-configuration. ## 1. Setup A starter for Vercel is available. Start your project with "create-hono" command. Select `vercel` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move into `my-app` and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: We will use Vercel CLI to work on the app locally in the next step. If you haven't already, install it globally following [the Vercel CLI documentation](https://vercel.com/docs/cli). ## 2. Hello World In the `index.ts` or `src/index.ts` of your project, export the Hono application as a default export. ```ts import { Hono } from 'hono' const app = new Hono() const welcomeStrings = [ 'Hello Hono!', 'To learn more about Hono on Vercel, visit https://vercel.com/docs/frameworks/backend/hono', ] app.get('/', (c) => { return c.text(welcomeStrings.join('\n\n')) }) export default app ``` If you started with the `vercel` template, this is already set up for you. ## 3. Run To run the development server locally: ```sh vercel dev ``` Visiting `localhost:3000` will respond with a text response. ## 4. Deploy Deploy to Vercel using `vc deploy`. ```sh vercel deploy ``` ## Further reading [Learn more about Hono in the Vercel documentation](https://vercel.com/docs/frameworks/backend/hono). # Supabase Edge Functions [Supabase](https://supabase.com/) is an open-source alternative to Firebase, offering a suite of tools similar to Firebase's capabilities, including database, authentication, storage, and now, serverless functions. Supabase Edge Functions are server-side TypeScript functions that are distributed globally, running closer to your users for improved performance. These functions are developed using [Deno](https://deno.com/), which brings several benefits, including improved security and a modern JavaScript/TypeScript runtime. Here's how you can get started with Supabase Edge Functions: ## 1. Setup ### Prerequisites Before you begin, make sure you have the Supabase CLI installed. If you haven't installed it yet, follow the instructions in the [official documentation](https://supabase.com/docs/guides/cli/getting-started). ### Creating a New Project 1. Open your terminal or command prompt. 2. Create a new Supabase project in a directory on your local machine by running: ```bash supabase init ``` This command initializes a new Supabase project in the current directory. ### Adding an Edge Function 3. Inside your Supabase project, create a new Edge Function named `hello-world`: ```bash supabase functions new hello-world ``` This command creates a new Edge Function with the specified name in your project. ## 2. Hello World Edit the `hello-world` function by modifying the file `supabase/functions/hello-world/index.ts`: ```ts import { Hono } from 'jsr:@hono/hono' // change this to your function name const functionName = 'hello-world' const app = new Hono().basePath(`/${functionName}`) app.get('/hello', (c) => c.text('Hello from hono-server!')) Deno.serve(app.fetch) ``` ## 3. Run To run the function locally, use the following command: 1. Use the following command to serve the function: ```bash supabase start # start the supabase stack supabase functions serve --no-verify-jwt # start the Functions watcher ``` The `--no-verify-jwt` flag allows you to bypass JWT verification during local development. 2. Make a GET request using cURL or Postman to `http://127.0.0.1:54321/functions/v1/hello-world/hello`: ```bash curl --location 'http://127.0.0.1:54321/functions/v1/hello-world/hello' ``` This request should return the text "Hello from hono-server!". ## 4. Deploy You can deploy all of your Edge Functions in Supabase with a single command: ```bash supabase functions deploy ``` Alternatively, you can deploy individual Edge Functions by specifying the name of the function in the deploy command: ```bash supabase functions deploy hello-world ``` For more deployment methods, visit the Supabase documentation on [Deploying to Production](https://supabase.com/docs/guides/functions/deploy). # Bun [Bun](https://bun.com) is another JavaScript runtime. It's not Node.js or Deno. Bun includes a transcompiler, we can write the code with TypeScript. Hono also works on Bun. ## 1. Install Bun To install `bun` command, follow the instruction in [the official web site](https://bun.com). ## 2. Setup ### 2.1. Setup a new project A starter for Bun is available. Start your project with "bun create" command. Select `bun` template for this example. ```sh bun create hono@latest my-app ``` Move into my-app and install the dependencies. ```sh cd my-app bun install ``` ### 2.2. Setup an existing project On an existing Bun project, we only need to install `hono` dependencies on the project root directory via ```sh bun add hono ``` Then add the `dev` command to your existing `package.json`. ```json { "scripts": { "dev": "bun run --hot src/index.ts" } } ``` See the [Bun starter template](https://github.com/honojs/starter/tree/main/templates/bun) for a minimal example setup. This is the output of running `bun create hono@latest`. ## 3. Hello World "Hello World" script is below. Almost the same as writing on other platforms. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Bun!')) export default app ``` If you are setting up Hono on an existing project, the `bun run dev` command expects the "Hello World" script to be placed in `src/index.tx` ## 4. Run Run the command. ```sh bun run dev ``` Then, access `http://localhost:3000` in your browser. ## Change port number You can specify the port number with exporting the `port`. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Bun!')) export default app // [!code --] export default { // [!code ++] port: 3000, // [!code ++] fetch: app.fetch, // [!code ++] } // [!code ++] ``` ## Serve static files To serve static files, use `serveStatic` which is imported from `hono/bun`. ```ts import { serveStatic } from 'hono/bun' const app = new Hono() app.use('/static/*', serveStatic({ root: './' })) app.use('/favicon.ico', serveStatic({ path: './favicon.ico' })) app.get('/', (c) => c.text('You can access: /static/hello.txt')) app.get('*', serveStatic({ path: './static/fallback.txt' })) ``` For the above code, it will work well with the following directory structure. ``` ./ β”œβ”€β”€ favicon.ico β”œβ”€β”€ src └── static β”œβ”€β”€ demo β”‚ └── index.html β”œβ”€β”€ fallback.txt β”œβ”€β”€ hello.txt └── images └── dinotocat.png ``` ### `rewriteRequestPath` If you want to map `http://localhost:3000/static/*` to `./statics`, you can use the `rewriteRequestPath` option: ```ts app.get( '/static/*', serveStatic({ root: './', rewriteRequestPath: (path) => path.replace(/^\/static/, '/statics'), }) ) ``` ### `mimes` You can add MIME types with `mimes`: ```ts app.get( '/static/*', serveStatic({ mimes: { m3u8: 'application/vnd.apple.mpegurl', ts: 'video/mp2t', }, }) ) ``` ### `onFound` You can specify handling when the requested file is found with `onFound`: ```ts app.get( '/static/*', serveStatic({ // ... onFound: (_path, c) => { c.header('Cache-Control', `public, immutable, max-age=31536000`) }, }) ) ``` ### `onNotFound` You can specify handling when the requested file is not found with `onNotFound`: ```ts app.get( '/static/*', serveStatic({ onNotFound: (path, c) => { console.log(`${path} is not found, you access ${c.req.path}`) }, }) ) ``` ### `precompressed` The `precompressed` option checks if files with extensions like `.br` or `.gz` are available and serves them based on the `Accept-Encoding` header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file. ```ts app.get( '/static/*', serveStatic({ precompressed: true, }) ) ``` ## Testing You can use `bun:test` for testing on Bun. ```ts import { describe, expect, it } from 'bun:test' import app from '.' describe('My first test', () => { it('Should return 200 Response', async () => { const req = new Request('http://localhost/') const res = await app.fetch(req) expect(res.status).toBe(200) }) }) ``` Then, run the command. ```sh bun test index.test.ts ``` # Deno [Deno](https://deno.com/) is a JavaScript runtime built on V8. It's not Node.js. Hono also works on Deno. You can use Hono, write the code with TypeScript, run the application with the `deno` command, and deploy it to "Deno Deploy". ## 1. Install Deno First, install `deno` command. Please refer to [the official document](https://docs.deno.com/runtime/getting_started/installation/). ## 2. Setup A starter for Deno is available. Start your project with the [`deno init`](https://docs.deno.com/runtime/reference/cli/init/) command. ```sh deno init --npm hono --template=deno my-app ``` Move into `my-app`. For Deno, you don't have to install Hono explicitly. ```sh cd my-app ``` ## 3. Hello World Edit `main.ts`: ```ts [main.ts] import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Deno!')) Deno.serve(app.fetch) ``` ## 4. Run Run the development server locally. Then, access `http://localhost:8000` in your Web browser. ```sh deno task start ``` ## Change port number You can specify the port number by updating the arguments of `Deno.serve` in `main.ts`: ```ts Deno.serve(app.fetch) // [!code --] Deno.serve({ port: 8787 }, app.fetch) // [!code ++] ``` ## Serve static files To serve static files, use `serveStatic` imported from `hono/deno`. ```ts import { Hono } from 'hono' import { serveStatic } from 'hono/deno' const app = new Hono() app.use('/static/*', serveStatic({ root: './' })) app.use('/favicon.ico', serveStatic({ path: './favicon.ico' })) app.get('/', (c) => c.text('You can access: /static/hello.txt')) app.get('*', serveStatic({ path: './static/fallback.txt' })) Deno.serve(app.fetch) ``` For the above code, it will work well with the following directory structure. ``` ./ β”œβ”€β”€ favicon.ico β”œβ”€β”€ index.ts └── static β”œβ”€β”€ demo β”‚ └── index.html β”œβ”€β”€ fallback.txt β”œβ”€β”€ hello.txt └── images └── dinotocat.png ``` ### `rewriteRequestPath` If you want to map `http://localhost:8000/static/*` to `./statics`, you can use the `rewriteRequestPath` option: ```ts app.get( '/static/*', serveStatic({ root: './', rewriteRequestPath: (path) => path.replace(/^\/static/, '/statics'), }) ) ``` ### `mimes` You can add MIME types with `mimes`: ```ts app.get( '/static/*', serveStatic({ mimes: { m3u8: 'application/vnd.apple.mpegurl', ts: 'video/mp2t', }, }) ) ``` ### `onFound` You can specify handling when the requested file is found with `onFound`: ```ts app.get( '/static/*', serveStatic({ // ... onFound: (_path, c) => { c.header('Cache-Control', `public, immutable, max-age=31536000`) }, }) ) ``` ### `onNotFound` You can specify handling when the requested file is not found with `onNotFound`: ```ts app.get( '/static/*', serveStatic({ onNotFound: (path, c) => { console.log(`${path} is not found, you access ${c.req.path}`) }, }) ) ``` ### `precompressed` The `precompressed` option checks if files with extensions like `.br` or `.gz` are available and serves them based on the `Accept-Encoding` header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file. ```ts app.get( '/static/*', serveStatic({ precompressed: true, }) ) ``` ## Deno Deploy Deno Deploy is a serverless platform for running JavaScript and TypeScript applications in the cloud. It provides a management plane for deploying and running applications through integrations like GitHub deployment. Hono also works on Deno Deploy. Please refer to [the official document](https://docs.deno.com/deploy/manual/). ## Testing Testing the application on Deno is easy. You can write with `Deno.test` and use `assert` or `assertEquals` from [@std/assert](https://jsr.io/@std/assert). ```sh deno add jsr:@std/assert ``` ```ts [hello.ts] import { Hono } from 'hono' import { assertEquals } from '@std/assert' Deno.test('Hello World', async () => { const app = new Hono() app.get('/', (c) => c.text('Please test me')) const res = await app.request('http://localhost/') assertEquals(res.status, 200) }) ``` Then run the command: ```sh deno test hello.ts ``` ## npm and JSR Hono is available on both [npm](https://www.npmjs.com/package/hono) and [JSR](https://jsr.io/@hono/hono) (the JavaScript Registry). You can use either `npm:hono` or `jsr:@hono/hono` in your `deno.json`: ```json { "imports": { "hono": "jsr:@hono/hono" // [!code --] "hono": "npm:hono" // [!code ++] } } ``` To use middleware you need to use the [Deno directory](https://docs.deno.com/runtime/fundamentals/configuration/#custom-path-mappings) syntax in the import. ```json { "imports": { "hono/": "npm:/hono/" } } ``` When using third-party middleware, you may need to use Hono from the same registry as the middleware for proper TypeScript type inference. For example, if using the middleware from npm, you should also use Hono from npm: ```json { "imports": { "hono": "npm:hono", "zod": "npm:zod", "@hono/zod-validator": "npm:@hono/zod-validator" } } ``` We also provide many third-party middleware packages on [JSR](https://jsr.io/@hono). When using the middleware on JSR, use Hono from JSR: ```json { "imports": { "hono": "jsr:@hono/hono", "zod": "npm:zod", "@hono/zod-validator": "jsr:@hono/zod-validator" } } ``` # Node.js [Node.js](https://nodejs.org/) is an open-source, cross-platform JavaScript runtime environment. Hono was not designed for Node.js at first, but with a [Node.js Adapter](https://github.com/honojs/node-server), it can run on Node.js as well. ::: info It works on Node.js versions greater than 18.x. The specific required Node.js versions are as follows: - 18.x => 18.14.1+ - 19.x => 19.7.0+ - 20.x => 20.0.0+ Essentially, you can simply use the latest version of each major release. ::: ## 1. Setup A starter for Node.js is available. Start your project with "create-hono" command. Select `nodejs` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move to `my-app` and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: ## 2. Hello World Edit `src/index.ts`: ```ts import { serve } from '@hono/node-server' import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Node.js!')) serve(app) ``` If you want to gracefully shut down the server, write it like this: ```ts const server = serve(app) // graceful shutdown process.on('SIGINT', () => { server.close() process.exit(0) }) process.on('SIGTERM', () => { server.close((err) => { if (err) { console.error(err) process.exit(1) } process.exit(0) }) }) ``` ## 3. Run Run the development server locally. Then, access `http://localhost:3000` in your Web browser. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm dev ``` ::: ## Change port number You can specify the port number with the `port` option. ```ts serve({ fetch: app.fetch, port: 8787, }) ``` ## Access the raw Node.js APIs You can access the Node.js APIs from `c.env.incoming` and `c.env.outgoing`. ```ts import { Hono } from 'hono' import { serve, type HttpBindings } from '@hono/node-server' // or `Http2Bindings` if you use HTTP2 type Bindings = HttpBindings & { /* ... */ } const app = new Hono<{ Bindings: Bindings }>() app.get('/', (c) => { return c.json({ remoteAddress: c.env.incoming.socket.remoteAddress, }) }) serve(app) ``` ## Serve static files You can use `serveStatic` to serve static files from the local file system. For example, suppose the directory structure is as follows: ```sh ./ β”œβ”€β”€ favicon.ico β”œβ”€β”€ index.ts └── static β”œβ”€β”€ hello.txt └── image.png ``` If a request to the path `/static/*` comes in and you want to return a file under `./static`, you can write the following: ```ts import { serveStatic } from '@hono/node-server/serve-static' app.use('/static/*', serveStatic({ root: './' })) ``` ::: warning The `root` option resolves paths relative to the current working directory (`process.cwd()`). This means the behavior depends on **where you run your Node.js process from**, not where your source file is located. If you start your server from a different directory, file resolution may fail. For reliable path resolution that always points to the same directory as your source file, use `import.meta.url`: ```ts import { fileURLToPath } from 'node:url' import { serveStatic } from '@hono/node-server/serve-static' app.use( '/static/*', serveStatic({ root: fileURLToPath(new URL('./', import.meta.url)) }) ) ``` ::: Use the `path` option to serve `favicon.ico` in the directory root: ```ts app.use('/favicon.ico', serveStatic({ path: './favicon.ico' })) ``` If a request to the path `/hello.txt` or `/image.png` comes in and you want to return a file named `./static/hello.txt` or `./static/image.png`, you can use the following: ```ts app.use('*', serveStatic({ root: './static' })) ``` ### `rewriteRequestPath` If you want to map `http://localhost:3000/static/*` to `./statics`, you can use the `rewriteRequestPath` option: ```ts app.get( '/static/*', serveStatic({ root: './', rewriteRequestPath: (path) => path.replace(/^\/static/, '/statics'), }) ) ``` ## http2 You can run hono on a [Node.js http2 Server](https://nodejs.org/api/http2.html). ### unencrypted http2 ```ts import { createServer } from 'node:http2' const server = serve({ fetch: app.fetch, createServer, }) ``` ### encrypted http2 ```ts import { createSecureServer } from 'node:http2' import { readFileSync } from 'node:fs' const server = serve({ fetch: app.fetch, createServer: createSecureServer, serverOptions: { key: readFileSync('localhost-privkey.pem'), cert: readFileSync('localhost-cert.pem'), }, }) ``` ## Building & Deployment ::: code-group ```sh [npm] npm run build ``` ```sh [yarn] yarn run build ``` ```sh [pnpm] pnpm run build ``` ```sh [bun] bun run build ``` ::: info Apps with a front-end framework may need to use [Hono's Vite plugins](https://github.com/honojs/vite-plugins). ::: ### Dockerfile Here is an example of a Node.js Dockerfile. ```Dockerfile FROM node:22-alpine AS base FROM base AS builder RUN apk add --no-cache gcompat WORKDIR /app COPY package*json tsconfig.json src ./ RUN npm ci && \ npm run build && \ npm prune --production FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 hono COPY --from=builder --chown=hono:nodejs /app/node_modules /app/node_modules COPY --from=builder --chown=hono:nodejs /app/dist /app/dist COPY --from=builder --chown=hono:nodejs /app/package.json /app/package.json USER hono EXPOSE 3000 CMD ["node", "/app/dist/index.js"] ``` # Netlify Netlify provides static site hosting and serverless backend services. [Edge Functions](https://docs.netlify.com/edge-functions/overview/) enables us to make the web pages dynamic. Edge Functions support writing in Deno and TypeScript, and deployment is made easy through the [Netlify CLI](https://docs.netlify.com/cli/get-started/). With Hono, you can create the application for Netlify Edge Functions. ## 1. Setup A starter for Netlify is available. Start your project with "create-hono" command. Select `netlify` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move into `my-app`. ## 2. Hello World Edit `netlify/edge-functions/index.ts`: ```ts import { Hono } from 'jsr:@hono/hono' import { handle } from 'jsr:@hono/hono/netlify' const app = new Hono() app.get('/', (c) => { return c.text('Hello Hono!') }) export default handle(app) ``` ## 3. Run Run the development server with Netlify CLI. Then, access `http://localhost:8888` in your Web browser. ```sh netlify dev ``` ## 4. Deploy You can deploy with a `netlify deploy` command. ```sh netlify deploy --prod ``` ## `Context` You can access the Netlify's `Context` through `c.env`: ```ts import { Hono } from 'jsr:@hono/hono' import { handle } from 'jsr:@hono/hono/netlify' // Import the type definition import type { Context } from 'https://edge.netlify.com/' export type Env = { Bindings: { context: Context } } const app = new Hono() app.get('/country', (c) => c.json({ 'You are in': c.env.context.geo.country?.name, }) ) export default handle(app) ``` # Alibaba Cloud Function Compute [Alibaba Cloud Function Compute](https://www.alibabacloud.com/en/product/function-compute) is a fully managed, event-driven compute service. Function Compute allows you to focus on writing and uploading code without having to manage infrastructure such as servers. This guide uses a third-party adapter [rwv/hono-alibaba-cloud-fc3-adapter](https://github.com/rwv/hono-alibaba-cloud-fc3-adapter) to run Hono on Alibaba Cloud Function Compute. ## 1. Setup ::: code-group ```sh [npm] mkdir my-app cd my-app npm i hono hono-alibaba-cloud-fc3-adapter npm i -D @serverless-devs/s esbuild mkdir src touch src/index.ts ``` ```sh [yarn] mkdir my-app cd my-app yarn add hono hono-alibaba-cloud-fc3-adapter yarn add -D @serverless-devs/s esbuild mkdir src touch src/index.ts ``` ```sh [pnpm] mkdir my-app cd my-app pnpm add hono hono-alibaba-cloud-fc3-adapter pnpm add -D @serverless-devs/s esbuild mkdir src touch src/index.ts ``` ```sh [bun] mkdir my-app cd my-app bun add hono hono-alibaba-cloud-fc3-adapter bun add -D esbuild @serverless-devs/s mkdir src touch src/index.ts ``` ::: ## 2. Hello World Edit `src/index.ts`. ```ts import { Hono } from 'hono' import { handle } from 'hono-alibaba-cloud-fc3-adapter' const app = new Hono() app.get('/', (c) => c.text('Hello Hono!')) export const handler = handle(app) ``` ## 3. Setup serverless-devs > [serverless-devs](https://github.com/Serverless-Devs/Serverless-Devs) is an open source and open serverless developer platform dedicated to providing developers with a powerful tool chain system. Through this platform, developers can not only experience multi cloud serverless products with one click and rapidly deploy serverless projects, but also manage projects in the whole life cycle of serverless applications, and combine serverless devs with other tools / platforms very simply and quickly to further improve the efficiency of R & D, operation and maintenance. Add the Alibaba Cloud AccessKeyID & AccessKeySecret ```sh npx s config add # Please select a provider: Alibaba Cloud (alibaba) # Input your AccessKeyID & AccessKeySecret ``` Edit `s.yaml` ```yaml edition: 3.0.0 name: my-app access: 'default' vars: region: 'us-west-1' resources: my-app: component: fc3 props: region: ${vars.region} functionName: 'my-app' description: 'Hello World by Hono' runtime: 'nodejs20' code: ./dist handler: index.handler memorySize: 1024 timeout: 300 ``` Edit `scripts` section in `package.json`: ```json { "scripts": { "build": "esbuild --bundle --outfile=./dist/index.js --platform=node --target=node20 ./src/index.ts", "deploy": "s deploy -y" } } ``` ## 4. Deploy Finally, run the command to deploy: ```sh npm run build # Compile the TypeScript code to JavaScript npm run deploy # Deploy the function to Alibaba Cloud Function Compute ``` # AWS Lambda AWS Lambda is a serverless platform by Amazon Web Services. You can run your code in response to events and automatically manages the underlying compute resources for you. Hono works on AWS Lambda with the Node.js 18+ environment. ## 1. Setup When creating the application on AWS Lambda, [CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html) is useful to set up the functions such as IAM Role, API Gateway, and others. Initialize your project with the `cdk` CLI. ::: code-group ```sh [npm] mkdir my-app cd my-app cdk init app -l typescript npm i hono npm i -D esbuild mkdir lambda touch lambda/index.ts ``` ```sh [yarn] mkdir my-app cd my-app cdk init app -l typescript yarn add hono yarn add -D esbuild mkdir lambda touch lambda/index.ts ``` ```sh [pnpm] mkdir my-app cd my-app cdk init app -l typescript pnpm add hono pnpm add -D esbuild mkdir lambda touch lambda/index.ts ``` ```sh [bun] mkdir my-app cd my-app cdk init app -l typescript bun add hono bun add -D esbuild mkdir lambda touch lambda/index.ts ``` ::: ## 2. Hello World Edit `lambda/index.ts`. ```ts import { Hono } from 'hono' import { handle } from 'hono/aws-lambda' const app = new Hono() app.get('/', (c) => c.text('Hello Hono!')) export const handler = handle(app) ``` ## 3. Deploy Edit `lib/my-app-stack.ts`. ```ts import * as cdk from 'aws-cdk-lib' import { Construct } from 'constructs' import * as lambda from 'aws-cdk-lib/aws-lambda' import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs' export class MyAppStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props) const fn = new NodejsFunction(this, 'lambda', { entry: 'lambda/index.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_22_X, }) const fnUrl = fn.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }) new cdk.CfnOutput(this, 'lambdaUrl', { value: fnUrl.url!, }) } } ``` Finally, run the command to deploy: ```sh cdk deploy ``` ## Serve Binary data Hono supports binary data as a response. In Lambda, base64 encoding is required to return binary data. Once binary type is set to `Content-Type` header, Hono automatically encodes data to base64. ```ts app.get('/binary', async (c) => { // ... c.status(200) c.header('Content-Type', 'image/png') // means binary data return c.body(buffer) // supports `ArrayBufferLike` type, encoded to base64. }) ``` ## Access AWS Lambda Object In Hono, you can access the AWS Lambda Events and Context by binding the `LambdaEvent`, `LambdaContext` type and using `c.env` ```ts import { Hono } from 'hono' import type { LambdaEvent, LambdaContext } from 'hono/aws-lambda' import { handle } from 'hono/aws-lambda' type Bindings = { event: LambdaEvent lambdaContext: LambdaContext } const app = new Hono<{ Bindings: Bindings }>() app.get('/aws-lambda-info/', (c) => { return c.json({ isBase64Encoded: c.env.event.isBase64Encoded, awsRequestId: c.env.lambdaContext.awsRequestId, }) }) export const handler = handle(app) ``` ## Access RequestContext In Hono, you can access the AWS Lambda request context by binding the `LambdaEvent` type and using `c.env.event.requestContext`. ```ts import { Hono } from 'hono' import type { LambdaEvent } from 'hono/aws-lambda' import { handle } from 'hono/aws-lambda' type Bindings = { event: LambdaEvent } const app = new Hono<{ Bindings: Bindings }>() app.get('/custom-context/', (c) => { const lambdaContext = c.env.event.requestContext return c.json(lambdaContext) }) export const handler = handle(app) ``` ### Before v3.10.0 (deprecated) you can access the AWS Lambda request context by binding the `ApiGatewayRequestContext` type and using `c.env.` ```ts import { Hono } from 'hono' import type { ApiGatewayRequestContext } from 'hono/aws-lambda' import { handle } from 'hono/aws-lambda' type Bindings = { requestContext: ApiGatewayRequestContext } const app = new Hono<{ Bindings: Bindings }>() app.get('/custom-context/', (c) => { const lambdaContext = c.env.requestContext return c.json(lambdaContext) }) export const handler = handle(app) ``` ## Lambda response streaming By changing the invocation mode of AWS Lambda, you can achieve [Streaming Response](https://aws.amazon.com/blogs/compute/introducing-aws-lambda-response-streaming/). ```diff fn.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, + invokeMode: lambda.InvokeMode.RESPONSE_STREAM, }) ``` Typically, the implementation requires writing chunks to NodeJS.WritableStream using awslambda.streamifyResponse, but with the AWS Lambda Adaptor, you can achieve the traditional streaming response of Hono by using streamHandle instead of handle. ```ts import { Hono } from 'hono' import { streamHandle } from 'hono/aws-lambda' import { streamText } from 'hono/streaming' const app = new Hono() app.get('/stream', async (c) => { return streamText(c, async (stream) => { for (let i = 0; i < 3; i++) { await stream.writeln(`${i}`) await stream.sleep(1) } }) }) export const handler = streamHandle(app) ``` # Getting Started Using Hono is super easy. We can set up the project, write code, develop with a local server, and deploy quickly. The same code will work on any runtime, just with different entry points. Let's look at the basic usage of Hono. ## Starter Starter templates are available for each platform. Use the following "create-hono" command. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono@latest my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono@latest my-app ``` ::: Then you will be asked which template you would like to use. Let's select Cloudflare Workers for this example. ``` ? Which template do you want to use? aws-lambda bun cloudflare-pages ❯ cloudflare-workers deno fastly nextjs nodejs vercel ``` The template will be pulled into `my-app`, so go to it and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: Once the package installation is complete, run the following command to start up a local server. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm dev ``` ```sh [bun] bun run dev ``` ::: ## Hello World You can write code in TypeScript with the Cloudflare Workers development tool "Wrangler", Deno, Bun, or others without being aware of transpiling. Write your first application with Hono in `src/index.ts`. The example below is a starter Hono application. The `import` and the final `export default` parts may vary from runtime to runtime, but all of the application code will run the same code everywhere. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => { return c.text('Hello Hono!') }) export default app ``` Start the development server and access `http://localhost:8787` with your browser. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm dev ``` ```sh [bun] bun run dev ``` ::: ## Return JSON Returning JSON is also easy. The following is an example of handling a GET Request to `/api/hello` and returning an `application/json` Response. ```ts app.get('/api/hello', (c) => { return c.json({ ok: true, message: 'Hello Hono!', }) }) ``` ## Request and Response Getting a path parameter, URL query value, and appending a Response header is written as follows. ```ts app.get('/posts/:id', (c) => { const page = c.req.query('page') const id = c.req.param('id') c.header('X-Message', 'Hi!') return c.text(`You want to see ${page} of ${id}`) }) ``` We can easily handle POST, PUT, and DELETE not only GET. ```ts app.post('/posts', (c) => c.text('Created!', 201)) app.delete('/posts/:id', (c) => c.text(`${c.req.param('id')} is deleted!`) ) ``` ## Return HTML You can write HTML with [the html Helper](/docs/helpers/html) or using [JSX](/docs/guides/jsx) syntax. If you want to use JSX, rename the file to `src/index.tsx` and configure it (check with each runtime as it is different). Below is an example using JSX. ```tsx const View = () => { return (

Hello Hono!

) } app.get('/page', (c) => { return c.html() }) ``` ## Return raw Response You can also return the raw [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). ```ts app.get('/', () => { return new Response('Good morning!') }) ``` ## Using Middleware Middleware can do the hard work for you. For example, add in Basic Authentication. ```ts import { basicAuth } from 'hono/basic-auth' // ... app.use( '/admin/*', basicAuth({ username: 'admin', password: 'secret', }) ) app.get('/admin', (c) => { return c.text('You are authorized!') }) ``` There are useful built-in middleware including Bearer and authentication using JWT, CORS and ETag. Hono also provides third-party middleware using external libraries such as GraphQL Server and Firebase Auth. And, you can make your own middleware. ## Adapter There are Adapters for platform-dependent functions, e.g., handling static files or WebSocket. For example, to handle WebSocket in Cloudflare Workers, import `hono/cloudflare-workers`. ```ts import { upgradeWebSocket } from 'hono/cloudflare-workers' app.get( '/ws', upgradeWebSocket((c) => { // ... }) ) ``` ## Next step Most code will work on any platform, but there are guides for each. For instance, how to set up projects or how to deploy. Please see the page for the exact platform you want to use to create your application! # Service Worker [Service Worker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) is a script that runs in the background of the browser to handle tasks like caching and push notifications. Using a Service Worker adapter, you can run applications made with Hono as [FetchEvent](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent) handler within the browser. This page shows an example of creating a project using [Vite](https://vitejs.dev/). ## 1. Setup First, create and move to your project directory: ```sh mkdir my-app cd my-app ``` Create the necessary files for the project. Make a `package.json` file with the following: ```json { "name": "my-app", "private": true, "scripts": { "dev": "vite dev" }, "type": "module" } ``` Similarly, create a `tsconfig.json` file with the following: ```json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "lib": ["ES2020", "DOM", "WebWorker"], "moduleResolution": "bundler" }, "include": ["./"], "exclude": ["node_modules"] } ``` Next, install the necessary modules. ::: code-group ```sh [npm] npm i hono npm i -D vite ``` ```sh [yarn] yarn add hono yarn add -D vite ``` ```sh [pnpm] pnpm add hono pnpm add -D vite ``` ```sh [bun] bun add hono bun add -D vite ``` ::: ## 2. Hello World Edit `index.html`: ```html Hello World by Service Worker ``` `main.ts` is a script to register the Service Worker: ```ts function register() { navigator.serviceWorker .register('/sw.ts', { scope: '/sw', type: 'module' }) .then( function (_registration) { console.log('Register Service Worker: Success') }, function (_error) { console.log('Register Service Worker: Error') } ) } function start() { navigator.serviceWorker .getRegistrations() .then(function (registrations) { for (const registration of registrations) { console.log('Unregister Service Worker') registration.unregister() } register() }) } start() ``` In `sw.ts`, create an application using Hono and register it to the `fetch` event with the Service Worker adapter’s `handle` function. This allows the Hono application to intercept access to `/sw`. ```ts // To support types // https://github.com/microsoft/TypeScript/issues/14877 declare const self: ServiceWorkerGlobalScope import { Hono } from 'hono' import { handle } from 'hono/service-worker' const app = new Hono().basePath('/sw') app.get('/', (c) => c.text('Hello World')) self.addEventListener('fetch', handle(app)) ``` ### Using `fire()` The `fire()` function automatically calls `addEventListener('fetch', handle(app))` for you, making the code more concise. ```ts import { Hono } from 'hono' import { fire } from 'hono/service-worker' const app = new Hono().basePath('/sw') app.get('/', (c) => c.text('Hello World')) fire(app) ``` ## 3. Run Start the development server. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm run dev ``` ```sh [bun] bun run dev ``` ::: By default, the development server will run on port `5173`. Access `http://localhost:5173/` in your browser to complete the Service Worker registration. Then, access `/sw` to see the response from the Hono application. # Azure Functions [Azure Functions](https://azure.microsoft.com/en-us/products/functions) is a serverless platform from Microsoft Azure. You can run your code in response to events, and it automatically manages the underlying compute resources for you. Hono was not designed for Azure Functions at first, but with [Azure Functions Adapter](https://github.com/Marplex/hono-azurefunc-adapter), it can run on it as well. It works with Azure Functions **V4** running on Node.js 18 or above. ## 1. Install CLI To create an Azure Function, you must first install [Azure Functions Core Tools](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-typescript?pivots=nodejs-model-v4#install-the-azure-functions-core-tools). On macOS ```sh brew tap azure/functions brew install azure-functions-core-tools@4 ``` Follow this link for other OS: - [Install the Azure Functions Core Tools | Microsoft Learn](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-typescript?pivots=nodejs-model-v4#install-the-azure-functions-core-tools) ## 2. Setup Create a TypeScript Node.js V4 project in the current folder. ```sh func init --typescript ``` Change the default route prefix of the host. Add this property to the root json object of `host.json`: ```json "extensions": { "http": { "routePrefix": "" } } ``` ::: info The default Azure Functions route prefix is `/api`. If you don't change it as shown above, be sure to start all your Hono routes with `/api` ::: Now you are ready to install Hono and the Azure Functions Adapter with: ::: code-group ```sh [npm] npm i @marplex/hono-azurefunc-adapter hono ``` ```sh [yarn] yarn add @marplex/hono-azurefunc-adapter hono ``` ```sh [pnpm] pnpm add @marplex/hono-azurefunc-adapter hono ``` ```sh [bun] bun add @marplex/hono-azurefunc-adapter hono ``` ::: ## 3. Hello World Create `src/app.ts`: ```ts // src/app.ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Azure Functions!')) export default app ``` Create `src/functions/httpTrigger.ts`: ```ts // src/functions/httpTrigger.ts import { app } from '@azure/functions' import { azureHonoHandler } from '@marplex/hono-azurefunc-adapter' import honoApp from '../app' app.http('httpTrigger', { methods: [ //Add all your supported HTTP methods here 'GET', 'POST', 'DELETE', 'PUT', ], authLevel: 'anonymous', route: '{*proxy}', handler: azureHonoHandler(honoApp.fetch), }) ``` ## 4. Run Run the development server locally. Then, access `http://localhost:7071` in your Web browser. ::: code-group ```sh [npm] npm run start ``` ```sh [yarn] yarn start ``` ```sh [pnpm] pnpm start ``` ```sh [bun] bun run start ``` ::: ## 5. Deploy ::: info Before you can deploy to Azure, you need to create some resources in your cloud infrastructure. Please visit the Microsoft documentation on [Create supporting Azure resources for your function](https://learn.microsoft.com/en-us/azure/azure-functions/create-first-function-cli-typescript?pivots=nodejs-model-v4&tabs=windows%2Cazure-cli%2Cbrowser#create-supporting-azure-resources-for-your-function) ::: Build the project for deployment: ::: code-group ```sh [npm] npm run build ``` ```sh [yarn] yarn build ``` ```sh [pnpm] pnpm build ``` ```sh [bun] bun run build ``` ::: Deploy your project to the function app in Azure Cloud. Replace `` with the name of your app. ```sh func azure functionapp publish ``` # Lambda@Edge [Lambda@Edge](https://aws.amazon.com/lambda/edge/) is a serverless platform by Amazon Web Services. It allows you to run Lambda functions at Amazon CloudFront's edge locations, enabling you to customize behaviors for HTTP requests/responses. Hono supports Lambda@Edge with the Node.js 18+ environment. ## 1. Setup When creating the application on Lambda@Edge, [CDK](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk.html) is useful to set up the functions such as CloudFront, IAM Role, API Gateway, and others. Initialize your project with the `cdk` CLI. ::: code-group ```sh [npm] mkdir my-app cd my-app cdk init app -l typescript npm i hono mkdir lambda ``` ```sh [yarn] mkdir my-app cd my-app cdk init app -l typescript yarn add hono mkdir lambda ``` ```sh [pnpm] mkdir my-app cd my-app cdk init app -l typescript pnpm add hono mkdir lambda ``` ```sh [bun] mkdir my-app cd my-app cdk init app -l typescript bun add hono mkdir lambda ``` ::: ## 2. Hello World Edit `lambda/index_edge.ts`. ```ts import { Hono } from 'hono' import { handle } from 'hono/lambda-edge' const app = new Hono() app.get('/', (c) => c.text('Hello Hono on Lambda@Edge!')) export const handler = handle(app) ``` ## 3. Deploy Edit `bin/my-app.ts`. ```ts #!/usr/bin/env node import 'source-map-support/register' import * as cdk from 'aws-cdk-lib' import { MyAppStack } from '../lib/my-app-stack' const app = new cdk.App() new MyAppStack(app, 'MyAppStack', { env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: 'us-east-1', }, }) ``` Edit `lambda/cdk-stack.ts`. ```ts import { Construct } from 'constructs' import * as cdk from 'aws-cdk-lib' import * as cloudfront from 'aws-cdk-lib/aws-cloudfront' import * as origins from 'aws-cdk-lib/aws-cloudfront-origins' import * as lambda from 'aws-cdk-lib/aws-lambda' import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs' import * as s3 from 'aws-cdk-lib/aws-s3' export class MyAppStack extends cdk.Stack { public readonly edgeFn: lambda.Function constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props) const edgeFn = new NodejsFunction(this, 'edgeViewer', { entry: 'lambda/index_edge.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_20_X, }) // Upload any html const originBucket = new s3.Bucket(this, 'originBucket') new cloudfront.Distribution(this, 'Cdn', { defaultBehavior: { origin: new origins.S3Origin(originBucket), edgeLambdas: [ { functionVersion: edgeFn.currentVersion, eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST, }, ], }, }) } } ``` Finally, run the command to deploy: ```sh cdk deploy ``` ## Callback If you want to add Basic Auth and continue with request processing after verification, you can use `c.env.callback()` ```ts import { Hono } from 'hono' import { basicAuth } from 'hono/basic-auth' import type { Callback, CloudFrontRequest } from 'hono/lambda-edge' import { handle } from 'hono/lambda-edge' type Bindings = { callback: Callback request: CloudFrontRequest } const app = new Hono<{ Bindings: Bindings }>() app.get( '*', basicAuth({ username: 'hono', password: 'acoolproject', }) ) app.get('/', async (c, next) => { await next() c.env.callback(null, c.env.request) }) export const handler = handle(app) ``` # Next.js Next.js is a flexible React framework that gives you building blocks to create fast web applications. You can run Hono on Next.js when using the Node.js runtime.\ On Vercel, deploying Hono with Next.js is easy by using Vercel Functions. ## 1. Setup A starter for Next.js is available. Start your project with "create-hono" command. Select `nextjs` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move into `my-app` and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: ## 2. Hello World If you use the App Router, Edit `app/api/[[...route]]/route.ts`. Refer to the [Supported HTTP Methods](https://nextjs.org/docs/app/building-your-application/routing/route-handlers#supported-http-methods) section for more options. ```ts import { Hono } from 'hono' import { handle } from 'hono/vercel' const app = new Hono().basePath('/api') app.get('/hello', (c) => { return c.json({ message: 'Hello Next.js!', }) }) export const GET = handle(app) export const POST = handle(app) ``` ## 3. Run Run the development server locally. Then, access `http://localhost:3000` in your Web browser. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm dev ``` ```sh [bun] bun run dev ``` ::: Now, `/api/hello` just returns JSON, but if you build React UIs, you can create a full-stack application with Hono. ## 4. Deploy If you have a Vercel account, you can deploy by linking the Git repository. ## Pages Router If you use the Pages Router, you'll need to install the Node.js adapter first. ::: code-group ```sh [npm] npm i @hono/node-server ``` ```sh [yarn] yarn add @hono/node-server ``` ```sh [pnpm] pnpm add @hono/node-server ``` ```sh [bun] bun add @hono/node-server ``` ::: Then, you can utilize the `handle` function imported from `@hono/node-server/vercel` in `pages/api/[[...route]].ts`. ```ts import { Hono } from 'hono' import { handle } from '@hono/node-server/vercel' import type { PageConfig } from 'next' export const config: PageConfig = { api: { bodyParser: false, }, } const app = new Hono().basePath('/api') app.get('/hello', (c) => { return c.json({ message: 'Hello Next.js!', }) }) export default handle(app) ``` In order for this to work with the Pages Router, it's important to disable Vercel Node.js helpers by setting up an environment variable in your project dashboard or in your `.env` file. ```text NODEJS_HELPERS=0 ``` # Fastly Compute [Fastly Compute](https://www.fastly.com/products/edge-compute) is an advanced edge computing system that runs your code, in your favorite language, on Fastly's global edge network. Hono also works on Fastly Compute. You can develop the application locally and publish it with a few commands using [Fastly CLI](https://www.fastly.com/documentation/reference/tools/cli/), which is installed locally automatically as part of the template. ## 1. Setup A starter for Fastly Compute is available. Start your project with "create-hono" command. Select `fastly` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move to `my-app` and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: ## 2. Hello World Edit `src/index.ts`: ```ts // src/index.ts import { Hono } from 'hono' import { fire } from '@fastly/hono-fastly-compute' const app = new Hono() app.get('/', (c) => c.text('Hello Fastly!')) fire(app) ``` > [!NOTE] > When using `fire` (or `buildFire()`) from `@fastly/hono-fastly-compute'` at the top level of your application, it is suitable to use `Hono` from `'hono'` rather than `'hono/quick'`, because `fire` causes its router to build its internal data during the application initialization phase. ## 3. Run Run the development server locally. Then, access `http://localhost:7676` in your Web browser. ::: code-group ```sh [npm] npm run start ``` ```sh [yarn] yarn start ``` ```sh [pnpm] pnpm run start ``` ```sh [bun] bun run start ``` ::: ## 4. Deploy To build and deploy your application to your Fastly account, type the following command. The first time you deploy the application, you will be prompted to create a new service in your account. If you don't have an account yet, you must [create your Fastly account](https://www.fastly.com/signup/). ::: code-group ```sh [npm] npm run deploy ``` ```sh [yarn] yarn deploy ``` ```sh [pnpm] pnpm run deploy ``` ```sh [bun] bun run deploy ``` ::: ## Bindings In Fastly Compute, you can bind Fastly platform resources, such as KV Stores, Config Stores, Secret Stores, Backends, Access Control Lists, Named Log Streams, and Environment Variables. You can access them through `c.env`, and will have their individual SDK types. To use these bindings, import `buildFire` instead of `fire` from `@fastly/hono-fastly-compute`. Define your [bindings](https://github.com/fastly/compute-js-context?tab=readme-ov-file#typed-bindings-with-buildcontextproxy) and pass them to [`buildFire()`](https://github.com/fastly/hono-fastly-compute?tab=readme-ov-file#basic-example) to obtain `fire`. Then use `fire.Bindings` to define your `Env` type as you construct `Hono`. ```ts // src/index.ts import { buildFire } from '@fastly/hono-fastly-compute' const fire = buildFire({ siteData: 'KVStore:site-data', // I have a KV Store named "site-data" }) const app = new Hono<{ Bindings: typeof fire.Bindings }>() app.put('/upload/:key', async (c, next) => { // e.g., Access the KV Store const key = c.req.param('key') await c.env.siteData.put(key, c.req.body) return c.text(`Put ${key} successfully!`) }) fire(app) ``` # Google Cloud Run [Google Cloud Run](https://cloud.google.com/run) is a serverless platform built by Google Cloud. You can run your code in response to events and Google automatically manages the underlying compute resources for you. Google Cloud Run uses containers to run your service. This means you can use any runtime you like (E.g., Deno or Bun) by providing a Dockerfile. If no Dockerfile is provided Google Cloud Run will use the default Node.js buildpack. This guide assumes you already have a Google Cloud account and a billing account. ## 1. Install the CLI When working with Google Cloud Platform, it is easiest to work with the [gcloud CLI](https://cloud.google.com/sdk/docs/install). For example, on MacOS using Homebrew: ```sh brew install --cask gcloud-cli ``` Authenticate with the CLI. ```sh gcloud auth login ``` ## 2. Project setup Create a project. Accept the auto-generated project ID at the prompt. ```sh gcloud projects create --set-as-default --name="my app" ``` Create environment variables for your project ID and project number for easy reuse. It may take ~30 seconds before the project successfully returns with the `gcloud projects list` command. ```sh PROJECT_ID=$(gcloud projects list \ --format='value(projectId)' \ --filter='name="my app"') PROJECT_NUMBER=$(gcloud projects list \ --format='value(projectNumber)' \ --filter='name="my app"') echo $PROJECT_ID $PROJECT_NUMBER ``` Find your billing account ID. ```sh gcloud billing accounts list ``` Add your billing account from the prior command to the project. ```sh gcloud billing projects link $PROJECT_ID \ --billing-account=[billing_account_id] ``` Enable the required APIs. ```sh gcloud services enable run.googleapis.com \ cloudbuild.googleapis.com ``` Update the service account permissions to have access to Cloud Build. ```sh gcloud projects add-iam-policy-binding $PROJECT_ID \ --member=serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role=roles/run.builder ``` ## 3. Hello World Start your project with "create-hono" command. Select `nodejs`. ```sh npm create hono@latest my-app ``` Move to `my-app` and install the dependencies. ```sh cd my-app npm i ``` Update the port in `src/index.ts` to be `8080`. ```ts import { serve } from '@hono/node-server' import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => { return c.text('Hello Hono!') }) serve({ fetch: app.fetch, port: 3000 // [!code --] port: 8080 // [!code ++] }, (info) => { console.log(`Server is running on http://localhost:${info.port}`) }) ``` Run the development server locally. Then, access http://localhost:8080 in your Web browser. ```sh npm run dev ``` ## 4. Deploy Start the deployment and follow the interactive prompts (E.g., select a region). ```sh gcloud run deploy my-app --source . --allow-unauthenticated ``` ## Changing runtimes If you want to deploy using Deno or Bun runtimes (or a customised Nodejs container), add a `Dockerfile` (and optionally `.dockerignore`) with your desired environment. For information on containerizing, please refer to: - [Node.js](/docs/getting-started/nodejs#building-deployment) - [Bun](https://bun.com/guides/ecosystem/docker) - [Deno](https://docs.deno.com/examples/google_cloud_run_tutorial) # WebAssembly (w/ WASI) [WebAssembly][wasm-core] is a secure, sandboxed, portable runtime that runs inside and outside web browsers. In practice: - Languages (like JavaScript) _compile to_ WebAssembly (`.wasm` files) - WebAssembly runtimes (like [`wasmtime`][wasmtime] or [`jco`][jco]) enable _running_ WebAssembly binaries While core WebAssembly has _no_ access to things like the local filesystem or sockets, the [WebAssembly System Interface][wasi] steps in to enable defining a platform under WebAssebly workloads. This means that _with_ WASI, WebAssembly can operate on files, sockets, and much more. ::: info Want to peek at the WASI interface yourself? check out [`wasi:http`][wasi-http] ::: Support for WebAssembly w/ WASI in JS is powered by [StarlingMonkey][sm], and thanks to the focus on Web standards in both StarlingMonkey and Hono, **Hono works \*out of the box with WASI-enabled WebAssembly ecosystems.** [sm]: https://github.com/bytecodealliance/StarlingMonkey [wasm-core]: https://webassembly.org/ [wasi]: https://wasi.dev/ [bca]: https://bytecodealliance.org/ [wasi-http]: https://github.com/WebAssembly/wasi-http ## 1. Setup The WebAssembly JS ecosystem provides tooling to make it easy to get started building WASI-enabled WebAssembly components: - [StarlingMonkey][sm] is a fork of [SpiderMonkey][spidermonkey] that compiles to WebAssembly and enables components - [`componentize-js`][componentize-js] turns JavaScript ES modules into WebAssembly components - [`jco`][jco] is a multi-tool that builds components, generates types, and runs components in environments like Node.js or the browser ::: info WebAssembly has an open ecosystem and is open source, with core projects stewarded primarily by the [Bytecode Alliance][bca] and its members. New features, issues, pull requests and other types of contributions are always welcome. ::: While a starter for Hono on WebAssembly is not yet available, you can start a WebAssembly Hono project just like any other: ::: code-group ```sh [npm] mkdir my-app cd my-app npm init npm i hono npm i -D @bytecodealliance/jco @bytecodealliance/componentize-js @bytecodealliance/jco-std npm i -D rolldown ``` ````sh [yarn] mkdir my-app cd my-app npm init yarn add hono yarn add -D @bytecodealliance/jco @bytecodealliance/componentize-js @bytecodealliance/jco-std yarn add -D rolldown G``` ```sh [pnpm] mkdir my-app cd my-app pnpm init --init-type module pnpm add hono pnpm add -D @bytecodealliance/jco @bytecodealliance/componentize-js @bytecodealliance/jco-std pnpm add -D rolldown ```` ```sh [bun] mkdir my-app cd my-app npm init bun add hono bun add -D @bytecodealliance/jco @bytecodealliance/componentize-js @bytecodealliance/jco-std ``` ::: ::: info To ensure your project uses ES modules, ensure `type` is set to `"module"` in `package.json` ::: After entering the `my-app` folder, install dependencies, and initialize TypeScript: ::: code-group ```sh [npm] npm i npx tsc --init ``` ```sh [yarn] yarn yarn tsc --init ``` ```sh [pnpm] pnpm i pnpm exec --init ``` ```sh [bun] bun i ``` ::: Once you have a basic TypeScript configuration file (`tsconfig.json`), please ensure it has the following configuration: - `compilerOptions.module` set to `"nodenext"` Since `componentize-js` (and `jco` which re-uses it) supports only single JS files, bundling is necessary, so [`rolldown`][rolldown] can be used to create a single file bundle. A Rolldown configuration (`rolldown.config.mjs`) like the following can be used: ```js import { defineConfig } from 'rolldown' export default defineConfig({ input: 'src/component.ts', external: /wasi:.*/, output: { file: 'dist/component.js', format: 'esm', }, }) ``` ::: info Feel free to use any other bundlers that you're more comfortable with (`rolldown`, `esbuild`, `rollup`, etc) ::: [jco]: https://github.com/bytecodealliance/jco [componentize-js]: https://github.com/bytecodealliance/componentize-js [rolldown]: https://rolldown.rs [spidermonkey]: https://spidermonkey.dev/ ## 2. Set up WIT interface & dependencies [WebAssembly Inteface Types (WIT)][wit] is an Interface Definition Language ("IDL") that governs what functionality a WebAssembly component uses ("imports"), and what it provides ("exports"). Amongst the standardized WIT interfaces, [`wasi:http`][wasi-http] is for dealing with HTTP requests (whether it's receiving them or sending them out), and since we intend to make a web server, our component must declare the use of `wasi:http/incoming-handler` in it's [WIT world][wit-world]: First, let's set up the component's WIT world in a file called `wit/component.wit`: ```txt package example:hono; world component { export wasi:http/incoming-handler@0.2.6; } ``` Put simply, the WIT file above means that our component "providers" the functionality of "receiving"/"handling incoming" HTTP requests. The `wasi:http/incoming-handler` interface relies on upstream standardized WIT interfaces (specifications on how requests are structured, etc). To pull those third party (Bytecode Alliance maintained) WIT interaces, one tool we can use is [`wkg`][wkg]: ```sh wkg wit fetch ``` Once `wkg` has finished running, you should find your `wit` folder populated with a new `deps` folder alongside `component.wit`: ``` wit β”œβ”€β”€ component.wit └── deps β”œβ”€β”€ wasi-cli-0.2.6 β”‚Β Β  └── package.wit β”œβ”€β”€ wasi-clocks-0.2.6 β”‚Β Β  └── package.wit β”œβ”€β”€ wasi-http-0.2.6 β”‚Β Β  └── package.wit β”œβ”€β”€ wasi-io-0.2.6 β”‚Β Β  └── package.wit └── wasi-random-0.2.6 └── package.wit ``` [wkg]: https://github.com/bytecodealliance/wasm-pkg-tools [wit-world]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md#wit-worlds [wit]: https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md ## 3. Hello Wasm To build a HTTP server in WebAssembly, we can make use of the [`jco-std`][jco-std] project, which contains helpers that make the experience very similar to the standard Hono experience. Let's fulfill our `component` world with a basic Hono application as a WebAssembly component in a file called `src/component.ts`: ```ts import { Hono } from 'hono' import { fire } from '@bytecodealliance/jco-std/wasi/0.2.6/http/adapters/hono/server' const app = new Hono() app.get('/hello', (c) => { return c.json({ message: 'Hello from WebAssembly!' }) }) fire(app) // Although we've called `fire()` with wasi HTTP configured for use above, // we still need to actually export the `wasi:http/incoming-handler` interface object, // as jco and componentize-js will be looking for the ES module export that matches the WASI interface. export { incomingHandler } from '@bytecodealliance/jco-std/wasi/0.2.6/http/adapters/hono/server' ``` ## 4. Build Since we're using Rolldown (and it's configured to handle TypeScript compilation), we can use it to build and bundle: ::: code-group ```sh [npm] npx rolldown -c ``` ```sh [yarn] yarn rolldown -c ``` ```sh [pnpm] pnpm exec rolldown -c ``` ```sh [bun] bun build --target=bun --outfile=dist/component.js ./src/component.ts ``` ::: ::: info The bundling step is necessary because WebAssembly JS ecosystem tooling only currently supports a single JS file, and we'd like to include Hono along with related libraries. For components with simpler requirements, bundlers are not necessary. ::: To build your WebAssembly component, use `jco` (and indirectly `componentize-js`): ::: code-group ```sh [npm] npx jco componentize -w wit -o dist/component.wasm dist/component.js ``` ```sh [yarn] yarn jco componentize -w wit -o dist/component.wasm dist/component.js ``` ```sh [pnpm] pnpm exec jco componentize -w wit -o dist/component.wasm dist/component.js ``` ```sh [bun] bun run jco componentize -w wit -o dist/component.wasm dist/component.js ``` ::: ## 5. Run To run your Hono WebAssembly HTTP server, you can use any WASI-enabled WebAssembly runtime: - [`wasmtime`][wasmtime] - `jco` (runs in Node.js) In this guide, we'll use `jco serve` since it's already installed. ::: warning `jco serve` is meant for development, and is not recommended for production use. ::: [wasmtime]: https://wasmtime.dev ::: code-group ```sh [npm] npx jco serve dist/component.wasm ``` ```sh [yarn] yarn jco serve dist/component.wasm ``` ```sh [pnpm] pnpm exec jco serve dist/component.wasm ``` ```sh [bun] bun run jco serve dist/component.wasm ``` ::: You should see output like the following: ``` $ npx jco serve dist/component.wasm Server listening @ localhost:8000... ``` Sending a request to `localhost:8000/hello` will produce the JSON output you've specified in your Hono application. You should see output like the following: ```json { "message": "Hello from WebAssembly!" } ``` ::: info `jco serve` works by converting the WebAssembly component into a basic WebAssembly coremodule, so that it can be run in runtimes like Node.js and the browser. This process is normally run via `jco transpile`, and is the way we can use JS engines like Node.js and the browser (which may use V8 or other Javascript engines) as WebAssembly Component runtimes. How `jco transpile` is outside the scope of this guide, you can read more about it in [the Jco book][jco-book] ::: ## More information To learn more about WASI, WebAssembly components and more, see the following resources: - [BytecodeAlliance Component Model book][cm-book] - [`jco` codebase][jco] - [`jco` example components][jco-example-components] (in particular the [Hono example][jco-example-component-hono]) - [Jco book][jco-book] - [`componentize-js` codebase][componentize-js] - [StarlingMonkey codebase][sm] To reach out to the WebAssembly community with questions, comments, contributions or to file issues: - [Bytecode Alliance Zulip](https://bytecodealliance.zulipchat.com) (consider posting in the [#jco channel](https://bytecodealliance.zulipchat.com/#narrow/channel/409526-jco)) - [Jco repository](https://github.com/bytecodealliance/jco) - [componentize-js repository](https://github.com/bytecodealliance/componentize-js) [cm-book]: https://component-model.bytecodealliance.org/ [jco-book]: https://bytecodealliance.github.io/jco/ [jco-example-components]: https://github.com/bytecodealliance/jco/tree/main/examples/components [jco-example-component-hono]: https://github.com/bytecodealliance/jco/tree/main/examples/components/http-server-hono # Cloudflare Pages [Cloudflare Pages](https://pages.cloudflare.com) is an edge platform for full-stack web applications. It serves static files and dynamic content provided by Cloudflare Workers. Hono fully supports Cloudflare Pages. It introduces a delightful developer experience. Vite's dev server is fast, and deploying with Wrangler is super quick. ## 1. Setup A starter for Cloudflare Pages is available. Start your project with "create-hono" command. Select `cloudflare-pages` template for this example. ::: code-group ```sh [npm] npm create hono@latest my-app ``` ```sh [yarn] yarn create hono my-app ``` ```sh [pnpm] pnpm create hono my-app ``` ```sh [bun] bun create hono@latest my-app ``` ```sh [deno] deno init --npm hono my-app ``` ::: Move into `my-app` and install the dependencies. ::: code-group ```sh [npm] cd my-app npm i ``` ```sh [yarn] cd my-app yarn ``` ```sh [pnpm] cd my-app pnpm i ``` ```sh [bun] cd my-app bun i ``` ::: Below is a basic directory structure. ```text ./ β”œβ”€β”€ package.json β”œβ”€β”€ public β”‚Β Β  └── static // Put your static files. β”‚Β Β  └── style.css // You can refer to it as `/static/style.css`. β”œβ”€β”€ src β”‚Β Β  β”œβ”€β”€ index.tsx // The entry point for server-side. β”‚Β Β  └── renderer.tsx β”œβ”€β”€ tsconfig.json └── vite.config.ts ``` ## 2. Hello World Edit `src/index.tsx` like the following: ```tsx import { Hono } from 'hono' import { renderer } from './renderer' const app = new Hono() app.get('*', renderer) app.get('/', (c) => { return c.render(

Hello, Cloudflare Pages!

) }) export default app ``` ## 3. Run Run the development server locally. Then, access `http://localhost:5173` in your Web browser. ::: code-group ```sh [npm] npm run dev ``` ```sh [yarn] yarn dev ``` ```sh [pnpm] pnpm dev ``` ```sh [bun] bun run dev ``` ::: ## 4. Deploy If you have a Cloudflare account, you can deploy to Cloudflare. In `package.json`, `$npm_execpath` needs to be changed to your package manager of choice. ::: code-group ```sh [npm] npm run deploy ``` ```sh [yarn] yarn deploy ``` ```sh [pnpm] pnpm run deploy ``` ```sh [bun] bun run deploy ``` ::: ### Deploy via the Cloudflare dashboard with GitHub 1. Log in to the [Cloudflare dashboard](https://dash.cloudflare.com) and select your account. 2. In Account Home, select Workers & Pages > Create application > Pages > Connect to Git. 3. Authorize your GitHub account, and select the repository. In Set up builds and deployments, provide the following information: | Configuration option | Value | | -------------------- | --------------- | | Production branch | `main` | | Build command | `npm run build` | | Build directory | `dist` | ## Bindings You can use Cloudflare Bindings like Variables, KV, D1, and others. In this section, let's use Variables and KV. ### Create `wrangler.toml` First, create `wrangler.toml` for local Bindings: ```sh touch wrangler.toml ``` Edit `wrangler.toml`. Specify Variable with the name `MY_NAME`. ```toml [vars] MY_NAME = "Hono" ``` ### Create KV Next, make the KV. Run the following `wrangler` command: ```sh wrangler kv namespace create MY_KV --preview ``` Note down the `preview_id` as the following output: ``` { binding = "MY_KV", preview_id = "abcdef" } ``` Specify `preview_id` with the name of Bindings, `MY_KV`: ```toml [[kv_namespaces]] binding = "MY_KV" id = "abcdef" ``` ### Edit `vite.config.ts` Edit the `vite.config.ts`: ```ts import devServer from '@hono/vite-dev-server' import adapter from '@hono/vite-dev-server/cloudflare' import build from '@hono/vite-cloudflare-pages' import { defineConfig } from 'vite' export default defineConfig({ plugins: [ devServer({ entry: 'src/index.tsx', adapter, // Cloudflare Adapter }), build(), ], }) ``` ### Use Bindings in your application Use Variable and KV in your application. Set the types. ```ts type Bindings = { MY_NAME: string MY_KV: KVNamespace } const app = new Hono<{ Bindings: Bindings }>() ``` Use them: ```tsx app.get('/', async (c) => { await c.env.MY_KV.put('name', c.env.MY_NAME) const name = await c.env.MY_KV.get('name') return c.render(

Hello! {name}

) }) ``` ### In production For Cloudflare Pages, you will use `wrangler.toml` for local development, but for production, you will set up Bindings in the dashboard. ## Client-side You can write client-side scripts and import them into your application using Vite's features. If `/src/client.ts` is the entry point for the client, simply write it in the script tag. Additionally, `import.meta.env.PROD` is useful for detecting whether it's running on a dev server or in the build phase. ```tsx app.get('/', (c) => { return c.html( {import.meta.env.PROD ? ( ) : ( )}

Hello

) }) ``` In order to build the script properly, you can use the example config file `vite.config.ts` as shown below. ```ts import pages from '@hono/vite-cloudflare-pages' import devServer from '@hono/vite-dev-server' import { defineConfig } from 'vite' export default defineConfig(({ mode }) => { if (mode === 'client') { return { build: { rollupOptions: { input: './src/client.ts', output: { entryFileNames: 'static/client.js', }, }, }, } } else { return { plugins: [ pages(), devServer({ entry: 'src/index.tsx', }), ], } } }) ``` You can run the following command to build the server and client script. ```sh vite build --mode client && vite build ``` ## Cloudflare Pages Middleware Cloudflare Pages uses its own [middleware](https://developers.cloudflare.com/pages/functions/middleware/) system that is different from Hono's middleware. You can enable it by exporting `onRequest` in a file named `_middleware.ts` like this: ```ts // functions/_middleware.ts export async function onRequest(pagesContext) { console.log(`You are accessing ${pagesContext.request.url}`) return await pagesContext.next() } ``` Using `handleMiddleware`, you can use Hono's middleware as Cloudflare Pages middleware. ```ts // functions/_middleware.ts import { handleMiddleware } from 'hono/cloudflare-pages' export const onRequest = handleMiddleware(async (c, next) => { console.log(`You are accessing ${c.req.url}`) await next() }) ``` You can also use built-in and 3rd party middleware for Hono. For example, to add Basic Authentication, you can use [Hono's Basic Authentication Middleware](/docs/middleware/builtin/basic-auth). ```ts // functions/_middleware.ts import { handleMiddleware } from 'hono/cloudflare-pages' import { basicAuth } from 'hono/basic-auth' export const onRequest = handleMiddleware( basicAuth({ username: 'hono', password: 'acoolproject', }) ) ``` If you want to apply multiple middleware, you can write it like this: ```ts import { handleMiddleware } from 'hono/cloudflare-pages' // ... export const onRequest = [ handleMiddleware(middleware1), handleMiddleware(middleware2), handleMiddleware(middleware3), ] ``` ### Accessing `EventContext` You can access [`EventContext`](https://developers.cloudflare.com/pages/functions/api-reference/#eventcontext) object via `c.env` in `handleMiddleware`. ```ts // functions/_middleware.ts import { handleMiddleware } from 'hono/cloudflare-pages' export const onRequest = [ handleMiddleware(async (c, next) => { c.env.eventContext.data.user = 'Joe' await next() }), ] ``` Then, you can access the data value in via `c.env.eventContext` in the handler: ```ts // functions/api/[[route]].ts import type { EventContext } from 'hono/cloudflare-pages' import { handle } from 'hono/cloudflare-pages' // ... type Env = { Bindings: { eventContext: EventContext } } const app = new Hono().basePath('/api') app.get('/hello', (c) => { return c.json({ message: `Hello, ${c.env.eventContext.data.user}!`, // 'Joe' }) }) export const onRequest = handle(app) ``` # Dev Helper Dev Helper provides useful methods you can use in development. ```ts import { Hono } from 'hono' import { getRouterName, showRoutes } from 'hono/dev' ``` ## `getRouterName()` You can get the name of the currently used router with `getRouterName()`. ```ts const app = new Hono() // ... console.log(getRouterName(app)) ``` ## `showRoutes()` `showRoutes()` function displays the registered routes in your console. Consider an application like the following: ```ts const app = new Hono().basePath('/v1') app.get('/posts', (c) => { // ... }) app.get('/posts/:id', (c) => { // ... }) app.post('/posts', (c) => { // ... }) showRoutes(app, { verbose: true, }) ``` When this application starts running, the routes will be shown in your console as follows: ```txt GET /v1/posts GET /v1/posts/:id POST /v1/posts ``` ## Options ### verbose: `boolean` When set to `true`, it displays verbose information. ### colorize: `boolean` When set to `false`, the output will not be colored. # Route Helper The Route Helper provides enhanced routing information for debugging and middleware development. It allows you to access detailed information about matched routes and the current route being processed. ## Import ```ts import { Hono } from 'hono' import { matchedRoutes, routePath, baseRoutePath, basePath, } from 'hono/route' ``` ## Usage ### Basic route information ```ts const app = new Hono() app.get('/posts/:id', (c) => { const currentPath = routePath(c) // '/posts/:id' const routes = matchedRoutes(c) // Array of matched routes return c.json({ path: currentPath, totalRoutes: routes.length, }) }) ``` ### Working with sub-applications ```ts const app = new Hono() const apiApp = new Hono() apiApp.get('/posts/:id', (c) => { return c.json({ routePath: routePath(c), // '/posts/:id' baseRoutePath: baseRoutePath(c), // '/api' basePath: basePath(c), // '/api' (with actual params) }) }) app.route('/api', apiApp) ``` ## `matchedRoutes()` Returns an array of all routes that matched the current request, including middleware. ```ts app.all('/api/*', (c, next) => { console.log('API middleware') return next() }) app.get('/api/users/:id', (c) => { const routes = matchedRoutes(c) // Returns: [ // { method: 'ALL', path: '/api/*', handler: [Function] }, // { method: 'GET', path: '/api/users/:id', handler: [Function] } // ] return c.json({ routes: routes.length }) }) ``` ## `routePath()` Returns the route path pattern registered for the current handler. ```ts app.get('/posts/:id', (c) => { console.log(routePath(c)) // '/posts/:id' return c.text('Post details') }) ``` ### Using with index parameter You can optionally pass an index parameter to get the route path at a specific position, similar to `Array.prototype.at()`. ```ts app.all('/api/*', (c, next) => { return next() }) app.get('/api/users/:id', (c) => { console.log(routePath(c, 0)) // '/api/*' (first matched route) console.log(routePath(c, -1)) // '/api/users/:id' (last matched route) return c.text('User details') }) ``` ## `baseRoutePath()` Returns the base path pattern of the current route as specified in routing. ```ts const subApp = new Hono() subApp.get('/posts/:id', (c) => { return c.text(baseRoutePath(c)) // '/:sub' }) app.route('/:sub', subApp) ``` ### Using with index parameter You can optionally pass an index parameter to get the base route path at a specific position, similar to `Array.prototype.at()`. ```ts app.all('/api/*', (c, next) => { return next() }) const subApp = new Hono() subApp.get('/users/:id', (c) => { console.log(baseRoutePath(c, 0)) // '/' (first matched route) console.log(baseRoutePath(c, -1)) // '/api' (last matched route) return c.text('User details') }) app.route('/api', subApp) ``` ## `basePath()` Returns the base path with embedded parameters from the actual request. ```ts const subApp = new Hono() subApp.get('/posts/:id', (c) => { return c.text(basePath(c)) // '/api' (for request to '/api/posts/123') }) app.route('/:sub', subApp) ``` # Proxy Helper Proxy Helper provides useful functions when using Hono application as a (reverse) proxy. ## Import ```ts import { Hono } from 'hono' import { proxy } from 'hono/proxy' ``` ## `proxy()` `proxy()` is a `fetch()` API wrapper for proxy. The parameters and return value are the same as for `fetch()` (except for the proxy-specific options). The `Accept-Encoding` header is replaced with an encoding that the current runtime can handle. Unnecessary response headers are removed, and a `Response` object is returned that can be sent from the handler. ### Examples Simple usage: ```ts app.get('/proxy/:path', (c) => { return proxy(`http://${originServer}/${c.req.param('path')}`) }) ``` Complicated usage: ```ts app.get('/proxy/:path', async (c) => { const res = await proxy( `http://${originServer}/${c.req.param('path')}`, { headers: { ...c.req.header(), // optional, specify only when forwarding all the request data (including credentials) is necessary. 'X-Forwarded-For': '127.0.0.1', 'X-Forwarded-Host': c.req.header('host'), Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization') }, } ) res.headers.delete('Set-Cookie') return res }) ``` Or you can pass the `c.req` as a parameter. ```ts app.all('/proxy/:path', (c) => { return proxy(`http://${originServer}/${c.req.param('path')}`, { ...c.req, // optional, specify only when forwarding all the request data (including credentials) is necessary. headers: { ...c.req.header(), 'X-Forwarded-For': '127.0.0.1', 'X-Forwarded-Host': c.req.header('host'), Authorization: undefined, // do not propagate request headers contained in c.req.header('Authorization') }, }) }) ``` You can override the default global `fetch` function with the `customFetch` option: ```ts app.get('/proxy', (c) => { return proxy('https://example.com/', { customFetch, }) }) ``` ### Connection Header Processing By default, `proxy()` ignores the `Connection` header to prevent Hop-by-Hop Header Injection attacks. You can enable strict RFC 9110 compliance with the `strictConnectionProcessing` option: ```ts // Default behavior (recommended for untrusted clients) app.get('/proxy/:path', (c) => { return proxy(`http://${originServer}/${c.req.param('path')}`, c.req) }) // Strict RFC 9110 compliance (use only in trusted environments) app.get('/internal-proxy/:path', (c) => { return proxy(`http://${internalServer}/${c.req.param('path')}`, { ...c.req, strictConnectionProcessing: true, }) }) ``` ### `ProxyFetch` The type of `proxy()` is defined as `ProxyFetch` and is as follows ```ts interface ProxyRequestInit extends Omit { raw?: Request customFetch?: (request: Request) => Promise strictConnectionProcessing?: boolean headers?: | HeadersInit | [string, string][] | Record | Record } interface ProxyFetch { ( input: string | URL | Request, init?: ProxyRequestInit ): Promise } ``` # Accepts Helper Accepts Helper helps to handle Accept headers in the Requests. ## Import ```ts import { Hono } from 'hono' import { accepts } from 'hono/accepts' ``` ## `accepts()` The `accepts()` function looks at the Accept header, such as Accept-Encoding and Accept-Language, and returns the proper value. ```ts import { accepts } from 'hono/accepts' app.get('/', (c) => { const accept = accepts(c, { header: 'Accept-Language', supports: ['en', 'ja', 'zh'], default: 'en', }) return c.json({ lang: accept }) }) ``` ### `AcceptHeader` type The definition of the `AcceptHeader` type is as follows. ```ts export type AcceptHeader = | 'Accept' | 'Accept-Charset' | 'Accept-Encoding' | 'Accept-Language' | 'Accept-Patch' | 'Accept-Post' | 'Accept-Ranges' ``` ## Options ### header: `AcceptHeader` The target accept header. ### supports: `string[]` The header values which your application supports. ### default: `string` The default values. ### match: `(accepts: Accept[], config: acceptsConfig) => string` The custom match function. # Adapter Helper The Adapter Helper provides a seamless way to interact with various platforms through a unified interface. ## Import ```ts import { Hono } from 'hono' import { env, getRuntimeKey } from 'hono/adapter' ``` ## `env()` The `env()` function facilitates retrieving environment variables across different runtimes, extending beyond just Cloudflare Workers' Bindings. The value that can be retrieved with `env(c)` may be different for each runtimes. ```ts import { env } from 'hono/adapter' app.get('/env', (c) => { // NAME is process.env.NAME on Node.js or Bun // NAME is the value written in `wrangler.toml` on Cloudflare const { NAME } = env<{ NAME: string }>(c) return c.text(NAME) }) ``` Supported Runtimes, Serverless Platforms and Cloud Services: - Cloudflare Workers - `wrangler.toml` - `wrangler.jsonc` - Deno - [`Deno.env`](https://docs.deno.com/runtime/manual/basics/env_variables) - `.env` file - Bun - [`Bun.env`](https://bun.com/guides/runtime/set-env) - `process.env` - Node.js - `process.env` - Vercel - [Environment Variables on Vercel](https://vercel.com/docs/projects/environment-variables) - AWS Lambda - [Environment Variables on AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/samples-blank.html#samples-blank-architecture) - Lambda@Edge\ Environment Variables on Lambda are [not supported](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/add-origin-custom-headers.html) by Lambda@Edge, you need to use [Lamdba@Edge event](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html) as an alternative. - Fastly Compute\ On Fastly Compute, you can use the ConfigStore to manage user-defined data. - Netlify\ On Netlify, you can use the [Netlify Contexts](https://docs.netlify.com/site-deploys/overview/#deploy-contexts) to manage user-defined data. ### Specify the runtime You can specify the runtime to get environment variables by passing the runtime key as the second argument. ```ts app.get('/env', (c) => { const { NAME } = env<{ NAME: string }>(c, 'workerd') return c.text(NAME) }) ``` ## `getRuntimeKey()` The `getRuntimeKey()` function returns the identifier of the current runtime. ```ts app.get('/', (c) => { if (getRuntimeKey() === 'workerd') { return c.text('You are on Cloudflare') } else if (getRuntimeKey() === 'bun') { return c.text('You are on Bun') } ... }) ``` ### Available Runtimes Keys Here are the available runtimes keys, unavailable runtime key runtimes may be supported and labeled as `other`, with some being inspired by [WinterCG's Runtime Keys](https://runtime-keys.proposal.wintercg.org/): - `workerd` - Cloudflare Workers - `deno` - `bun` - `node` - `edge-light` - Vercel Edge Functions - `fastly` - Fastly Compute - `other` - Other unknown runtimes keys # JWT Authentication Helper This helper provides functions for encoding, decoding, signing, and verifying JSON Web Tokens (JWTs). JWTs are commonly used for authentication and authorization purposes in web applications. This helper offers robust JWT functionality with support for various cryptographic algorithms. ## Import To use this helper, you can import it as follows: ```ts import { decode, sign, verify } from 'hono/jwt' ``` ::: info [JWT Middleware](/docs/middleware/builtin/jwt) also import the `jwt` function from the `hono/jwt`. ::: ## `sign()` This function generates a JWT token by encoding a payload and signing it using the specified algorithm and secret. ```ts sign( payload: unknown, secret: string, alg?: 'HS256'; ): Promise; ``` ### Example ```ts import { sign } from 'hono/jwt' const payload = { sub: 'user123', role: 'admin', exp: Math.floor(Date.now() / 1000) + 60 * 5, // Token expires in 5 minutes } const secret = 'mySecretKey' const token = await sign(payload, secret) ``` ### Options
#### payload: `unknown` The JWT payload to be signed. You can include other claims like in [Payload Validation](#payload-validation). #### secret: `string` The secret key used for JWT verification or signing. #### alg: [AlgorithmTypes](#supported-algorithmtypes) The algorithm used for JWT signing or verification. The default is HS256. ## `verify()` This function checks if a JWT token is genuine and still valid. It ensures the token hasn't been altered and checks validity only if you added [Payload Validation](#payload-validation). ```ts verify( token: string, secret: string, alg: 'HS256'; issuer?: string | RegExp; ): Promise; ``` ### Example ```ts import { verify } from 'hono/jwt' const tokenToVerify = 'token' const secretKey = 'mySecretKey' const decodedPayload = await verify(tokenToVerify, secretKey, 'HS256') console.log(decodedPayload) ``` ### Options
#### token: `string` The JWT token to be verified. #### secret: `string` The secret key used for JWT verification or signing. #### alg: [AlgorithmTypes](#supported-algorithmtypes) The algorithm used for JWT signing or verification. #### issuer: `string | RegExp` The expected issuer used for JWT verification. ## `decode()` This function decodes a JWT token without performing signature verification. It extracts and returns the header and payload from the token. ```ts decode(token: string): { header: any; payload: any }; ``` ### Example ```ts import { decode } from 'hono/jwt' // Decode the JWT token const tokenToDecode = 'eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJzdWIiOiAidXNlcjEyMyIsICJyb2xlIjogImFkbWluIn0.JxUwx6Ua1B0D1B0FtCrj72ok5cm1Pkmr_hL82sd7ELA' const { header, payload } = decode(tokenToDecode) console.log('Decoded Header:', header) console.log('Decoded Payload:', payload) ``` ### Options
#### token: `string` The JWT token to be decoded. > The `decode` function allows you to inspect the header and payload of a JWT token _**without**_ performing verification. This can be useful for debugging or extracting information from JWT tokens. ## Payload Validation When verifying a JWT token, the following payload validations are performed: - `exp`: The token is checked to ensure it has not expired. - `nbf`: The token is checked to ensure it is not being used before a specified time. - `iat`: The token is checked to ensure it is not issued in the future. - `iss`: The token is checked to ensure it has been issued by a trusted issuer. Please ensure that your JWT payload includes these fields, as an object, if you intend to perform these checks during verification. ## Custom Error Types The module also defines custom error types to handle JWT-related errors. - `JwtAlgorithmNotImplemented`: Indicates that the requested JWT algorithm is not implemented. - `JwtTokenInvalid`: Indicates that the JWT token is invalid. - `JwtTokenNotBefore`: Indicates that the token is being used before its valid date. - `JwtTokenExpired`: Indicates that the token has expired. - `JwtTokenIssuedAt`: Indicates that the "iat" claim in the token is incorrect. - `JwtTokenIssuer`: Indicates that the "iss" claim in the token is incorrect. - `JwtTokenSignatureMismatched`: Indicates a signature mismatch in the token. ## Supported AlgorithmTypes The module supports the following JWT cryptographic algorithms: - `HS256`: HMAC using SHA-256 - `HS384`: HMAC using SHA-384 - `HS512`: HMAC using SHA-512 - `RS256`: RSASSA-PKCS1-v1_5 using SHA-256 - `RS384`: RSASSA-PKCS1-v1_5 using SHA-384 - `RS512`: RSASSA-PKCS1-v1_5 using SHA-512 - `PS256`: RSASSA-PSS using SHA-256 and MGF1 with SHA-256 - `PS384`: RSASSA-PSS using SHA-386 and MGF1 with SHA-386 - `PS512`: RSASSA-PSS using SHA-512 and MGF1 with SHA-512 - `ES256`: ECDSA using P-256 and SHA-256 - `ES384`: ECDSA using P-384 and SHA-384 - `ES512`: ECDSA using P-521 and SHA-512 - `EdDSA`: EdDSA using Ed25519 # Cookie Helper The Cookie Helper provides an easy interface to manage cookies, enabling developers to set, parse, and delete cookies seamlessly. ## Import ```ts import { Hono } from 'hono' import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie, generateCookie, generateSignedCookie, } from 'hono/cookie' ``` ## Usage ### Regular cookies ```ts app.get('/cookie', (c) => { setCookie(c, 'cookie_name', 'cookie_value') const yummyCookie = getCookie(c, 'cookie_name') deleteCookie(c, 'cookie_name') const allCookies = getCookie(c) // ... }) ``` ### Signed cookies **NOTE**: Setting and retrieving signed cookies returns a Promise due to the async nature of the WebCrypto API, which is used to create HMAC SHA-256 signatures. ```ts app.get('/signed-cookie', (c) => { const secret = 'secret' // make sure it's a large enough string to be secure await setSignedCookie(c, 'cookie_name0', 'cookie_value', secret) const fortuneCookie = await getSignedCookie( c, secret, 'cookie_name0' ) deleteCookie(c, 'cookie_name0') // `getSignedCookie` will return `false` for a specified cookie if the signature was tampered with or is invalid const allSignedCookies = await getSignedCookie(c, secret) // ... }) ``` ### Cookie Generation `generateCookie` and `generateSignedCookie` functions allow you to create cookie strings directly without setting them in the response headers. #### `generateCookie` ```ts // Basic cookie generation const cookie = generateCookie('delicious_cookie', 'macha') // Returns: 'delicious_cookie=macha; Path=/' // Cookie with options const cookie = generateCookie('delicious_cookie', 'macha', { path: '/', secure: true, httpOnly: true, domain: 'example.com', }) ``` #### `generateSignedCookie` ```ts // Basic signed cookie generation const signedCookie = await generateSignedCookie( 'delicious_cookie', 'macha', 'secret chocolate chips' ) // Signed cookie with options const signedCookie = await generateSignedCookie( 'delicious_cookie', 'macha', 'secret chocolate chips', { path: '/', secure: true, httpOnly: true, } ) ``` **Note**: Unlike `setCookie` and `setSignedCookie`, these functions only generate the cookie strings. You need to manually set them in headers if needed. ## Options ### `setCookie` & `setSignedCookie` - domain: `string` - expires: `Date` - httpOnly: `boolean` - maxAge: `number` - path: `string` - secure: `boolean` - sameSite: `'Strict'` | `'Lax'` | `'None'` - priority: `'Low' | 'Medium' | 'High'` - prefix: `secure` | `'host'` - partitioned: `boolean` Example: ```ts // Regular cookies setCookie(c, 'great_cookie', 'banana', { path: '/', secure: true, domain: 'example.com', httpOnly: true, maxAge: 1000, expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)), sameSite: 'Strict', }) // Signed cookies await setSignedCookie( c, 'fortune_cookie', 'lots-of-money', 'secret ingredient', { path: '/', secure: true, domain: 'example.com', httpOnly: true, maxAge: 1000, expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)), sameSite: 'Strict', } ) ``` ### `deleteCookie` - path: `string` - secure: `boolean` - domain: `string` Example: ```ts deleteCookie(c, 'banana', { path: '/', secure: true, domain: 'example.com', }) ``` `deleteCookie` returns the deleted value: ```ts const deletedCookie = deleteCookie(c, 'delicious_cookie') ``` ## `__Secure-` and `__Host-` prefix The Cookie helper supports `__Secure-` and `__Host-` prefix for cookies names. If you want to verify if the cookie name has a prefix, specify the prefix option. ```ts const securePrefixCookie = getCookie(c, 'yummy_cookie', 'secure') const hostPrefixCookie = getCookie(c, 'yummy_cookie', 'host') const securePrefixSignedCookie = await getSignedCookie( c, secret, 'fortune_cookie', 'secure' ) const hostPrefixSignedCookie = await getSignedCookie( c, secret, 'fortune_cookie', 'host' ) ``` Also, if you wish to specify a prefix when setting the cookie, specify a value for the prefix option. ```ts setCookie(c, 'delicious_cookie', 'macha', { prefix: 'secure', // or `host` }) await setSignedCookie( c, 'delicious_cookie', 'macha', 'secret choco chips', { prefix: 'secure', // or `host` } ) ``` ## Following the best practices A New Cookie RFC (a.k.a cookie-bis) and CHIPS include some best practices for Cookie settings that developers should follow. - [RFC6265bis-13](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis-13) - `Max-Age`/`Expires` limitation - `__Host-`/`__Secure-` prefix limitation - [CHIPS-01](https://www.ietf.org/archive/id/draft-cutler-httpbis-partitioned-cookies-01.html) - `Partitioned` limitation Hono is following the best practices. The cookie helper will throw an `Error` when parsing cookies under the following conditions: - The cookie name starts with `__Secure-`, but `secure` option is not set. - The cookie name starts with `__Host-`, but `secure` option is not set. - The cookie name starts with `__Host-`, but `path` is not `/`. - The cookie name starts with `__Host-`, but `domain` is set. - The `maxAge` option value is greater than 400 days. - The `expires` option value is 400 days later than the current time. # css Helper The CSS helper - `hono/css` - is Hono's built-in CSS in JS(X). You can write CSS in JSX in a JavaScript template literal named `css`. The return value of `css` will be the class name, which is set to the value of the class attribute. The ` {title}
{children}
) }) ``` ## `keyframes` You can use `keyframes` to write the contents of `@keyframes`. In this case, `fadeInAnimation` will be the name of the animation. ```tsx const fadeInAnimation = keyframes` from { opacity: 0; } to { opacity: 1; } ` const headerClass = css` animation-name: ${fadeInAnimation}; animation-duration: 2s; ` const Header = () => Hello! ``` ## `cx` The `cx` composites the two class names. ```tsx const buttonClass = css` border-radius: 10px; ` const primaryClass = css` background: orange; ` const Button = () => ( Click! ) ``` It can also compose simple strings. ```tsx const Header = () => Hi ``` ## Usage in combination with [Secure Headers](/docs/middleware/builtin/secure-headers) middleware If you want to use the CSS helpers in combination with the [Secure Headers](/docs/middleware/builtin/secure-headers) middleware, you can add the [`nonce` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce) to the `