Type-safe API versioning for Hono, with URI, header and query strategies.
- Three strategies:
/v1/users,X-API-Version: v1or?version=v1 - Fully typed: the RPC client (
hc) knows every version and its routes - Plain Hono apps: each version is a normal
Honoinstance with its own middleware,onErrorandnotFound - Runs anywhere Hono runs: Bun, Deno, Node.js, Cloudflare Workers and other edge runtimes
bun add @gradienttim/hono-versioning hono
# or: npm install @gradienttim/hono-versioning honoimport { Hono } from 'hono'
import { versioning } from '@gradienttim/hono-versioning'
const v1 = new Hono().get('/users', (c) => c.json([{ name: 'Ada' }]))
const v2 = new Hono().get('/users', (c) => c.json({ data: [{ name: 'Ada' }] }))
const app = versioning({
versions: { v1, v2 },
defaultVersion: 'v2',
})
// GET /v1/users -> v1
// GET /v2/users -> v2
// GET /users -> v2 (default version)
export default appUse a header or query parameter instead of the path:
versioning({ versions: { v1, v2 }, defaultVersion: 'v2', strategy: { type: 'header' } }) // X-API-Version: v1
versioning({ versions: { v1, v2 }, defaultVersion: 'v2', strategy: { type: 'query' } }) // ?version=v1Custom header and query names, error handling, disabling the default version and the typed client are covered in
the documentation. Runnable examples are in examples/.
Your existing app becomes the first version. Routes, middleware, onError and notFound stay as they are; only
the top-level app changes.
Without options
// Before
const app = new Hono().get('/users', (c) => c.json([{ name: 'Ada' }]))
export default app// After
const v1 = new Hono().get('/users', (c) => c.json([{ name: 'Ada' }]))
const app = versioning({
versions: { v1 },
defaultVersion: 'v1', // existing clients calling /users keep working
})
export default appWith options
Options you passed to new Hono() move to the second argument of versioning(), which creates the top-level app:
// Before
const app = new Hono({ strict: false }).get('/users', (c) => c.json([{ name: 'Ada' }]))// After
const v1 = new Hono({ strict: false }).get('/users', (c) => c.json([{ name: 'Ada' }]))
const app = versioning(
{ versions: { v1 }, defaultVersion: 'v1' },
{ strict: false } // same options as `new Hono(...)`
)Keep the options on the version apps too if their own routing depends on them (e.g. strict).