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

middleware

244 notes in this subject, read out of this brain and free to use. This is page 4 of 5.

Request ID Middleware import and setup

Import the requestId middleware from 'hono/request-id'. Apply it with app.use('*', requestId()) to generate a unique ID for each request. Access the request ID in handlers via c.get('requestId').

Request ID Middleware TypeScript typing

To explicitly type the request ID in context variables, import RequestIdVariables from 'hono/request-id' and pass it as the Variables generic: new Hono<{ Variables: RequestIdVariables }>()

Request ID Middleware platform-specific IDs

Platforms like AWS Lambda, Cloudflare, Deno, and Fastly generate their own request IDs. To use platform-specific IDs instead of generating new ones, pass a custom generator function to the requestId middleware that captures and returns the platform's request ID.

Request ID Middleware example with custom ID

Example showing how to set a custom request ID via the X-Request-Id header: const app = new Hono() app.use('*', requestId()) app.get('/', (c) => { return c.text(`${c.get('requestId')}`) }) const res = await app.request('/', { headers: { 'X-Request-Id': 'your-custom-id', }, }) console.log(await res.text()) // your-custom-id

Timeout middleware cannot be used with streams

The timeout middleware cannot be used with stream responses. For streaming endpoints like SSE (Server-Sent Events), use stream.close() and setTimeout() together instead. Set a timer that calls stream.close() and use stream.onAbort() to handle client disconnections and clear the timeout.

Timeout middleware import

The Timeout Middleware is imported from 'hono/timeout'. Import statement: import { timeout } from 'hono/timeout'

Timeout middleware basic usage

The timeout middleware accepts a duration in milliseconds as its first parameter. Basic usage: app.use('/api', timeout(5000)) applies a 5-second timeout to requests matching the path. The middleware will reject the promise and throw an error if the specified duration is exceeded.

Timeout middleware custom exception

The timeout middleware accepts an optional second parameter for a custom exception handler. This can be either a function that receives context and returns an HTTPException, or a static HTTPException instance. Example function form: const customTimeoutException = (context) => new HTTPException(408, { message: `Request timeout...` }). The function receives context parameter with access to the request object.

Timeout middleware with SSE example

Example of managing timeouts with Server-Sent Events using streamSSE: Set a timer with setTimeout() that calls stream.close() after the desired duration. Use stream.onAbort() to listen for client disconnections and clear the timeout with clearTimeout(). Keep a running flag to control the loop and write messages with stream.writeSSE(). This pattern allows timeout behavior for streaming responses where the timeout middleware cannot be applied.

Timeout middleware order consideration

Middleware order matters when using the timeout middleware, especially when combined with error-handling or other timing-related middleware, as the order might affect the behavior of the timeout middleware.

Server-Timing middleware options: crossOrigin

The crossOrigin option is a boolean, string, or function that takes Context and returns boolean or string (optional, default false). Controls which origins can read the Server-Timing header. If false, only current origin. If true, all origins. If string, comma-separated list of allowed domains. This sets the Timing-Allow-Origin header.

Server-Timing middleware import

Import the timing middleware and related functions from 'hono/timing': timing, setMetric, startTime, endTime, wrapTime, and the TimingVariables type.

Server-Timing middleware usage

Add the timing middleware to your Hono app with app.use(timing()). Define a Variables type as TimingVariables to allow c.get('metric') type inference. Use setMetric(c, name, value) to add custom metrics, startTime(c, name) to start a timer, endTime(c, name) to end it, or wrapTime(c, name, promise) to wrap a promise with timing.

Server-Timing middleware options: total

The total option is a boolean (optional, default true). When true, shows the total response time in the Server-Timing header.

Server-Timing middleware options: enabled

The enabled option is a boolean or function that takes Context and returns boolean (optional, default true). Controls whether timings are added to response headers. Can be used to conditionally enable timing based on request properties.

Server-Timing middleware options: totalDescription

The totalDescription option is a boolean (optional, default 'Total Response Time'). Sets the description text for the total response time metric in the Server-Timing header.

Server-Timing middleware on Cloudflare Workers limitation

On Cloudflare Workers, timer metrics from the Server-Timing middleware may not be accurate because timers only show the time of last I/O operation.

Server-Timing middleware options: autoEnd

The autoEnd option is a boolean (optional). If true, timers started with startTime() automatically end at the end of the request. If false, manually ended timers will not be shown.

secureHeaders custom nonce generator

Pass a ContentSecurityPolicyOptionHandler function to scriptSrc or styleSrc that receives the context and returns a nonce string. The function is called on every request and can set custom context variables.

secureHeaders middleware import

Import secureHeaders from 'hono/secure-headers'. The middleware simplifies setup of security headers inspired by Helmet and allows control over activation and deactivation of specific security headers.

secureHeaders default usage

Call app.use(secureHeaders()) with no arguments to apply optimal default security header settings.

secureHeaders suppress headers

Pass an options object with specific header keys set to false to suppress unnecessary headers. Example: secureHeaders({ xFrameOptions: false, xXssProtection: false })

secureHeaders override header values

Pass string values in the options object to override default header values. Example: secureHeaders({ strictTransportSecurity: 'max-age=63072000; includeSubDomains; preload', xFrameOptions: 'DENY', xXssProtection: '1' })

secureHeaders option: contentSecurityPolicy

Option: contentSecurityPolicy. Header: Content-Security-Policy. Default: No Setting. Accepts an object with directives like defaultSrc, baseUri, childSrc, connectSrc, fontSrc, formAction, frameAncestors, frameSrc, imgSrc, manifestSrc, mediaSrc, objectSrc, reportTo, reportUri, sandbox, scriptSrc, scriptSrcAttr, scriptSrcElem, styleSrc, styleSrcAttr, styleSrcElem, upgradeInsecureRequests, workerSrc.

secureHeaders option: contentSecurityPolicyReportOnly

Option: contentSecurityPolicyReportOnly. Header: Content-Security-Policy-Report-Only. Default: No Setting. Accepts same configuration as contentSecurityPolicy but only reports violations without blocking.

secureHeaders option: trustedTypes

Option: trustedTypes. Header: Trusted Types. Default: No Setting. Part of Content-Security-Policy configuration for trusted types policy.

secureHeaders option: requireTrustedTypesFor

Option: requireTrustedTypesFor. Header: Require Trusted Types For. Default: No Setting. Part of Content-Security-Policy configuration.

secureHeaders option: crossOriginEmbedderPolicy

Option: crossOriginEmbedderPolicy. Header: Cross-Origin-Embedder-Policy. Value: require-corp. Default: False.

secureHeaders option: crossOriginOpenerPolicy

Option: crossOriginOpenerPolicy. Header: Cross-Origin-Opener-Policy. Value: same-origin. Default: True.

secureHeaders option: originAgentCluster

Option: originAgentCluster. Header: Origin-Agent-Cluster. Value: ?1. Default: True.

secureHeaders option: reportingEndpoints

Option: reportingEndpoints. Header: Reporting-Endpoints. Default: No Setting. Accepts an array of objects with 'name' and 'url' properties for configuring reporting endpoints.

secureHeaders option: xContentTypeOptions

Option: xContentTypeOptions. Header: X-Content-Type-Options. Value: nosniff. Default: True.

secureHeaders option: xDnsPrefetchControl

Option: xDnsPrefetchControl. Header: X-DNS-Prefetch-Control. Value: off. Default: True.

secureHeaders option: xDownloadOptions

Option: xDownloadOptions. Header: X-Download-Options. Value: noopen. Default: True.

secureHeaders option: xFrameOptions

Option: xFrameOptions. Header: X-Frame-Options. Value: SAMEORIGIN. Default: True.

secureHeaders option: xPermittedCrossDomainPolicies

Option: xPermittedCrossDomainPolicies. Header: X-Permitted-Cross-Domain-Policies. Value: none. Default: True.

secureHeaders option: reportTo

Option: reportTo. Header: Report-To. Default: No Setting. Accepts an array of objects with 'group', 'max_age', and 'endpoints' properties for configuring report-to headers.

secureHeaders option: permissionPolicy

Option: permissionPolicy. Header: Permissions-Policy. Default: No Setting. Allows control of browser features and APIs with options like fullscreen, bluetooth, payment, syncXhr, camera, microphone, geolocation, usb, accelerometer, gyroscope, magnetometer.

X-Powered-By header removal

The secureHeaders middleware removes the X-Powered-By header by default (set to True), deleting the header entirely.

secureHeaders middleware order matters

The order of middleware matters when multiple middlewares modify the same header. secureHeaders() removes x-powered-by if specified before poweredBy(), but poweredBy() will add it back if specified before secureHeaders().

secureHeaders nonce support

Import NONCE from 'hono/secure-headers' and add it to scriptSrc or styleSrc arrays to automatically inject nonce attributes. The nonce value is accessible via c.get('secureHeadersNonce') after importing SecureHeadersVariables type.

secureHeaders option: referrerPolicy

Option: referrerPolicy. Header: Referrer-Policy. Value: no-referrer. Default: True.

secureHeaders permissionsPolicy values

permissionsPolicy directives accept array of origins, true for wildcard '*', false for 'none', or an empty array '()'. Example: fullscreen: ['self'], bluetooth: ['none'], payment: ['self', 'https://example.com'], camera: false, microphone: true, geolocation: ['*'], usb: ['self', 'https://a.example.com'], accelerometer: ['https://*.example.com'], gyroscope: ['src'].

secureHeaders CSP example configuration

Example secureHeaders configuration with contentSecurityPolicy object containing directives: defaultSrc: ["'self'"], baseUri: ["'self'"], childSrc: ["'self'"], connectSrc: ["'self'"], fontSrc: ["'self'", 'https:', 'data:'], formAction: ["'self'"], frameAncestors: ["'self'"], frameSrc: ["'self'"], imgSrc: ["'self'", 'data:'], manifestSrc: ["'self'"], mediaSrc: ["'self'"], objectSrc: ["'none'"], reportTo: 'endpoint-1', reportUri: '/csp-report', sandbox: ['allow-same-origin', 'allow-scripts'], scriptSrc: ["'self'"], scriptSrcAttr: ["'none'"], scriptSrcElem: ["'self'"], styleSrc: ["'self'", 'https:', "'unsafe-inline'"], styleSrcAttr: ['none'], styleSrcElem: ["'self'", 'https:', "'unsafe-inline'"], upgradeInsecureRequests: [], workerSrc: ["'self'"].

secureHeaders option: xXssProtection

Option: xXssProtection. Header: X-XSS-Protection. Value: 0. Default: True.

secureHeaders option: strictTransportSecurity

Option: strictTransportSecurity. Header: Strict-Transport-Security. Value: max-age=15552000; includeSubDomains. Default: True.

appendTrailingSlash and trimTrailingSlash middleware

The trailing slash middleware handles trailing slash in the URL on GET requests. appendTrailingSlash redirects URLs to add a trailing slash if the content was not found. trimTrailingSlash removes the trailing slash. Import from 'hono/trailing-slash'.

Trailing slash middleware import

Import appendTrailingSlash and trimTrailingSlash from 'hono/trailing-slash'.

trimTrailingSlash usage example

Example: A GET request of /about/me/ redirects to /about/me. Import Hono and trimTrailingSlash, create app with Hono({ strict: true }), use app.use(trimTrailingSlash()), and define app.get('/about/me', (c) => c.text('Without Trailing Slash')).

Trailing slash middleware alwaysRedirect option

The alwaysRedirect option is an optional boolean. By default, trailing slash middleware only redirects when the response status is 404. When alwaysRedirect is set to true, the middleware redirects before executing handlers. This is useful for wildcard routes (*) where the default behavior doesn't work. Available for both trimTrailingSlash and appendTrailingSlash.

Trailing slash middleware skip option

The skip option is an optional function with signature (path: string) => boolean. It determines whether the redirect should be skipped based on the request path. If the function returns true, the redirect will be skipped. This is useful to exclude certain paths, such as those with file extensions, from being redirected. Available for both trimTrailingSlash and appendTrailingSlash.

Trailing slash middleware skip example

Example of skip option: app.use(appendTrailingSlash({ skip: (path) => /\.\w+$/.test(path) })) will skip redirecting paths with file extensions.

Trailing slash middleware activation condition

Trailing slash middleware is enabled when the request method is GET and the response status is 404.

Monitoring and tracing middleware packages available

Third-party monitoring and tracing middleware for Hono includes: Apitally (API monitoring & analytics), Highlight.io, LogTape (Logging), OpenTelemetry, Prometheus Metrics, Sentry, and Pino logger.

Server and adapter middleware packages available

Third-party server and adapter middleware for Hono includes: GraphQL Server, oRPC, and tRPC Server.

Transpiler middleware packages available

Third-party transpiler middleware for Hono includes: Bun Transpiler and esbuild Transpiler.

Queue and job processing middleware packages available

Third-party queue and job processing middleware for Hono includes: GlideMQ (Message Queue REST API + SSE).

UI and renderer middleware packages available

Third-party UI and renderer middleware for Hono includes: Qwik City, React Compatibility, and React Renderer.

Internationalization middleware packages available

Third-party internationalization middleware for Hono includes: Intlayer i18n.

Utility middleware packages available

Third-party utility middleware for Hono includes: Bun Compress, Cap Checkpoint, Event Emitter, Geo, Hono Rate Limiter, Hono Problem Details (RFC 9457), Hono Simple DI, InferDI, Idempotency (Stripe-style idempotency keys), idempot-js (spec-compliant middleware supporting redis, postgres, mysql, sqlite), jsonv-ts (Validator, OpenAPI, MCP), MCP, RONIN (Database), Session, StitchAPI (Typed, resilient API calls + SSE), tsyringe, and User Agent based Blocker.

Give your agent this brain