CodeSampleX

샘플

hono 4.13.2: Compose nested sub-routers with onion middleware context propagation and centralized error handling in Hono

검증된 샘플 — npm hono 4.13.2: Compose nested sub-routers with onion middleware context propagation and centralized error handling in Hono. node 22 · linux…

sha256:9f3af537033dce66441d0e2bec7c12895574b570ef881d9073aebea003ffc51b

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

케이스

HOW
목표
Compose nested sub-routers with onion middleware context propagation and centralized error handling in Hono
패키지
심벌
  • Hono
  • c.set
  • c.get
  • app.route
  • app.onError
환경
node
생성일
2026-08-17T13:56:13Z

컨트랙트

  1. Root onion middleware intercepts nested sub-app routes, propagates context variables set with c.set() to downstream handlers, and mutates response headers after await next().
  2. Multi-segment path parameters within mounted sub-routers are extracted via c.req.param() alongside inherited context variables.
  3. Centralized app.onError catches HTTPException instances thrown in nested routes and returns custom status codes with preserved context state.
  4. Unmatched routes traverse outer onion middleware and return 404 with middleware-injected response headers.

파일

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Hono Nested Routing, Onion Middleware, and Error Handling

## Prior Findings

A search for known solutions on the target package returned sample `sha256:4119fb31a4aae36adedb382471bf336dc173784bfa20d638562f477ab0d9702c`, which verified basic route definitions (`app.get`, `app.post`) and simple parameter parsing with `c.req.param`.

This sample proves a distinct set of behaviors: multi-level route composition with `app.route`, context state propagation with `c.set` and `c.get` across nested routers, onion middleware execution order with downstream header mutations, and centralized error handling with `app.onError` and `HTTPException`.

## Pinned Release

- `hono`: `4.13.2` (pinned exactly in `package.json` and `package-lock.json`)

## Observed Behaviors

1. **Onion Middleware Lifecycle**:
   - Middleware registered on the root router with `app.use('*', async (c, next) => { ... await next(); ... })` executes before sub-routers and handlers.
   - Code before `await next()` sets context variables (`c.set('traceId', ...)`).
   - Code after `await next()` executes after handlers and nested middleware finish, enabling post-downstream response header modifications (`c.header(...)`).

2. **Hierarchical Route Composition & Parameter Extraction**:
   - Sub-routers mounted via `app.route('/api', api)` inherit context variables set by outer middleware.
   - Handlers in mounted sub-routers extract multi-segment parameters (e.g., `/catalog/:categoryId/:itemId`) via `c.req.param('categoryId')` and `c.req.param('itemId')` while simultaneously accessing inherited context variables via `c.get('traceId')`.

3. **Centralized Error Handling**:
   - When handlers in sub-routers throw `HTTPException`, root `app.onError` catches the exception without unhandled rejections.
   - Handlers in `app.onError` access context variables set during earlier middleware execution and return structured JSON responses with the appropriate HTTP status code.

4. **In-Memory Request Dispatch**:
   - Requests dispatched via `app.request('http://localhost/...')` run the full middleware and routing pipeline in-memory using standard Web Request and Response semantics.
csx.json
{"case":{"caseId":"case:sha256:3a0217c6f4d0419bbb85ea7c0c0db880733e37401fcf3d53a69bd520441741a3","contract":["Root onion middleware intercepts nested sub-app routes, propagates context variables set with c.set() to downstream handlers, and mutates response headers after await next().","Multi-segment path parameters within mounted sub-routers are extracted via c.req.param() alongside inherited context variables.","Centralized app.onError catches HTTPException instances thrown in nested routes and returns custom status codes with preserved context state.","Unmatched routes traverse outer onion middleware and return 404 with middleware-injected response headers."],"goal":"Compose nested sub-routers with onion middleware context propagation and centralized error handling in Hono","kind":"HOW","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["Hono","c.set","c.get","app.route","app.onError"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/hono@4.13.2"],"schemaVersion":1,"symbols":["Hono","c.set","c.get","app.route","app.onError"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-hono-version-depth",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-hono-version-depth",
      "version": "1.0.0",
      "dependencies": {
        "hono": "4.13.2"
      }
    },
    "node_modules/hono": {
      "version": "4.13.2",
      "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.2.tgz",
      "integrity": "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA==",
      "license": "MIT",
      "engines": {
        "node": ">=16.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-hono-version-depth",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "hono": "4.13.2"
  }
}
src/index.mjs
import { Hono } from 'hono';
import { HTTPException } from 'hono/http-exception';

export function createApp() {
  const app = new Hono();

  // Root onion middleware
  app.use('*', async (c, next) => {
    c.set('traceId', 'req-trace-42');
    c.set('startedAt', 1000);

    await next();

    c.header('X-Trace-Id', c.get('traceId'));
    c.header('X-Pipeline-Stage', 'completed');
  });

  // Sub-router for API resources
  const api = new Hono();

  api.use('*', async (c, next) => {
    c.set('apiScope', 'v1');
    await next();
  });

  api.get('/catalog/:categoryId/:itemId', (c) => {
    const categoryId = c.req.param('categoryId');
    const itemId = c.req.param('itemId');
    const traceId = c.get('traceId');
    const apiScope = c.get('apiScope');

    return c.json({
      categoryId,
      itemId,
      traceId,
      apiScope,
      ok: true,
    }, 200);
  });

  api.get('/protected-action', () => {
    throw new HTTPException(401, { message: 'Unauthorized action' });
  });

  // Mount sub-router under /api prefix
  app.route('/api', api);

  // Centralized error handler
  app.onError((err, c) => {
    const traceId = c.get('traceId') ?? 'unknown';
    if (err instanceof HTTPException) {
      return c.json({
        error: err.message,
        status: err.status,
        traceId,
      }, err.status);
    }
    return c.json({ error: 'Internal error', traceId }, 500);
  });

  return app;
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import { createApp } from '../src/index.mjs';

const app = createApp();

// 1. Nested sub-app route with onion middleware and context propagation
const successRes = await app.request('http://localhost/api/catalog/electronics/laptop-99');
assert.equal(successRes.status, 200);
assert.equal(successRes.headers.get('x-trace-id'), 'req-trace-42');
assert.equal(successRes.headers.get('x-pipeline-stage'), 'completed');

const successBody = await successRes.json();
assert.deepEqual(successBody, {
  categoryId: 'electronics',
  itemId: 'laptop-99',
  traceId: 'req-trace-42',
  apiScope: 'v1',
  ok: true,
});

// 2. Centralized error handling for nested sub-app HTTPException
const errorRes = await app.request('http://localhost/api/protected-action');
assert.equal(errorRes.status, 401);
assert.equal(errorRes.headers.get('x-trace-id'), 'req-trace-42');

const errorBody = await errorRes.json();
assert.deepEqual(errorBody, {
  error: 'Unauthorized action',
  status: 401,
  traceId: 'req-trace-42',
});

// 3. Unmatched route passes through outer onion middleware and returns 404
const notFoundRes = await app.request('http://localhost/api/unknown-endpoint');
assert.equal(notFoundRes.status, 404);
assert.equal(notFoundRes.headers.get('x-trace-id'), 'req-trace-42');
assert.equal(notFoundRes.headers.get('x-pipeline-stage'), 'completed');

console.log('CONTRACT PASS: nested sub-app routing, onion middleware, and error handling verified');

오리진 시더

csx-seed