Middleware
Introduction
Middleware sits between the incoming request and your route handler. Each layer can inspect or change the request, call the next layer, then inspect or change the response on the way back out. You use middleware for cross-cutting work such as authentication, session handling, response headers, CORS and rate limiting.
A middleware is a plain async function. It receives the Request and a next function, and returns a Response.
Defining middleware
import type { Middleware } from '@plinthjs/http'
export const timing: Middleware = async (req, next) => {
const started = Date.now()
const res = await next(req) // pass control inward
return res.header('X-Response-Time', `${Date.now() - started}ms`)
}Calling next(req) continues down the stack and resolves with the response. Return a Response without calling next to short-circuit everything inward:
import { Response } from '@plinthjs/http'
import type { Middleware } from '@plinthjs/http'
export const requireApiKey: Middleware = async (req, next) => {
if (req.header('x-api-key') !== process.env.API_KEY) {
return Response.json({ message: 'Unauthorized' }, 401)
}
return next(req)
}Requests are immutable. To pass something forward, call next with a modified copy:
export const forceJson: Middleware = (req, next) =>
next(req.withHeader('accept', 'application/json'))
export const tagRequest: Middleware = (req, next) =>
next(req.withAttribute('startedAt', Date.now())) // read later with req.attribute('startedAt')A scaffolded application keeps its middleware in src/middleware/, and the generated make:middleware command creates a file there that exports a factory returning a Middleware:
export function authenticate(): Middleware {
return async (request, next) => {
// ... before
const response = await next(request)
// ... after
return response
}
}Errors thrown in a handler or in route middleware are rendered into a response by the exception handler before they travel back out through your middleware. That means an outer middleware always receives a real Response from next(), even for failed requests, so it can still add headers or save a session.
Global middleware
Global middleware wraps every request, including those that match no route. Pass it to the kernel, outermost first:
import { cors, HttpKernel, Router, securityHeaders } from '@plinthjs/http'
const router = new Router()
const kernel = new HttpKernel(router, {
middleware: [securityHeaders({ hsts: true }), timing],
})The scaffolded web app registers its global stack in src/server.ts: security headers, then the session, then CSRF verification, then a middleware that attaches the signed in user.
Route middleware
Attach middleware to a single route with middleware(). It takes any number of entries:
router.get('/dashboard', showDashboard).middleware(authenticate(), timing)Route middleware runs after global middleware and after the route has been matched.
Group middleware
Apply middleware to every route in a group:
router.group({ prefix: '/admin', middleware: [authenticate(), requireAdmin] }, (r) => {
r.get('/users', listUsers)
r.get('/reports', listReports)
})Group middleware runs before middleware attached to the individual routes inside it.
Aliases and middleware groups
Register a name once and refer to it by string anywhere a middleware is accepted. Names are resolved when a matched route's stack is assembled.
router.aliasMiddleware('auth', authenticate())
router.aliasMiddleware('admin', requireAdmin)
router.middlewareGroup('web', [timing, 'auth']) // a group may contain names too
router.get('/account', showAccount).middleware('web')
router.group({ prefix: '/admin', middleware: ['web', 'admin'] }, (r) => {
r.get('/', adminHome)
})Using a name that has no alias or group throws when a request reaches the route, which renders as a 500, so typos surface in tests quickly.
Middleware parameters
Because middleware are just functions, parameters are arguments to a factory. Write a function that returns a middleware, and call it where you attach it:
import { Response } from '@plinthjs/http'
import type { Middleware } from '@plinthjs/http'
export function role(name: string): Middleware {
return async (req, next) => {
if (req.header('x-role') !== name) return Response.json({ message: 'Forbidden' }, 403)
return next(req)
}
}
router.get('/admin', adminHome).middleware(role('admin'))
router.aliasMiddleware('editor', role('editor')) // or give a configured instance an aliasTerminable middleware
Some work should happen after the response has been produced, such as saving state or logging. Pass an object with handle and terminate instead of a function. The kernel calls terminate(req, res) once the response exists. Terminators run for global middleware first, then the matched route's middleware, and an error in one does not stop the others.
import type { TerminableMiddleware } from '@plinthjs/http'
export const audit: TerminableMiddleware = {
async handle(req, next) {
return next(req)
},
async terminate(req, res) {
console.log(req.method(), req.path(), res.status) // GET /dashboard 200
},
}
router.get('/dashboard', showDashboard).middleware(audit)Built-in middleware
@plinthjs/http ships three ready-made middleware factories that most production apps need.
Security headers
securityHeaders() adds baseline security headers to responses. It never overwrites a header already set, so a route can opt out per response.
import { securityHeaders } from '@plinthjs/http'
securityHeaders() // X-Content-Type-Options, X-Frame-Options, Referrer-Policy
securityHeaders({
hsts: true, // Strict-Transport-Security, only sent when the request is HTTPS
frameOptions: 'DENY', // 'DENY' | 'SAMEORIGIN' (default) | false to omit
noSniff: true, // default true
referrerPolicy: 'no-referrer', // default 'strict-origin-when-cross-origin', or false
})
securityHeaders({ hsts: { maxAge: 63_072_000 } }) // custom max-age in secondsHSTS is gated on req.isSecure(), which follows X-Forwarded-Proto when the direct peer is a trusted proxy, so it works behind a TLS-terminating proxy and stays off for plain local HTTP.
CORS
cors() answers preflight OPTIONS requests with a 204 and stamps the CORS headers on real responses.
import { cors } from '@plinthjs/http'
cors() // allow any origin
cors({
origin: ['https://app.example.com'], // string, list, or (origin) => boolean
methods: ['GET', 'POST'], // default GET, HEAD, PUT, PATCH, POST, DELETE
allowedHeaders: ['Content-Type', 'Authorization'], // default: echo the request's headers
exposedHeaders: ['X-Total-Count'],
credentials: true, // Access-Control-Allow-Credentials
maxAge: 600, // preflight cache in seconds, default 86400
})When the origin is not '*', the response also carries Vary: Origin. An origin that is not allowed simply gets no CORS headers. Register cors() as global middleware so preflight requests are answered even for paths that have no OPTIONS route.
Throttling
throttle() limits how often a client may hit a route. Over the limit it responds 429 with a Retry-After header. It needs a limiter with hit, tooManyAttempts and availableIn, which the RateLimiter from @plinthjs/rate-limiter provides. See Rate limiting.
import { throttle } from '@plinthjs/http'
import { RateLimiter } from '@plinthjs/rate-limiter'
const limiter = new RateLimiter()
router.post('/login', login).middleware(throttle({ limiter, max: 5, decaySeconds: 60 }))
// the 6th request in a minute => 429, Retry-After: 60By default the key is the client IP plus method and path, so each route is limited separately per client. Pass key to scope it differently, for example by the submitted email:
throttle({ limiter, max: 5, key: (req) => String(req.input('email')) })Defaults are max: 60 and decaySeconds: 60.
Testing middleware
Call the kernel with synthetic requests. No server is needed:
import { HttpKernel, Request, Router } from '@plinthjs/http'
const router = new Router()
router.get('/a', () => 'a').middleware(timing)
const res = await new HttpKernel(router).handle(new Request({ url: '/a' }))
res.headers['X-Response-Time'] // => '0ms'