### Basic Deno Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Set up a basic Hono application for the Deno runtime. Ensure Deno is installed and the necessary modules can be imported. ```typescript import { Hono } from 'https://deno.land/x/hono/mod.ts' import { serve } from 'https://deno.land/std@0.181.0/http/server.ts' const app = new Hono() app.get('/', (c) => c.text('Hello from Deno!')) serve(app.fetch, { port: 3000 }) ``` -------------------------------- ### Basic Hono App Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Initialize a basic Hono application instance. This is the starting point for building your web application. ```typescript // Basic app const app = new Hono() ``` -------------------------------- ### Install dependencies Source: https://github.com/honojs/hono/blob/main/benchmarks/routers/README.md Install the required project dependencies using Bun. ```bash bun install --frozen-lockfile ``` -------------------------------- ### Basic Bun Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Initialize a Hono application for the Bun runtime. This setup is optimized for Bun's performance and features. ```typescript import { Hono } from 'hono' import { serve } from '@hono/bun' const app = new Hono() app.get('/', (c) => c.text('Hello from Bun!')) serve(app, () => { console.log('Listening on http://localhost:3000') }) ``` -------------------------------- ### Create a Basic Hono Application Source: https://github.com/honojs/hono/blob/main/README.md This snippet demonstrates how to initialize a Hono application and define a simple GET route that returns a text response. It requires the Hono package to be installed in your project. ```typescript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hono!')) export default app ``` -------------------------------- ### Basic Node.js Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Set up a basic Hono application to run on Node.js using the native HTTP module. This is suitable for simple server setups. ```typescript import { Hono } from 'hono' import { serve } from '@hono/node-server' const app = new Hono() app.get('/', (c) => c.text('Hello from Node.js!')) serve(app, (info) => { console.log(`Listening on http://localhost:${info.port}`) }) ``` -------------------------------- ### Custom Schema Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md An example demonstrating how to define a custom schema for multiple API endpoints. It specifies the input and output types for GET and POST requests to '/users' and a GET request with a parameter. ```typescript type MySchema = { 'GET /users': { in: {} out: { users: Array<{ id: string; name: string }> } } 'POST /users': { in: { name: string; email: string } out: { id: string; created: boolean } } 'GET /users/:id': { in: {} out: { id: string; name: string; email: string } } } ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/honojs/hono/blob/main/docs/CONTRIBUTING.md Installs project dependencies using Bun, ensuring the lockfile is used for reproducible builds. This is a prerequisite for development. ```bash bun install --frozen-lockfile ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/honojs/hono/blob/main/docs/CONTRIBUTING.md Clones the Hono repository and installs its dependencies using Bun. This command sets up the local development environment. ```bash git clone git@github.com:honojs/hono.git && cd hono && bun install --frozen-lockfile ``` -------------------------------- ### Handler Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md Illustrates defining and using a handler with a custom environment and typed path parameters. ```typescript const handler: Handler = (c) => { const id = c.req.param('id') return c.json({ id }) } app.get('/users/:id', handler) ``` -------------------------------- ### Basic Vercel Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Set up a basic Hono application for Vercel deployment. This requires importing `handle` from `@hono/node-server/vercel`. ```typescript import { Hono } from 'hono' import { handle } from '@hono/node-server/vercel' const app = new Hono() app.get('/', (c) => c.text('Hello from Vercel!')) export default handle(app) ``` -------------------------------- ### Handler Chaining Example Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md Demonstrates how multiple middleware and a final handler are chained together for a GET request. Middleware executes before and after the next handler. ```typescript app.get('/users/:id', async (c, next) => { console.log('Middleware 1: Before') await next() console.log('Middleware 1: After') }, async (c, next) => { console.log('Middleware 2: Before') await next() console.log('Middleware 2: After') }, (c) => { console.log('Final handler') return c.json({ id: c.req.param('id') }) } ) ``` -------------------------------- ### MiddlewareHandler Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md Shows an example of an authentication middleware that checks for an Authorization header and logs a message after the main handler executes. ```typescript const authMiddleware: MiddlewareHandler = async (c, next) => { const token = c.req.header('Authorization') if (!token) { return c.text('Unauthorized', 401) } await next() console.log('After handler execution') } app.use(authMiddleware) ``` -------------------------------- ### Get and Set Signed Cookies Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Provides examples for retrieving and setting signed cookies, requiring a secret for security. ```typescript // Signed const value = await getSignedCookie(c, 'secret', 'name') await setSignedCookie(c, 'name', 'value', 'secret') ``` -------------------------------- ### Logger Middleware Example Output Source: https://github.com/honojs/hono/blob/main/_autodocs/middleware-reference.md Illustrates the format of log messages generated by the logger middleware. ```text GET /users 200 1.23ms POST /api/data 201 5.67ms GET /admin 401 0.45ms ``` -------------------------------- ### Initialize Hono Project Source: https://github.com/honojs/hono/blob/main/README.md This command uses the Hono CLI to scaffold a new project quickly. It is the recommended way to start a new Hono application. ```bash npm create hono@latest ``` -------------------------------- ### Fastly Compute@Edge Configuration Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Example `fastly.toml` configuration file for a Fastly Compute@Edge project. ```toml # fastly.toml [profile.production] name = "my-hono-app" description = "My Hono app" ``` -------------------------------- ### NotFoundHandler Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md An example of a not found handler that returns a JSON response indicating the route was not found, including the requested path. ```typescript const notFoundHandler: NotFoundHandler = (c) => { return c.json( { error: 'Route not found', path: c.req.path }, 404 ) } app.notFound(notFoundHandler) ``` -------------------------------- ### Basic Middleware Implementation Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md A fundamental example of creating middleware that executes logic before and after `next()` is called. ```typescript // Basic middleware app.use(async (c, next) => { console.log('Before') await next() console.log('After') }) ``` -------------------------------- ### Basic Fastly Compute@Edge Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Set up a basic Hono application for Fastly Compute@Edge. This involves creating a Hono instance and defining routes. ```typescript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello from Fastly!')) export default app ``` -------------------------------- ### Complete API Server Example with Hono Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md A comprehensive example of an API server using Hono. It includes common middleware like logging, CORS, and JWT authentication, along with route definitions, error handling, and a 404 handler. The JWT middleware requires 'secret' and 'alg' options. ```typescript import { Hono } from 'hono' import { cors } from 'hono/cors' import { jwt } from 'hono/jwt' import { HTTPException } from 'hono/http-exception' import { logger } from 'hono/logger' type Env = { Variables: { user?: { id: string; role: string } } } const app = new Hono() // Middleware app.use(logger()) app.use(cors()) // Public routes app.get('/', (c) => c.json({ message: 'Welcome' })) app.post('/login', async (c) => { const { username, password } = await c.req.json() if (username === 'admin' && password === 'secret') { const token = await sign({ sub: 'admin' }, 'secret', 'HS256') return c.json({ token }) } throw new HTTPException(401, { message: 'Invalid credentials' }) }) // Protected routes app.use('/api/*', jwt({ secret: 'secret', alg: 'HS256' })) app.get('/api/protected', (c) => { const payload = c.get('jwtPayload') return c.json({ message: 'Protected data', payload }) }) // Error handling app.notFound((c) => c.json({ error: 'Not found' }, 404)) app.onError((err, c) => { if (err instanceof HTTPException) { return err.getResponse() } return c.json({ error: 'Internal error' }, 500) }) export default app ``` -------------------------------- ### Custom Environment Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md Demonstrates defining a custom environment type with specific bindings and variables, and using it with a Hono application. ```typescript type MyEnv = { Bindings: { DATABASE_URL: string API_KEY: string KV: KVNamespace } Variables: { user?: { id: string; email: string } requestId: string } } const app = new Hono() app.use(async (c, next) => { c.set('requestId', crypto.randomUUID()) c.set('user', { id: '123', email: 'test@example.com' }) await next() }) ``` -------------------------------- ### Registering Basic Routes Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Define simple GET and POST routes, routes with path parameters, and wildcard routes. ```typescript const app = new Hono() // Simple path app.get('/users', (c) => c.json([])) app.post('/users', (c) => c.json({}, 201)) // Path with parameters app.get('/users/:id', (c) => c.json({ id: c.req.param('id') })) app.get('/users/:id/posts/:postId', (c) => { const { id, postId } = c.req.param() return c.json({ userId: id, postId }) }) // Wildcard paths app.get('/files/*', (c) => c.text('File route')) app.all('/*', (c) => c.text('Catch all')) ``` -------------------------------- ### Basic AWS Lambda Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Set up a basic Hono application to be used as an AWS Lambda function handler. This requires importing `handle` from the AWS Lambda adapter. ```typescript import { Hono } from 'hono' import { handle } from 'hono/aws-lambda' const app = new Hono() app.get('/', (c) => c.text('Hello from Lambda!')) export const handler = handle(app) ``` -------------------------------- ### Run HTTP Benchmark Locally - Bash Source: https://github.com/honojs/hono/blob/main/benchmarks/http-server/README.md This command navigates to the http-server benchmark directory and executes the benchmark script using Bun. It requires Bun v1.0+ to be installed. ```bash cd benchmarks/http-server bun run benchmark.ts ``` -------------------------------- ### Basic AWS Lambda@Edge Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Set up a basic Hono application for AWS Lambda@Edge. This involves importing the Hono framework and the `handle` function from the `hono/lambda-edge` adapter. ```typescript import { Hono } from 'hono' import { handle } from 'hono/lambda-edge' const app = new Hono() app.get('/', (c) => c.text('Hello from Lambda@Edge!')) export const handler = handle(app) ``` -------------------------------- ### Configure CORS Middleware Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Example of setting up the CORS middleware with specific options for origin, allowed methods, and credentials. ```typescript app.use(cors({ origin: 'https://example.com', allowMethods: ['GET', 'POST'], credentials: true })) ``` -------------------------------- ### ErrorHandler Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md Provides an example of a custom error handler that logs errors and returns appropriate JSON responses for HTTP exceptions or general errors. ```typescript const errorHandler: ErrorHandler = (err, c) => { console.error('Error:', err.message) if (err instanceof HTTPException) { return err.getResponse() } return c.json({ error: 'Internal Server Error' }, 500) } app.onError(errorHandler) ``` -------------------------------- ### Combine Cookie, Accepts, and ConnInfo Helpers Source: https://github.com/honojs/hono/blob/main/_autodocs/helpers-reference.md This example shows how to use `getCookie`, `setCookie`, `accepts`, and `getConnInfo` helpers together in a Hono route handler. Ensure necessary imports are included. ```typescript import { getCookie, setCookie } from 'hono/helper/cookie' import { accepts } from 'hono/helper/accepts' import { getConnInfo } from 'hono/helper/conninfo' app.get('/example', async (c) => { const sessionId = getCookie(c, 'sessionId') const contentType = accepts(c, 'json', 'html') const connInfo = getConnInfo(c) setCookie(c, 'lastVisit', new Date().toISOString(), { maxAge: 30 * 24 * 60 * 60 // 30 days }) return c.json({ sessionId, contentType, ip: connInfo.remote.address }) }) ``` -------------------------------- ### Multiple Methods on Same Path Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Handles multiple HTTP methods (GET, POST) on the same path using the `on()` method. ```APIDOC ## GET, POST /data ### Description Handles both GET and POST requests for the `/data` path. Responds with an empty array for GET and an empty object with status 201 for POST. ### Method GET, POST ### Endpoint /data ### Response Example (GET) ```json [] ``` ### Response Example (POST) ```json {} ``` ``` -------------------------------- ### Vercel Deployment Configuration Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Example `vercel.json` configuration for deploying a Hono application to Vercel. This specifies build commands, output directories, and function settings. ```json { "buildCommand": "npm run build", "outputDirectory": "dist", "functions": { "api/[[...path]].ts": { "maxDuration": 10 } } } ``` -------------------------------- ### Hono App Setup with Custom Options Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Initialize a Hono application with custom options, such as disabling strict routing, using a regular expression router, or providing a custom path getter function. ```typescript // With custom options const app = new Hono({ strict: false, router: new RegExpRouter(), getPath: (req) => req.url.pathname }) ``` -------------------------------- ### createFactory() Source: https://github.com/honojs/hono/blob/main/_autodocs/helpers-reference.md Creates reusable handler factories with pre-configured context setup. This allows for consistent context initialization across multiple handlers. ```APIDOC ## createFactory() ### Description Creates handler factories with pre-configured context setup. ### Signature ```typescript createFactory( cb: (c: Context) => void ): { createHandlers: (handlers: Handler[]) => MiddlewareHandler[]; } ``` ### Example ```typescript const factory = createFactory((c) => { c.set('version', '1.0') }) const handlers = factory.createHandlers([ (c) => c.json({ version: c.get('version') }) ]) ``` ``` -------------------------------- ### Basic Cloudflare Workers App Setup Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md A minimal Hono application for Cloudflare Workers. This is the entry point for a typical Cloudflare Workers service. ```typescript import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello from Cloudflare Workers!')) export default app ``` -------------------------------- ### Custom 404 Response Example Source: https://github.com/honojs/hono/blob/main/_autodocs/types-and-interfaces.md Demonstrates how to extend the `NotFoundResponse` interface and implement a custom 404 handler using `app.notFound` to return a JSON error message. ```typescript declare module 'hono' { interface NotFoundResponse extends Response, TypedResponse {} } app.notFound((c) => { return c.json({ error: 'Not found' }, 404) }) ``` -------------------------------- ### Node.js Setup with Environment Variables Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Configure a Hono application for Node.js that utilizes environment variables for configuration, such as database URLs and ports. It also demonstrates setting variables within the Hono context. ```typescript type Env = { Bindings: { DATABASE_URL: string PORT: string } Variables: { db?: Database } } const app = new Hono() app.use(async (c, next) => { const dbUrl = process.env.DATABASE_URL c.set('db', new Database(dbUrl)) await next() }) serve(app) ``` -------------------------------- ### Get and Set Context Variables Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Shows how to retrieve values using `c.get(key)` and set values using `c.set(key, value)` within the request context. ```typescript // Get variable c.get(key) // Set variable c.set(key, value) ``` -------------------------------- ### Deno File System Access Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Handle file system access in Deno to read files based on request parameters. This example demonstrates opening and reading a file from a local directory. ```typescript app.get('/file/:name', async (c) => { const name = c.req.param('name') try { const file = await Deno.open(`./files/${name}`) return c.body(await Deno.readAll(file)) } catch { return c.text('Not found', 404) } }) ``` -------------------------------- ### Handle File Uploads Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Example of processing a file upload in a POST request, retrieving form data and the file content as an ArrayBuffer. ```typescript app.post('/upload', async (c) => { const formData = await c.req.formData() const file = formData.get('file') as File const name = formData.get('name') const buffer = await file.arrayBuffer() return c.json({ name, size: buffer.byteLength }) }) ``` -------------------------------- ### Set and Get Response Status Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Demonstrates how to set and retrieve the HTTP status code for a response using the `c.status()` method and `c.res.status` property. ```typescript // Status c.status(200) // Set status c.res.status // Get status ``` -------------------------------- ### Run Router Benchmarks with Deno Source: https://github.com/honojs/hono/blob/main/benchmarks/routers-deno/README.md Execute the benchmark script using Deno. Ensure you have the necessary read and run permissions. ```bash deno run --allow-read --allow-run src/bench.mts ``` -------------------------------- ### Get Environment Variable in Deno Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Access environment variables in Deno using Deno.env.get(). This example shows how to retrieve an API key and configure a basic Hono route. ```typescript const apiKey = Deno.env.get('API_KEY') || 'default' app.get('/', (c) => { return c.json({ configured: !!apiKey }) }) ``` -------------------------------- ### Bun WebSocket Handling Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Implement WebSocket functionality within a Hono application running on Bun. This example shows how to handle incoming messages and send echoes. ```typescript import { upgradeWebSocket } from 'hono/helper/websocket' app.get('/ws', upgradeWebSocket({ onMessage: (message, ws) => { ws.send(`Echo: ${message}`) } })) ``` -------------------------------- ### GET Method Handler Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md Handles GET requests for a specific path, extracting path parameters. ```APIDOC ## GET /users/:id ### Description Handles GET requests for a specific path, extracting path parameters. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. ### Response #### Success Response (200) - **id** (string) - The extracted user ID. ``` -------------------------------- ### Handle GET Requests Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md Define a handler for GET requests to a specific path, extracting parameters from the URL. ```typescript app.get('/users/:id', (c) => { const id = c.req.param('id') return c.json({ id }) }) ``` -------------------------------- ### req.method Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get the HTTP method of the request. This property returns the HTTP method as a string (e.g., 'GET', 'POST'). ```APIDOC ## req.method ### Description Get the HTTP method. ### Property `c.req.method: string` ### Example ```ts app.all('/endpoint', (c) => { if (c.req.method === 'GET') { return c.text('GET request') } else if (c.req.method === 'POST') { return c.text('POST request') } return c.text('Other method') }) ``` ``` -------------------------------- ### Run benchmarks Source: https://github.com/honojs/hono/blob/main/benchmarks/routers/README.md Execute the benchmark suite for either Node.js or Bun environments. ```bash bun run bench:node ``` ```bash bun run bench:bun ``` -------------------------------- ### Basic Hono App Export Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md A minimal Hono application setup that exports a fetch handler. Suitable for Cloudflare Workers, Deno, and other Web Standard compatible runtimes. ```typescript const app = new Hono() app.get('/', (c) => c.text('Hello')) export default app ``` -------------------------------- ### Hono App Setup with Environment Typing Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Configure a Hono application with specific environment types, including bindings and variables. This enhances type safety for your application's context. ```typescript // With environment type MyEnv = { Bindings: { API_KEY: string; DB: Database } Variables: { user?: User } } const app = new Hono() ``` -------------------------------- ### Response Body Methods Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Provides examples of different methods for sending responses with various content types: text, JSON, HTML, raw data, or a new `Response` object. ```typescript // Response methods c.text(text, status?, headers?) c.json(object, status?, headers?) c.html(html, status?, headers?) c.body(data, status?, headers?) c.newResponse(body, init?) ``` -------------------------------- ### Bun Server Entry Point Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Utilize the @hono/bun adapter to serve the Hono application with Bun. Import the shared app and use the serve function from the adapter. ```typescript // bun.ts import app from './src/app' import { serve } from '@hono/bun' serve(app) ``` -------------------------------- ### Bun Deployment Commands Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Provides basic command-line instructions for running a Hono application locally with Bun in development mode and for production deployment. ```bash # Run locally bun run dev # Run in production bun run index.ts ``` -------------------------------- ### Get HTTP Method Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md Retrieve the HTTP method of the request (e.g., 'GET', 'POST') using `c.req.method`. This can be used for conditional logic. ```typescript app.all('/endpoint', (c) => { const method = c.req.method // 'GET', 'POST', etc. return c.json({ method }) }) ``` -------------------------------- ### Early Validation Return in Hono Source: https://github.com/honojs/hono/blob/main/_autodocs/validation-and-schema.md This example shows how to implement early return logic within a Hono validator middleware. Invalid data is rejected immediately, preventing further processing and improving efficiency. ```typescript app.post('/data', validator('json', (data) => { // Return false immediately for invalid data if (!data) return false if (typeof data !== 'object') return false if (!('name' in data)) return false // Continue with detailed validation return isValidName(data.name) }), (c) => { // Reaches only if all checks pass const data = c.req.valid('json') return c.json({ processed: true }) }) ``` -------------------------------- ### Configure serveStatic with manifest in Cloudflare Workers Source: https://github.com/honojs/hono/blob/main/docs/MIGRATION.md When using the serveStatic function in the Cloudflare Workers adapter, the 'manifest' option must be specified. This example shows how to import the manifest and use it with serveStatic. ```typescript import manifest from '__STATIC_CONTENT_MANIFEST' // ... app.use('/static/*', serveStatic({ root: './assets', manifest })) ``` -------------------------------- ### Define HTTP Routes with Hono Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Use methods like `get`, `post`, `put`, `delete`, `patch`, `options`, and `all` to define routes for specific HTTP methods. For custom methods or multiple methods, use `app.on()`. ```typescript app.get(path, ...handlers) app.post(path, ...handlers) app.put(path, ...handlers) app.delete(path, ...handlers) app.patch(path, ...handlers) app.options(path, ...handlers) app.all(path, ...handlers) app.on(method, path, ...handlers) app.on(['GET', 'POST'], path, ...handlers) ``` -------------------------------- ### Get All Request Headers Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md The `headers()` method returns all request headers as an object. ```APIDOC ## Get All Request Headers ### Description Get all request headers as an object. ### Method `headers(): Record` ### Returns An object containing all request headers. ### Example ```ts app.post('/', (c) => { const allHeaders = c.req.headers() return c.json(allHeaders) }) ``` ``` -------------------------------- ### Get All Cookies Source: https://github.com/honojs/hono/blob/main/_autodocs/helpers-reference.md Retrieves all cookies from the request context. Useful for accessing multiple cookies at once. ```typescript app.get('/', (c) => { const cookies = getCookie(c) // { sessionId: 'abc123', theme: 'dark' } return c.json(cookies) }) ``` -------------------------------- ### Node.js Server Entry Point Source: https://github.com/honojs/hono/blob/main/_autodocs/adapters-and-deployment.md Use the @hono/node-server adapter to serve the Hono application in a Node.js environment. Import the shared app and use the serve function. ```typescript // server.ts import app from './src/app' import { serve } from '@hono/node-server' serve(app) ``` -------------------------------- ### req.path Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get the request path. This property returns the path of the incoming request as a string. ```APIDOC ## req.path ### Description Get the request path. ### Property `c.req.path: string` ### Example ```ts app.get('/users/:id', (c) => { const path = c.req.path // '/users/123' return c.text(`Path: ${path}`) }) ``` ``` -------------------------------- ### req.param(key?) Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get path parameters. You can retrieve a specific parameter by its key or all parameters as an object. ```APIDOC ## req.param(key?) ### Description Get path parameters. ### Method `param(): Record param(key: string): string | undefined` ### Parameters #### Path Parameters - **key** (string) - Optional. Parameter name. ### Returns Single parameter value or object of all parameters. ### Example ```ts // Get single parameter app.get('/users/:id', (c) => { const id = c.req.param('id') // '123' return c.json({ id }) }) // Get all parameters app.get('/users/:userId/posts/:postId', (c) => { const params = c.req.param() // { userId: '123', postId: '456' } return c.json(params) }) ``` ``` -------------------------------- ### Get Request Pathname Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md Access the pathname of the request using `c.req.path`. This is useful for routing or logging. ```typescript app.get('/users/123', (c) => { console.log(c.req.path) // '/users/123' return c.text('OK') }) ``` -------------------------------- ### Mounting a Sub-Application with mount() Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md Explains how to mount a Hono application as a sub-router at a specific path using the `mount()` method. ```APIDOC ## Mount Sub-Application ### Description Mounts a Hono application as a sub-router at a specified path. ### Method MOUNT ### Endpoint [path] ### Parameters #### Path Parameters - **path** (string) - Required - Base path for the mounted app - **application** (HonoBase) - Required - The Hono instance to mount #### Example: Modular Architecture ```ts const api = new Hono() api.get('/users', (c) => c.json([])) api.get('/posts', (c) => c.json([])) const app = new Hono() app.mount('/api', api) // Routes: /api/users, /api/posts ``` ``` -------------------------------- ### Route Mounting and Nesting with route() Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md Demonstrates creating nested route groups with their own handlers and middleware using the `route()` pattern. ```APIDOC ## GET /api/users ### Description Retrieves a list of users. ### Method GET ### Endpoint /api/users ### Response #### Success Response (200) - [] (json) - An array of users. #### Response Example ```json [] ``` ## POST /api/users ### Description Creates a new user. ### Method POST ### Endpoint /api/users ### Response #### Success Response (201) - id (number) - The ID of the newly created user. #### Response Example ```json { "id": 1 } ``` ``` -------------------------------- ### Enable Server-Timing Header Source: https://github.com/honojs/hono/blob/main/_autodocs/middleware-reference.md Use the timing middleware to add Server-Timing headers for performance metrics. Import it from 'hono/timing'. ```typescript import { timing } from 'hono/timing' app.use(timing()) ``` -------------------------------- ### Extract Single Query Parameter Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md Use `c.req.query('key')` to get the value of a specific query parameter. ```typescript app.get('/search', (c) => { const q = c.req.query('q') // GET /search?q=hono // 'hono' return c.json({ q }) }) ``` -------------------------------- ### req.query(key?) Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get query string parameters. You can retrieve a specific parameter by its key or all parameters as an object. ```APIDOC ## req.query(key?) ### Description Get query string parameters. ### Method `query(): Record query(key: string): string | undefined` ### Parameters #### Path Parameters - **key** (string) - Optional. Query parameter name. ### Returns Single parameter value or object of all parameters. ### Example ```ts // Get single query param app.get('/search', (c) => { const q = c.req.query('q') // 'hono' return c.text(`Search for: ${q}`) }) // Get all query params app.get('/search', (c) => { const params = c.req.query() // { q: 'hono', limit: '10', offset: '0' } return c.json(params) }) // Usage: GET /search?q=hono&limit=10&offset=0 ``` ``` -------------------------------- ### req.url Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get the full request URL. This property returns the complete URL of the incoming request as a string. ```APIDOC ## req.url ### Description Get the full request URL. ### Property `c.req.url: string` ### Example ```ts app.get('/', (c) => { const url = c.req.url // 'https://example.com/path?query=value' return c.text(url) }) ``` ``` -------------------------------- ### Available Routers Configuration Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Demonstrates how to instantiate Hono with different router types: RegExpRouter, TrieRouter, PatternRouter, and SmartRouter with custom configurations. ```typescript import { RegExpRouter, TrieRouter, PatternRouter, SmartRouter } from 'hono/router' // RegExpRouter: Uses regex for matching (fast) const appRegex = new Hono({ router: new RegExpRouter() }) // TrieRouter: Uses trie data structure (optimized for many routes) const appTrie = new Hono({ router: new TrieRouter() }) // PatternRouter: Uses pattern matching const appPattern = new Hono({ router: new PatternRouter() }) // SmartRouter: Automatically selects (recommended) const appSmart = new Hono({ router: new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] }) }) ``` -------------------------------- ### Get Single Request Header Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md The `header(name)` method retrieves the value of a specific request header. ```APIDOC ## Get Single Request Header ### Description Get a single request header value by its name. ### Method `header(name: string): string | undefined` ### Parameters #### Path Parameters - **name** (string) - Required - Header name (case-insensitive) ### Returns Header value or undefined if not present. ### Example ```ts app.get('/', (c) => { const contentType = c.req.header('Content-Type') const userAgent = c.req.header('User-Agent') const custom = c.req.header('X-Custom-Header') return c.json({ contentType, userAgent, custom }) }) ``` ``` -------------------------------- ### Route Ordering Best Practices Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Shows the recommended practice of placing more specific routes before less specific ones to ensure correct matching. This prevents catch-all routes from intercepting requests intended for more detailed paths. ```typescript // Good: Specific routes first app.get('/users/me', (c) => c.text('Current user')) app.get('/users/:id', (c) => c.text('User by ID')) ``` -------------------------------- ### Custom Logging Middleware Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md An example of a custom middleware that logs the request method, path, and processing time. ```typescript // Custom logger app.use(async (c, next) => { const start = Date.now() await next() console.log(`${c.req.method} ${c.req.path} ${Date.now() - start}ms`) }) ``` -------------------------------- ### Serving Static Files with Adapters in Hono Source: https://github.com/honojs/hono/blob/main/docs/MIGRATION.md Use `serveStatic` from the appropriate adapter (e.g., `hono/cloudflare-workers`, `hono/bun`, `npm:hono/deno`) to serve static files. The `root` option specifies the directory to serve from. ```typescript // For Cloudflare Workers import { serveStatic } from 'hono/cloudflare-workers' // For Bun // import { serveStatic } from 'hono/bun' // For Deno // import { serveStatic } from 'npm:hono/deno' // ... app.get('/static/*', serveStatic({ root: './' })) ``` -------------------------------- ### JWT Authentication Middleware Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Example of configuring the `jwt` middleware with a secret key and algorithm, and retrieving the payload. ```typescript // JWT app.use(jwt({ secret: 'key', alg: 'HS256' })) const payload = c.get('jwtPayload') ``` -------------------------------- ### Get Single Cookie Source: https://github.com/honojs/hono/blob/main/_autodocs/helpers-reference.md Retrieves a specific cookie by its name from the request context. Returns undefined if the cookie is not found. ```typescript app.get('/', (c) => { const session = getCookie(c, 'sessionId') return c.json({ session }) }) ``` -------------------------------- ### Upgrade to WebSocket Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Demonstrates how to upgrade an HTTP request to a WebSocket connection using `upgradeWebSocket` helper. ```typescript import { upgradeWebSocket } from 'hono/helper/websocket' app.get('/ws', upgradeWebSocket({ onOpen: (ws) => ws.send('Welcome'), onMessage: (msg, ws) => ws.send(`Echo: ${msg}`), onClose: () => console.log('Closed') })) ``` -------------------------------- ### Deployment Options for Hono Applications Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Shows how to deploy a Hono application in different environments like Node.js, Bun, Cloudflare Workers, AWS Lambda, Deno, and Vercel. Ensure you import the correct 'serve' function for your environment. ```typescript // Node.js import { serve } from '@hono/node-server' serve(app) ``` ```typescript // Bun import { serve } from '@hono/bun' serve(app) ``` ```typescript // Cloudflare Workers export default app ``` ```typescript // AWS Lambda export const handler = handle(app) ``` ```typescript // Deno import { serve } from 'https://deno.land/std/http/server.ts' serve(app.fetch, { port: 3000 }) ``` ```typescript // Vercel export default handle(app) ``` -------------------------------- ### Hono Constructor Source: https://github.com/honojs/hono/blob/main/_autodocs/hono-core-api.md Creates a new instance of the Hono web framework. This is the primary entry point for building Hono applications. ```APIDOC ## new Hono() ### Description Creates an instance of the Hono web framework. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns `Hono` instance with routing methods and middleware support. ### Example ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hello, Hono!')) ``` ``` -------------------------------- ### Get All Query Parameters - Hono Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Retrieve all query string parameters as an object. Useful for accessing multiple parameters at once. ```typescript // Get all query params app.get('/search', (c) => { const params = c.req.query() // { q: 'hono', limit: '10', offset: '0' } return c.json(params) }) ``` -------------------------------- ### Extracting Single Path Parameter Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Get a specific path parameter value from the request. The extracted parameter is always a string. ```typescript app.get('/users/:id', (c) => { const id = c.req.param('id') // id is a string return c.json({ id }) }) ``` -------------------------------- ### req.header(name) Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get a single request header by name. This method is case-insensitive and returns the header value or undefined if not present. ```APIDOC ## req.header(name) ### Description Get a single request header. ### Method `header(name: string): string | undefined` ### Parameters #### Path Parameters - **name** (string) - Header name (case-insensitive) ### Returns Header value or undefined if not present. ### Example ```ts app.get('/', (c) => { const contentType = c.req.header('Content-Type') const auth = c.req.header('Authorization') return c.json({ contentType, auth }) }) ``` ``` -------------------------------- ### Extract All Path Parameters Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md Use `c.req.param()` without arguments to get an object containing all path parameters from the matched route. ```typescript app.get('/users/:userId/posts/:postId', (c) => { const params = c.req.param() // { userId: '123', postId: '456' } return c.json(params) }) ``` -------------------------------- ### HTTP Method Routing Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Defines routes for specific HTTP methods like GET, POST, PUT, DELETE, PATCH, and OPTIONS. ```APIDOC ## GET /items ### Description Retrieves a list of items. ### Method GET ### Endpoint /items ### Response Example ```json [] ``` --- ## POST /items ### Description Creates a new item. ### Method POST ### Endpoint /items ### Response Example ```json {} ``` ``` ```APIDOC ## PUT /items/:id ### Description Updates an existing item by its ID. ### Method PUT ### Endpoint /items/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the item to update. ### Response Example ```json {} ``` --- ## DELETE /items/:id ### Description Deletes an item by its ID. ### Method DELETE ### Endpoint /items/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the item to delete. ### Response Example ```json null ``` --- ## PATCH /items/:id ### Description Partially updates an existing item by its ID. ### Method PATCH ### Endpoint /items/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the item to patch. ### Response Example ```json {} ``` --- ## OPTIONS /items ### Description Returns allowed HTTP methods for the /items endpoint. ### Method OPTIONS ### Endpoint /items ### Response Example ```json null ``` ``` -------------------------------- ### Get Secure Cookie Source: https://github.com/honojs/hono/blob/main/_autodocs/helpers-reference.md Retrieves a cookie with a specified prefix, such as 'secure', from the request context. Useful for accessing cookies with security prefixes. ```typescript app.get('/', (c) => { const secure = getCookie(c, 'token', 'secure') return c.text(secure || 'Not found') }) ``` -------------------------------- ### Set Cookie with Options Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Shows how to set a cookie with various options like `maxAge`, `httpOnly`, and `secure`. ```typescript // Set setCookie(c, 'sessionId', 'abc123', { maxAge: 7 * 24 * 60 * 60, httpOnly: true, secure: true }) ``` -------------------------------- ### Extract All Repeated Query Parameters Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md Use `c.req.queries()` to get an object where keys map to arrays of values for repeated query parameters. ```typescript app.get('/filter', (c) => { const params = c.req.queries() // GET /filter?color=red&color=blue&size=large&size=small // { color: ['red', 'blue'], size: ['large', 'small'] } return c.json(params) }) ``` -------------------------------- ### Get Single Query Parameter - Hono Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Retrieve the value of a single query string parameter. Returns `undefined` if the parameter is not present. ```typescript // Get single query param app.get('/search', (c) => { const q = c.req.query('q') // 'hono' return c.text(`Search for: ${q}`) }) ``` -------------------------------- ### Get Path Parameters - Hono Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Extract path parameters defined in the route. Can retrieve a single parameter by key or all parameters as an object. ```typescript // Get single parameter app.get('/users/:id', (c) => { const id = c.req.param('id') // '123' return c.json({ id }) }) ``` ```typescript // Get all parameters app.get('/users/:userId/posts/:postId', (c) => { const params = c.req.param() // { userId: '123', postId: '456' } return c.json(params) }) ``` -------------------------------- ### Access Environment Bindings Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Illustrates how to access environment variables or bindings directly through `c.env`. ```typescript // Environment bindings c.env.DATABASE_URL c.env.API_KEY ``` -------------------------------- ### Serve Static Files Source: https://github.com/honojs/hono/blob/main/_autodocs/helpers-reference.md Serve static files from a specified root directory. You can optionally rewrite the request path before serving. ```typescript import { serveStatic } from 'hono/middleware/serve-static' app.use('/static/*', serveStatic({ root: './public' })) ``` ```typescript import { serveStatic } from 'hono/middleware/serve-static' // or with custom root app.use('/assets/*', serveStatic({ root: './assets', rewriteRequestPath: (path) => path.replace(/^\/assets/, '') })) ``` -------------------------------- ### Enable Response Compression Source: https://github.com/honojs/hono/blob/main/_autodocs/middleware-reference.md Use the compress middleware to enable gzip, deflate, or brotli compression for responses. Import it from 'hono/compress'. ```typescript import { compress } from 'hono/compress' app.use(compress()) ``` -------------------------------- ### Conditional Middleware Execution Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Shows how to apply middleware conditionally, for example, to specific routes like '/api/*', and includes authorization logic. ```typescript // Conditional middleware app.use('/api/*', async (c, next) => { const token = c.req.header('Authorization') if (!token) return c.text('Unauthorized', 401) await next() }) ``` -------------------------------- ### Get Cookie Value Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Demonstrates how to retrieve a specific cookie's value using `getCookie(c, 'sessionId')` or all cookies when no key is provided. ```typescript // Get const sessionId = getCookie(c, 'sessionId') const allCookies = getCookie(c) ``` -------------------------------- ### Catch-All Pattern Routing Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Use '/*' with `app.all()` to create a catch-all route that matches any HTTP method and any path. This is typically used for 404 Not Found responses. ```typescript app.all('/*', (c) => { return c.json({ method: c.req.method, path: c.req.path, message: 'Not found' }, 404) }) ``` -------------------------------- ### Mounting Applications for Path Prefixing Source: https://github.com/honojs/hono/blob/main/_autodocs/routing-patterns.md Mount another Hono application onto the main application using `app.mount()`. This allows for modular routing and organization, effectively creating a sub-application with its own routes under a specified path. ```typescript const api = new Hono() api.get('/users', (c) => c.json([])) api.post('/users', (c) => c.json({}, 201)) const app = new Hono() app.mount('/api', api) // Routes: GET /api/users, POST /api/users ``` -------------------------------- ### req.raw Source: https://github.com/honojs/hono/blob/main/_autodocs/context-api.md Get the raw Web Standard Request object. This allows access to the underlying Request object and its properties like `cf` metadata. ```APIDOC ## req.raw ### Description Get the raw Web Standard Request object. ### Property `c.req.raw: Request` ### Example ```ts app.post('/', (c) => { const raw = c.req.raw const cf = raw.cf // Cloudflare metadata const headers = raw.headers return c.text('OK') }) ``` ``` -------------------------------- ### Import Main Framework and Context Source: https://github.com/honojs/hono/blob/main/_autodocs/quick-reference.md Import the core Hono framework and Context type for application development. Also imports type definitions for environment, handlers, and middleware. ```typescript // Main framework import { Hono } from 'hono' import { Context } from 'hono' import type { Env, Handler, MiddlewareHandler } from 'hono' ``` -------------------------------- ### Get All Request Headers Source: https://github.com/honojs/hono/blob/main/_autodocs/request-api.md Obtain all request headers as a key-value object using `c.req.headers()`. This provides a convenient way to inspect all incoming headers. ```typescript app.post('/', (c) => { const allHeaders = c.req.headers() return c.json(allHeaders) }) ``` -------------------------------- ### Middleware Reference Source: https://github.com/honojs/hono/blob/main/_autodocs/MANIFEST.txt Documentation for built-in middleware covering authentication, security, performance, logging, and utilities. ```APIDOC ## Middleware Reference This section lists and describes the various built-in middleware modules available in Hono. ### Authentication - **`basicAuth`**: For Basic HTTP authentication. - **`bearerAuth`**: For Bearer token authentication. - **`jwt`**: For JSON Web Token validation. ### CORS and Security - **`cors`**: Handles Cross-Origin Resource Sharing. - **`secureHeaders`**: Adds security-related headers. - **`csrf`**: Protects against Cross-Site Request Forgery. - **`ipRestriction`**: Restricts access based on IP address. ### Performance - **`compress`**: Compresses response bodies. - **`cache`**: Implements caching strategies. - **`etag`**: Adds ETag headers for caching. ### Logging - **`logger`**: Logs incoming requests. - **`timing`**: Measures request processing time. - **`requestId`**: Generates and tracks request IDs. ### Request Processing - **`bodyLimit`**: Limits the size of the request body. - **`methodOverride`**: Allows overriding the HTTP method. - **`timeout`**: Sets a timeout for request processing. ### Utilities - **`poweredBy`**: Adds a `X-Powered-By` header. - **`prettyJSON`**: Formats JSON responses for readability. - **`language`**: Handles content negotiation based on `Accept-Language` header. ```