new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Hono · all subjects

app

149 notes in this subject, read out of this brain and free to use. This is page 2 of 3.

Create KV namespace command

Run 'wrangler kv namespace create MY_KV --preview' to create a KV namespace. This outputs the binding name and preview_id which should be recorded and added to wrangler.toml.

Cloudflare Pages production Bindings setup

For production Cloudflare Pages deployments, Bindings are configured in the Cloudflare dashboard, not in wrangler.toml. wrangler.toml is used for local development only.

Build client and server for Cloudflare Pages

To build both client and server scripts for Cloudflare Pages, use separate Vite modes: 'vite build --mode client && vite build'. Configure vite.config.ts to return different build options based on the mode value.

Client-side script handling in Cloudflare Pages

In Cloudflare Pages, distinguish between dev and production builds using import.meta.env.PROD. In dev, reference source TypeScript files directly; in production, reference built JavaScript in the public directory.

vite.config.ts for Cloudflare Pages with Bindings

Configure Vite for Cloudflare Pages with Bindings using: import devServer from '@hono/vite-dev-server'; import adapter from '@hono/vite-dev-server/cloudflare'; import build from '@hono/vite-cloudflare-pages'; export default defineConfig({ plugins: [devServer({ entry: 'src/index.tsx', adapter }), build()] })

Cloudflare Pages setup with create-hono command

To start a new Cloudflare Pages project with Hono, use the 'create-hono' command and select the 'cloudflare-pages' template. Run 'npm create hono@latest my-app' (or equivalent for yarn, pnpm, bun, deno), then cd into the directory and install dependencies with the package manager's install command.

Cloudflare Pages deployment build settings

When deploying Cloudflare Pages via GitHub, the build configuration should be: Production branch is 'main', Build command is 'npm run build', and Build directory is 'dist'.

Hello World example for Deno

A minimal Hono application on Deno looks like this: ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Deno!')) Deno.serve(app.fetch) ``` Run with deno task start and access http://localhost:8000 in your web browser.

Hono works on Deno runtime

Hono is a JavaScript/TypeScript framework that works on Deno, a JavaScript runtime built on V8. You can write code with TypeScript, run the application with the deno command, and deploy it to Deno Deploy.

Initialize Hono project on Deno

To start a new Hono project on Deno, use the command: deno init --npm hono --template=deno my-app. This creates a starter project with Hono already configured. You do not need to install Hono explicitly after running this command.

Change port number on Deno

To specify a custom port number on Deno, pass a configuration object to Deno.serve: Deno.serve({ port: 8787 }, app.fetch). Replace 8787 with your desired port number.

Test Hono applications on Deno

Test Hono applications on Deno using Deno.test and assertions from @std/assert. Install with deno add jsr:@std/assert. Example test: ```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) }) ``` Run tests with deno test hello.ts.

Hono available on npm and JSR registries

Hono is available on both npm and JSR (JavaScript Registry). In deno.json, you can use either npm:hono or jsr:@hono/hono. For middleware support, use the Deno directory syntax: "hono/": "npm:/hono/" or "hono/": "jsr:/@hono/hono/".

Registry consistency for middleware compatibility

When using third-party Hono middleware on Deno, ensure Hono and the middleware come from the same registry (either both from npm or both from JSR) for proper TypeScript type inference. For example, if using @hono/zod-validator from npm, also import Hono from npm. Many third-party middleware packages are available on JSR at jsr.io/@hono.

Create Hono project for Cloudflare Workers

Use the create-hono command with the cloudflare-workers template to start a new Hono project. Run `npm create hono@latest my-app` (or equivalent for yarn, pnpm, bun, or deno), select cloudflare-workers template, then enter the directory and install dependencies with `npm i` (or the equivalent for your package manager).

Run Hono dev server for Cloudflare Workers

Execute `npm run dev` (or equivalent for yarn, pnpm, bun) to run the local development server. The server will be accessible at `http://localhost:8787` by default.

Change port number for Cloudflare Workers dev server

The port number can be changed by updating `wrangler.toml`, `wrangler.json`, or `wrangler.jsonc` files following Wrangler Configuration instructions, or by using Wrangler CLI options.

Deploy Hono to Cloudflare Workers

Run `npm run deploy` (or equivalent for yarn, pnpm, bun) to deploy the application. Ensure package.json has the correct package manager configured by replacing `$npm_execpath` with the appropriate package manager.

Hello World example for Cloudflare Workers

A minimal Hono app for Cloudflare Workers requires importing Hono, creating an instance, and exporting it as default. The example creates a route responding with text: `import { Hono } from 'hono'; const app = new Hono(); app.get('/', (c) => c.text('Hello Cloudflare Workers!')); export default app`

Deploy Hono to Cloudflare via GitHub Actions

Create a Cloudflare API token with 'Edit Cloudflare Workers' permissions in User API Tokens dashboard. Add it as a repository secret named `CLOUDFLARE_API_TOKEN` in GitHub Settings. Create `.github/workflows/deploy.yml` with the cloudflare/wrangler-action@v3 action passing the token. Then update `wrangler.jsonc` to add `"main": "src/index.ts"` and `"minify": true` after the `compatibility_date` line.

Test Hono app in Cloudflare Workers

Use `@cloudflare/vitest-pool-workers` for testing. Call `app.request()` with a URL to get a Response object and assert on its properties. Example: `const res = await app.request('http://localhost/'); expect(res.status).toBe(200)`

Install Cloudflare Workers types

Install `@cloudflare/workers-types` as a dev dependency to get proper TypeScript types for Cloudflare Workers: `npm i --save-dev @cloudflare/workers-types` (or equivalent for yarn, pnpm, bun).

Serve static files in Cloudflare Workers

Use Cloudflare Workers Static Assets feature by specifying the assets directory in `wrangler.jsonc`: `"assets": { "directory": "public" }`. Create a `public` directory and place files there; for example, `./public/static/hello.txt` will be served as `/static/hello.txt`.

Module Worker mode with other event handlers

In Module Worker mode, you can integrate Hono with other event handlers like `scheduled`. Export `app.fetch` as the module's fetch handler and implement other handlers as needed: `export default { fetch: app.fetch, scheduled: async (batch, env) => {} }`

Google Cloud Run default port requirement

When deploying a Hono application to Google Cloud Run, the application must listen on port 8080. This is the standard port that Cloud Run expects services to use.

Google Cloud Run runtime options

Google Cloud Run supports any runtime through containerization via Dockerfile. If no Dockerfile is provided, Google Cloud Run uses the default Node.js buildpack. You can deploy using Deno, Bun, or a customized Node.js container by providing a Dockerfile and optionally a .dockerignore file.

Hono on Google Cloud Run deployment command

Deploy a Hono application to Google Cloud Run using the command: gcloud run deploy my-app --source . --allow-unauthenticated. This command starts the deployment and presents interactive prompts for selecting options such as region.

Node.js server setup for Cloud Run

A minimal Hono application for Cloud Run uses the @hono/node-server package. The application imports serve from @hono/node-server and Hono from hono, creates an app instance, defines routes, and calls serve with the app.fetch method and port 8080.

Fastly Compute deployment command

Deploy a Hono application to Fastly Compute by running npm run deploy (or equivalent yarn/pnpm/bun command). On first deployment, you will be prompted to create a new service in your Fastly account. A Fastly account must be created at https://www.fastly.com/signup/ before initial deployment.

Fastly Compute development server port

The local development server for Fastly Compute runs on http://localhost:7676. Start it with npm run start (or equivalent yarn/pnpm/bun command).

fire() import and usage for Fastly Compute

The fire() function is imported from @fastly/hono-fastly-compute and is called with the Hono app instance to initialize the application for Fastly Compute runtime. When using fire() at the top level, import Hono from 'hono' rather than 'hono/quick' because fire causes the router to build its internal data during application initialization.

Fastly Compute template setup with create-hono

Create a new Hono project for Fastly Compute by running npm create hono@latest my-app (or equivalent yarn/pnpm/bun/deno command), then select the fastly template. After creation, move into the project directory and install dependencies.

Fastly Compute buildFire bindings example

Example using buildFire() with bindings: ```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) ```

Fastly Compute Hello World example

Example Fastly Compute Hono application: ```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) ```

buildFire() for typed bindings configuration

Use buildFire() imported from @fastly/hono-fastly-compute instead of fire() when you need to configure bindings. Pass a bindings object to buildFire() where keys are binding names and values are binding declarations in the format 'ResourceType:resource-name'. The returned object has a Bindings property that defines the SDK types for use with Hono<{ Bindings: typeof fire.Bindings }>.

Fastly Compute bindings types and resources

Fastly Compute supports bindings for KV Stores, Config Stores, Secret Stores, Backends, Access Control Lists, Named Log Streams, and Environment Variables. These bindings are accessed through c.env and have individual SDK types provided by Fastly.

Netlify setup with create-hono

To set up a Hono project for Netlify Edge Functions, use the create-hono command with the netlify template. Use 'npm create hono@latest my-app', 'yarn create hono my-app', 'pnpm create hono my-app', 'bun create hono@latest my-app', or 'deno init --npm hono my-app' depending on your package manager.

Netlify Edge Functions development server

Run the development server for Netlify Edge Functions using the 'netlify dev' command. The local development server runs on http://localhost:8888.

Netlify Edge Functions deployment

Deploy a Netlify Edge Functions Hono app to production using the 'netlify deploy --prod' command.

Netlify Hello World example

Example of a minimal Netlify Edge Functions Hono app. Import Hono from 'jsr:@hono/hono' and handle from 'jsr:@hono/hono/netlify'. Create a Hono app, define a GET route on '/' that returns c.text('Hello Hono!'), and export the result of handle(app) as default.

Netlify Edge Functions entry point

The entry point for a Netlify Edge Functions Hono app is netlify/edge-functions/index.ts. Import Hono from 'jsr:@hono/hono' and import the handle function from 'jsr:@hono/hono/netlify', then export the result of handle(app) as the default export.

Next.js Pages Router requires bodyParser: false in API config

When using Hono with Next.js Pages Router, set bodyParser to false in the exported PageConfig object to prevent Next.js from parsing the request body before Hono can handle it.

Hono on Next.js with App Router

To run Hono on Next.js using the App Router, edit the file app/api/[[...route]]/route.ts. Import Hono and the handle function from hono/vercel. Create a new Hono app with basePath('/api'). Define routes on the app instance. Export GET and POST handlers using handle(app).

Create Hono Next.js project with create-hono

A starter for Next.js is available through the create-hono command. Select the nextjs template when prompted. The command works with npm, yarn, pnpm, bun, and deno package managers.

Hono can run on Next.js with Node.js runtime

Hono can be run on Next.js when using the Node.js runtime. On Vercel, deploying Hono with Next.js is easy by using Vercel Functions.

App Router Hello World example

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)

Hono on Next.js Pages Router requires Node.js adapter

To use Hono with Next.js Pages Router, install the @hono/node-server package. Use the getRequestListener function from @hono/node-server in the pages/api/[[...route]].ts file.

Pages Router Hello World example

import { getRequestListener } from '@hono/node-server' import { Hono } from 'hono' 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 getRequestListener(app.fetch)

Pages Router requires NODEJS_HELPERS=0 environment variable

When using Hono with Next.js Pages Router, set the environment variable NODEJS_HELPERS=0 in your project dashboard or .env file. This disables Vercel Node.js helpers which are incompatible with the setup.

serveStatic rewriteRequestPath option

Use the rewriteRequestPath option in serveStatic to map request paths to different file paths. It accepts a function that transforms the request path and returns the mapped path.

Node.js runtime version requirements

Hono requires Node.js 18.14.1 or later for 18.x, 19.7.0 or later for 19.x, and 20.0.0 or later for 20.x. Generally, use the latest version of each major release.

Node.js adapter module

Hono requires the Node.js Adapter package '@hono/node-server' to run on Node.js. Import 'serve' from '@hono/node-server' to start the server.

Basic Hello World example for Node.js

Example of a simple Hono app running on Node.js: import { serve } from '@hono/node-server' import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello Node.js!')) serve(app)

Graceful server shutdown on Node.js

To gracefully shut down a Hono server on Node.js, store the server returned by serve() and listen for SIGINT and SIGTERM signals. On SIGINT, call server.close() and process.exit(0). On SIGTERM, call server.close() with a callback that checks for errors before exiting. const server = serve(app) 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) }) })

Changing port number in Node.js serve

Pass a port option to serve() to specify the server port. Example: serve({ fetch: app.fetch, port: 8787 }) starts the server on port 8787.

WebSocket support in Node.js

WebSocket support is built into @hono/node-server. Install the 'ws' package and optionally '@types/ws' for TypeScript. Create a WebSocketServer with { noServer: true } and pass it to serve() with the websocket option. Use upgradeWebSocket() from '@hono/node-server' as a handler.

Deprecated @hono/node-ws package

@hono/node-ws is deprecated. Use the built-in WebSocket support in @hono/node-server instead.

serveStatic middleware for Node.js

Import serveStatic from '@hono/node-server/serve-static' to serve static files from the local file system. The root option specifies the base directory relative to the current working directory.

serveStatic root option works relative to current working directory

The root option in serveStatic resolves paths relative to process.cwd(), not the source file location. This means file resolution depends on where you run the Node.js process from, not where the source file is located.

serveStatic with import.meta.url for reliable paths

For reliable path resolution that always points to the same directory as the source file, use import.meta.url with fileURLToPath: import { fileURLToPath } from 'node:url' import { serveStatic } from '@hono/node-server/serve-static' app.use( '/static/*', serveStatic({ root: fileURLToPath(new URL('./', import.meta.url)) }) )

Give your agent this brain