Routing
Introduction
A route connects an HTTP method and a path to the code that should answer it. Plinth routes are registered on a Router from @plinthjs/http. The router matches an incoming method, path and host, extracts parameters, and hands the matched route to the HttpKernel, which runs middleware and calls your handler.
In an application created by the scaffolder, routes live in src/routes/web.ts (and src/routes/api.ts for API apps). Each file exports a function that receives the router, and src/server.ts builds the router and kernel from them.
pnpm add @plinthjs/httpBasic routes
The simplest route takes a path and a closure. The closure receives the Request and may return a string, an object, a Response, or nothing.
import { Response, Router } from '@plinthjs/http'
const router = new Router()
router.get('/', () => 'Hello Plinth') // HTML response
router.get('/status', () => ({ ok: true })) // JSON response
router.get('/teapot', () => Response.make('short and stout', 418))
router.delete('/cache', () => null) // 204 No ContentThe kernel coerces the return value like this: a Response is sent as is, a string becomes an HTML response, null or undefined becomes 204 No Content, and any other object becomes JSON.
Available verbs
There is a method for each verb: get, post, put, patch, delete and options. A HEAD request is answered by the matching GET route with the body removed.
To answer several verbs with one handler use on() or any():
router.on(['GET', 'POST'], '/contact', handler) // GET and POST only
router.any('/ping', () => 'pong') // GET, POST, PUT, PATCH, DELETE, OPTIONSWhen the path exists but not for the request's verb, the kernel answers 405 Method Not Allowed and sets the Allow header. When nothing matches, it answers 404.
Redirect and view routes
router.redirect('/old-docs', '/docs') // 302
router.permanentRedirect('/older-docs', '/docs') // 301
router.redirect('/moved', '/new', 307) // custom status
router.view('/welcome', 'welcome', { name: 'Ada' })@plinthjs/http has no template engine, so router.view() hands the view name, the data and the request to a renderer you install. Pass it as the viewRenderer constructor option, or call renderViewsUsing():
router.renderViewsUsing((view, data, req) => `rendering ${view} for ${String(data.name)}`)Dispatching a view route with no renderer installed throws an error that tells you how to install one. See Views for the view engine.
Route parameters
Wrap a segment in braces to capture it. Parameters are always strings, and values are URL-decoded for you. Read them with req.param():
router.get('/users/{id}', (req) => ({ id: req.param('id') }))
router.get('/posts/{post}/comments/{comment}', (req) => req.params())
// GET /posts/3/comments/9 => { post: '3', comment: '9' }req.param(name, default) returns the default when the parameter is absent, and req.params() returns the whole bag.
Optional parameters
Add a question mark to make a segment optional, and give param() a default:
router.get('/posts/{page?}', (req) => ({ page: req.param('page', '1') }))
// GET /posts => { page: '1' }
// GET /posts/3 => { page: '3' }Constraining parameters
By default a parameter matches any non-empty segment. Chain where() or one of its shortcuts to restrict it. A value that fails its constraint makes the route not match at all, so the request falls through to later routes and finally to a 404. Patterns are anchored: the whole value must match.
router.get('/users/{id}', showUser).whereNumber('id')
router.get('/tags/{tag}', showTag).whereAlpha('tag')
router.get('/codes/{code}', showCode).whereAlphaNumeric('code')
router.get('/orders/{order}', showOrder).whereUuid('order')
router.get('/events/{event}', showEvent).whereUlid('event')
router.get('/files/{kind}', showFile).whereIn('kind', ['images', 'videos'])
router.get('/archive/{year}/{slug}', showArchive).where({
year: '[0-9]{4}',
slug: /[a-z0-9-]+/,
})You can also set constraints once for a whole group, see Route groups.
Named routes
Name a route with name() so you can generate its URL without hard coding the path:
router.get('/users/{id}', showUser).name('users.show')
router.url('users.show', { id: 7 }) // => '/users/7'
router.url('users.show', { id: 7 }, { tab: 'posts' }) // => '/users/7?tab=posts'router.url() throws if the name is unknown or a required parameter is missing. Optional parameters may be omitted. Inside a handler or middleware, req.routeIs('users.*') tells you whether the matched route's name fits a wildcard pattern. See URL generation for more.
Route groups
A group applies a shared prefix, middleware, parameter constraints or domain to every route registered inside its callback. Groups nest, and prefixes and middleware accumulate.
router.group({ prefix: '/api', middleware: 'auth' }, (r) => {
r.get('/me', showProfile).name('me')
r.group({ prefix: '/v2', where: { id: '[0-9]+' } }, (v2) => {
v2.get('/items/{id}', showItem) // GET /api/v2/items/{id}, needs the auth middleware
})
})middleware accepts a function, an alias name, a middleware group name, or an array of them. See Middleware. A where on a route overrides the group's constraint for the same parameter.
Subdomain and domain routing
Give a group a domain pattern to match on the request host. Brace segments in the domain become route parameters, available alongside the path parameters:
router.group({ domain: '{account}.myapp.com' }, (r) => {
r.get('/dashboard', (req) => ({ account: req.param('account') }))
})
// Host: acme.myapp.com GET /dashboard => { account: 'acme' }
// Any other host => 404You can also call route.domain('...') on a single route. A route with a domain only matches when the host satisfies it. When groups nest, the innermost domain wins.
Resource routes
router.resource() registers the seven conventional RESTful routes for a controller class. The parameter name is the singular of the resource name.
import { Controller, Request, Router } from '@plinthjs/http'
class PhotoController extends Controller {
index() {
return []
}
create() {
return 'form'
}
store(req: Request) {
return { created: true }
}
show(req: Request) {
return { id: req.param('photo') }
}
edit(req: Request) {
return 'edit form'
}
update(req: Request) {
return { updated: true }
}
destroy(req: Request) {
return null
}
}
router.resource('photos', PhotoController)| Verb | Path | Method | Route name |
|---|---|---|---|
| GET | /photos | index | photos.index |
| GET | /photos/create | create | photos.create |
| POST | /photos | store | photos.store |
| GET | /photos/{photo} | show | photos.show |
| GET | /photos/{photo}/edit | edit | photos.edit |
| PUT, PATCH | /photos/{photo} | update | photos.update |
| DELETE | /photos/{photo} | destroy | photos.destroy |
For an API you rarely want the two form-presenting routes, so apiResource() registers the same set without create and edit:
router.apiResource('posts', PostController)The returned registration is chainable. Everything also works as an options object in the third argument.
router.resource('photos', PhotoController).only(['index', 'show'])
router.resource('photos', PhotoController).except(['destroy'])
router.resource('photos', PhotoController).parameters('picture') // /photos/{picture}
router.resource('photos', PhotoController).names({ index: 'gallery' })
router.resource('photos', PhotoController, { only: ['index'], parameters: 'picture' })Resource routes are normal routes: you can name them, constrain them and attach middleware, and they honor the group they are declared in. To nest a resource under a parent, join the names with a dot. The parent gets a {parent} segment named after its singular, and the route names keep the dotted form:
router.resource('team.members', MemberController)
// GET /team/{team}/members team.members.index
// GET /team/{team}/members/create team.members.create
// POST /team/{team}/members team.members.store
// GET /team/{team}/members/{member} team.members.show
// GET /team/{team}/members/{member}/edit team.members.edit
// PUT /team/{team}/members/{member} team.members.update
// DELETE /team/{team}/members/{member} team.members.destroyCall .shallow() to drop the parent prefix from the member routes (show, edit, update, destroy), since a member id is already unique. The collection routes stay nested, and the shallow member routes are named after the leaf resource alone:
router.resource('team.members', MemberController).shallow()
// GET /team/{team}/members team.members.index
// GET /members/{member} members.show.parameters({ team: 'squad', members: 'm' }) renames the parameters per resource name. A group whose prefix carries a parameter (router.group({ prefix: '/posts/{post}' }, ...)) works too when you want full control of the path.
INFO
The registration is finalized lazily, the first time the router is matched, listed, asked for a URL or cached. That is why you can chain only() and friends after the call.
Singleton resources
A singleton has exactly one instance in its context (a profile, a thumbnail), so it has no index, no create or store, and no id segment. singleton() registers show, edit and update. Chain destroyable() to add destroy.
router.singleton('profile', ProfileController).destroyable()
// GET /profile, GET /profile/edit, PUT|PATCH /profile, DELETE /profile
router.apiSingleton('avatar', AvatarController) // show and update onlyFallback routes
Register a fallback to handle any request no route matched, for example to serve a single page application or a custom JSON 404:
import { Response } from '@plinthjs/http'
router.fallback(() => Response.json({ message: 'Not Found' }, 404))Route model binding
router.bind() tells the router how to turn a parameter into an object. The kernel runs the resolver after the route's middleware and just before your handler, so a middleware that rejects the request (authentication, throttling) stops it before any lookup happens. req.route() returns the resolved object instead of the raw string. A resolver that returns null or undefined produces a 404, and it may be async.
router.bind('user', async (id) => users.find(id)) // users is your own data access
router.get('/users/{user}', (req) => {
const user = req.route<User>('user') // the model, not the string
return user
})The resolver is keyed by parameter name, so every route that has a {user} segment gets the binding. The resolver also receives the request as its second argument. See ORM for models you can bind.
Controller routes
Instead of a closure, pass a [Controller, 'method'] pair, or a bare controller class for a single action controller. See Controllers.
router.get('/users/{id}', [UserController, 'show']).name('users.show')
router.post('/subscribe', SubscribeController) // calls its __invoke methodRoute caching
A router can be serialized to a plain JSON snapshot and rebuilt later, which lets a deployment skip evaluating route files. A snapshot records methods, path, name, domain, middleware names and the [controller, method] action. Closures cannot be serialized, so toCache() throws if any route uses one, or uses anonymous middleware. It tells you which route is at fault.
const snapshot = router.toCache()
writeFileSync('routes.json', JSON.stringify(snapshot))
// later, at boot
const cached = JSON.parse(readFileSync('routes.json', 'utf8'))
const rebuilt = Router.fromCache(cached, {
controller: (name) => controllers[name], // map a class name back to the class
middleware: (name) => middlewareByName[name], // optional
})Router.fromCache(snapshot, resolver) also accepts a bare controller resolver function. If you omit the middleware resolver, cached middleware is not reattached (the action still dispatches). Middleware is recorded by name: a string alias, a named function or a class. toCache() throws if a route uses anonymous middleware (an inline arrow function or an anonymous class), because it could not be reattached; register it with router.aliasMiddleware() and reference it by name, or use a named function.
WARNING
Route caching only works when every route uses a [Controller, 'method'] action or an invokable class. Named controllers must have unique class names, because the cache refers to them by name.
Listing routes
router.getRoutes() returns every registered route, including resource routes. Each route exposes methods, path, handler, getName(), getDomain(), getMiddleware() and parameterNames().
for (const route of router.getRoutes()) {
console.log(route.methods.join('|'), route.path, route.getName() ?? '')
}
// GET /users/{id} users.showScaffolded applications also ship a route:list console command that prints this as a table with method, URI, name and action. See Console.
Matching without a server
router.match(method, path, host?) resolves a request without dispatching it. It returns a matched route with its params, a method-not-allowed result with the allowed verbs, or not-found. It is handy in tests:
const result = router.match('GET', '/users/5')
if (result.type === 'matched') console.log(result.params) // { id: '5' }To exercise handlers and middleware too, build an HttpKernel and call kernel.handle(new Request({ method: 'GET', url: '/users/5' })). No socket is involved. See Testing.