Skip to content

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.

// Every request
app.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.

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' });
PhaseAttachedSees
early (default)When app.use() is calledThe raw request
afterPluginsDuring compile(), after every plugin is installedauth.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.

For an HTTP request, from outside in:

  1. Body-size limit (the handling route’s own limit when it declares one, the application-wide one otherwise)
  2. CORS
  3. app.use() — early
  4. Plugin middleware — authentication, RBAC context, session, …
  5. app.use(…, { phase: 'afterPlugins' })
  6. Route guards — @Auth, @Roles, @Permissions, @MinimumRole
  7. Controller middleware — @Controller(prefix, { middleware })
  8. Route middleware — @UseMiddleware, @RateLimit, @Timeout
  9. The handler

Two consequences worth remembering:

  • Guards run after afterPlugins middleware. 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).
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.

app.useRateLimit({
windowMs: 60_000,
max: 300,
});

New in v3.7.0.

keyBy chooses what identifies a caller:

keyByKeyNotes
ip (default)Client addressRuns in the early phase, so it also shields the authentication layer
userAuthenticated user (sub)Anonymous requests are not limited by this limiter
user-or-ipThe user when authenticated, the address otherwiseThe 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.

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 });
trustedProxyHopsAddress used
0 (default)The socket peer. X-Forwarded-For is ignored
NThe 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 | undefined

trustProxy was removed in v4.0.0 — it read the leftmost entry, which the client writes. Passing it throws a TypeError.

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),
});
  • skip exempts 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 when NODE_ENV=production.

@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.

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 limit

Or 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 MiB
upload() {}
@Post('/comment')
@BodyLimit(4 * 1024) // this one, 4 KiB
comment() {}
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.

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.