Middleware
Middleware
Section titled “Middleware”Middleware runs around your handlers. This guide covers where it can be attached, when each piece runs, and the two built-ins you will configure in almost every application: the rate limiter and the body-size limit.
Global middleware
Section titled “Global middleware”// Every requestapp.use(async (c, next) => { const started = Date.now(); await next(); c.header('X-Response-Time', `${Date.now() - started}ms`);});
// Only under a path (v3.7.0)app.use('/admin/*', auditMiddleware);Return a response without calling next() to short-circuit the request.
Phases
Section titled “Phases”New in v3.7.0.
app.use() attaches the middleware immediately. Plugins attach theirs later, during compile() — so a plain app.use() runs before the authentication middleware and never sees the user.
Pass phase: 'afterPlugins' to attach a middleware behind everything the plugins install:
app.use(async (c, next) => { const user = c.get('auth.user'); // available here if (user) c.header('X-User', String(user.sub)); await next();}, { phase: 'afterPlugins' });
app.use('/api/*', tenantMiddleware, { phase: 'afterPlugins' });| Phase | Attached | Sees |
|---|---|---|
early (default) | When app.use() is called | The raw request |
afterPlugins | During compile(), after every plugin is installed | auth.user, the session, and anything else a plugin put in the context |
Within a phase, middleware runs in registration order. Calling app.use(…, { phase: 'afterPlugins' }) after compile() attaches the middleware right away.
Order of execution
Section titled “Order of execution”For an HTTP request, from outside in:
- Body-size limit (the handling route’s own limit when it declares one, the application-wide one otherwise)
- CORS
app.use()—early- Plugin middleware — authentication, RBAC context, session, …
app.use(…, { phase: 'afterPlugins' })- Route guards —
@Auth,@Roles,@Permissions,@MinimumRole - Controller middleware —
@Controller(prefix, { middleware }) - Route middleware —
@UseMiddleware,@RateLimit,@Timeout - The handler
Two consequences worth remembering:
- Guards run after
afterPluginsmiddleware. That phase is the place to prepare what a guard needs — see Multi-tenancy. - WebSocket upgrade requests pass through steps 1–5 as well (since v3.7.0).
Route and controller middleware
Section titled “Route and controller middleware”import { Controller, Get, UseMiddleware } from 'veloce-ts';
@Controller('/reports', { middleware: [requireFeatureFlag('reports')] })class ReportsController { @Get('/export') @UseMiddleware(slowQueryLogger) export() {}}Each middleware runs exactly once per request, whatever the order of the decorators on the method.
Rate limiting
Section titled “Rate limiting”app.useRateLimit({ windowMs: 60_000, max: 300,});Who is being limited
Section titled “Who is being limited”New in v3.7.0.
keyBy chooses what identifies a caller:
keyBy | Key | Notes |
|---|---|---|
ip (default) | Client address | Runs in the early phase, so it also shields the authentication layer |
user | Authenticated user (sub) | Anonymous requests are not limited by this limiter |
user-or-ip | The user when authenticated, the address otherwise | The usual choice for an API with both kinds of traffic |
app.useRateLimit({ windowMs: 60_000, max: 300, keyBy: 'user-or-ip' });With user or user-or-ip the limiter is attached in the afterPlugins phase automatically, since it needs the authenticated user. A custom keyGenerator still takes precedence; set phase yourself if it reads something a plugin provides.
The real client address
Section titled “The real client address”Behind a reverse proxy the socket peer is the proxy, and X-Forwarded-For is a list the client can prepend to. Tell the limiter how many proxies you run:
app.useRateLimit({ windowMs: 60_000, max: 100, trustedProxyHops: 1 });trustedProxyHops | Address used |
|---|---|
0 (default) | The socket peer. X-Forwarded-For is ignored |
N | The Nth entry of X-Forwarded-For counted from the right — the one written by your outermost proxy |
Counting from the right matters: each proxy appends the address it received the request from, so the rightmost entries are the trustworthy ones and the leftmost is whatever the client typed.
The same logic is available on its own:
import { clientIp } from 'veloce-ts';
const address = clientIp(c, { trustedProxyHops: 1 }); // string | undefinedtrustProxy was removed in v4.0.0 — it read the leftmost entry, which the client writes. Passing it throws a TypeError.
Exemptions and stores
Section titled “Exemptions and stores”import { RedisRateLimitStore } from 'veloce-ts';
app.useRateLimit({ windowMs: 60_000, max: 300, keyBy: 'user-or-ip', skip: (c) => c.req.path.startsWith('/health') || c.req.path === '/webhooks/stripe', store: new RedisRateLimitStore(redis),});skipexempts requests — health checks, webhooks that carry their own authentication.- The default store is in-memory and per-process: with N instances the effective limit is N ×
max. Pass a shared store when you scale out. The limiter warns about this once whenNODE_ENV=production.
Per route
Section titled “Per route”@RateLimit takes the same options and, being route middleware, already runs after authentication:
@Post('/login')@RateLimit({ windowMs: 15 * 60 * 1000, max: 5 })login() {}
@Post('/exports')@RateLimit({ windowMs: 60_000, max: 2, keyBy: 'user' })createExport() {}Every limited response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; a rejected one is a 429 with Retry-After.
Request body limit
Section titled “Request body limit”Bodies above 1 MiB are rejected with 413 before any handler reads them. Change it application-wide:
const app = new Veloce({ bodyLimit: 5 * 1024 * 1024 }); // 0 disables the limitOr per route, in either direction (v3.7.0):
import { Put, Post, BodyLimit } from 'veloce-ts';
@Put('/upload')@BodyLimit(25 * 1024 * 1024) // this route accepts 25 MiBupload() {}
@Post('/comment')@BodyLimit(4 * 1024) // this one, 4 KiBcomment() {}
app.post('/import', { handler, bodyLimit: 5 * 1024 * 1024 });A per-route limit lets one upload endpoint accept large bodies without raising — or disabling — the limit for the rest of the API.
There is a single body-size check, first in the pipeline. It already knows which route will handle the request, so it applies that route’s limit when the route declares one and the application-wide limit otherwise — a larger per-route limit is not blocked by a smaller global one.
Other built-ins
Section titled “Other built-ins”app.useCors({ origin: ['https://app.example.com'], credentials: true });app.useCompression();See Request Context for request ids, timeouts and cancellation, and Caching for the response cache.
Related
Section titled “Related”- Access Control
- Multi-tenancy
- Plugins — the
beforeCompilehook, for middleware a plugin needs to add