Routers
AutoRouter - itty-router new in v5
*includes error
, json
, and withParams
AutoRouter is a batteries-included thin-wrapper of Router
, with the following behaviors:
withParams
middleware is included by default, upstream of any otherbefore
stage handlers.json
response formatter is included by default. By default, all non-Responses will be converted to JSON. Override by setting theformat
option.error
is included by default ascatch: error
to catch uncaught errors (returning with a generic 500, unless a specificStatusError
is thrown).- A generic 404 will be returned on any un-matched route. This is equivalent to adding
router.all('*', () => error(404))
to your routes, and may be overridden using themissing
option (below).
Example
ts
import { AutoRouter } from 'itty-router'
const router = AutoRouter()
router
.get('/json', () => ({ foo: 'bar', array: [1,2,3] }))
.get('/params/:id', ({ id }) => id)
export default router
AutoRouterOptions
AutoRouter(options?: AutoRouterOptions): RouterType
Name | Type(s) | Default Value | Description |
---|---|---|---|
base | string | Prefixes all routes with this string. For example, Router({ base: '/docs' }) would prefix all route matches with /docs . | |
before v5 | Array of RequestHandler | [] | An array of route handlers/middleware to execute on requests before any route-matching |
catch v5 | ErrorHandler | error | A single error handler to catch any thrown error. This may be used to return a Response, log errors, etc. If thrown during the before stage or route-matching, the finally stage will still be applied after this catch. Conversely, if an error is thrown during the finally stage, this will still fire, but none of the finally stage handlers will be applied to it. |
finally v5 | Array of ResponseHandler | [] | An array of response handlers to execute on any response after route-matching is complete |
format v5 | ResponseHandler | json | The default formatter for unformatted responses. This may be replaced (e.g. with text ) or set to a no-op () => {} to avoid formatting altogether. |
missing v5 | RequestHandler | () => error(404) | The default 404 message. To prevent a 404, enter a no-op () => {} . |
routes advanced | Array of RouteEntry | [] | Array of manual routes for preloading |
...other v4.1+ | any | Any other object attributes that don't conflict with methods will be embedded in the final Router object. This is useful for attaching additional information to the router for exporting. For example: Router({ port: 3001 }) could be used to control the port in a Bun setup. |