Skip to content

Routers

Router - itty-router updated in v5

~550 bytes Bundle Size

This is the core functionality of IttyRouter, with the addition of before, finally, and catch stages for configuration-based flow control. This allows batteries-included routers like AutoRouter to function.

Example

ts
import { Router, error, json, withParams } from 'itty-router'

const router = Router({
  before: [withParams],
  catch: error,
  finally: [json],
})

router
  .get('/json', () => ({ foo: 'bar', array: [1,2,3] }))
  .get('/params/:id', ({ id }) => id)
  .all('*', () => error(404))

export default router

RouterOptions

Router(options?: RouterOptions): RouterType

NameType(s)Default ValueDescription
basestringPrefixes all routes with this string. For example, Router({ base: '/docs' }) would prefix all route matches with /docs.
before v5RouteHandler[][]An array of route handlers/middleware to execute on requests before any route-matching
catch v5ErrorHandlerA 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 v5ResponseHandler[][]An array of response handlers to execute on any response after route-matching is complete
routes advancedRouteEntry[][]Array of manual routes for preloading
...other v4.1+anyAny 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.

Released under the MIT License.