Skip to content

Latest commit

 

History

History
107 lines (74 loc) · 2.81 KB

README.md

File metadata and controls

107 lines (74 loc) · 2.81 KB

@gradienttim/hono-versioning

Type-safe API versioning for Hono, with URI, header and query strategies.

  • Three strategies: /v1/users, X-API-Version: v1 or ?version=v1
  • Fully typed: the RPC client (hc) knows every version and its routes
  • Plain Hono apps: each version is a normal Hono instance with its own middleware, onError and notFound
  • Runs anywhere Hono runs: Bun, Deno, Node.js, Cloudflare Workers and other edge runtimes

📖 Documentation

Install

bun add @gradienttim/hono-versioning hono
# or: npm install @gradienttim/hono-versioning hono

Usage

import { 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 app

Use 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=v1

Custom header and query names, error handling, disabling the default version and the typed client are covered in the documentation. Runnable examples are in examples/.

Migration

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 app
With 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).

License

MIT