Built-in middlewares
Helpers in this package. Import what you need. Stacking every export is not a security story and will hurt benchmarks (logger() especially).
import {
app,
logger,
cors,
helmet,
rateLimit,
jwtAuth,
session,
cache,
validate,
requestId,
circuitBreaker,
etag,
compress,
} from "velociradix";IMPORTANT
Global middlewares must be registered before route definitions. Middlewares execute in the exact order they are attached using app.use().
CAUTION
Sensitive encryption secrets for jwtAuth and session must always be read from environment variables (process.env.JWT_SECRET), never hardcoded directly in application source code.
Reference
1. logger(options?)
Logs incoming requests with HTTP method, URL path, status code, and response time.
logger: Custom logger function(msg) => void(default:console.log)includeRes: Log response status and duration (default:false)
app.use(logger({ includeRes: true }));2. helmet(options?)
Injects modern HTTP security headers: X-Content-Type-Options, X-Frame-Options, Referrer-Policy, HSTS, Content-Security-Policy, Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy, Permissions-Policy. X-XSS-Protection is set to 0 (the XSS auditor is harmful in legacy browsers).
frameOptions: Frame options header value (default:'SAMEORIGIN')referrerPolicy: Referrer policy (default:'no-referrer')contentSecurityPolicy: CSP string, orfalseto disable (default: restrictivedefault-src 'self')crossOriginResourcePolicy: default'same-origin'— set'cross-origin'for public APIs consumed from other originshsts/hstsMaxAge/hstsPreload
app.use(helmet());
app.use(
helmet({
contentSecurityPolicy: false,
crossOriginResourcePolicy: "cross-origin",
}),
);3. cors(options?)
Configures Cross-Origin Resource Sharing and handles OPTIONS preflight requests automatically.
origin: Allowed origin string, array,true(reflect request Origin), or function (default:'*')methods: Allowed HTTP methods (default:'GET,POST,PUT,DELETE,PATCH,OPTIONS')headers: Allowed request header namescredentials: Support cookies & authorization headers (true|false). Never sent together withAccess-Control-Allow-Origin: *.
app.use(cors({ origin: "https://example.com", credentials: true }));4. rateLimit(options?)
Sliding-window IP rate limiter to protect against spam and denial-of-service.
windowMs: Time window in milliseconds (default:60000)max: Maximum requests allowed per IP in the window (default:100)message: Custom error payload on limit exceededmaxKeys: Cap on unique tracked IPs to prevent memory exhaustion (default:10000)
app.use(rateLimit({ windowMs: 60 * 1000, max: 100 }));5. rateLimitByKey(keyFn, options?)
Rate limit requests partitioned by custom keys (e.g. User ID, API Key, Tenant).
app.use(rateLimitByKey((ctx) => ctx.get("X-API-Key") || ctx.ip, { max: 50 }));6. slowDown(options?)
Progressive request delay limiter that gradually slows down abusive clients instead of immediately blocking them.
delayAfter: Request count threshold before adding delay (default:5)delayMs: Delay in ms added per request (default:500)windowMs: Time window (default:60000)
app.use(slowDown({ delayAfter: 10, delayMs: 200 }));7. jwtAuth(options)
HMAC JWT verification (HS256 default; HS384/HS512 optional). Constant-time signature compare, blocks alg: none, checks exp/nbf, and attaches the payload to ctx.state.user.
secret: HMAC secret (required).algorithms: Allowed algs (default:['HS256']).issuer/audience: Optional claim checks.
app.use("/admin/*", jwtAuth({ secret: process.env.JWT_SECRET }));8. bearerAuth(options)
Static or custom-verified bearer token guard.
token: Expected static token string.verify: Custom callback(token, ctx) => boolean.
app.use(bearerAuth({ token: "secret-token-12345" }));9. basicAuth(options)
HTTP Basic Authentication guard.
users: Object map of valid username-password credentials{ admin: 'password' }.realm: Custom authentication realm string.
app.use(basicAuth({ users: { admin: "supersecret" } }));10. apiKey(options)
Validates API keys from the request header only (query string is off by default so keys do not leak via logs/Referer).
keys: Array of valid keys.headerName: Header name to read (default:'x-api-key').allowQuery: Settrueonly if you accept the risk of query-string keys.
app.use(apiKey({ keys: ["secret-key-1", "secret-key-2"] }));11. cache(options?)
In-memory response cache with TTL and LRU eviction. Do not use on authenticated routes unless you pass vary. By default, requests with Authorization or Cookie are not cached (so user A cannot receive user B's GET).
ttlMs: Cache duration in milliseconds (default:10000)maxSize: Maximum entries in cache store (default:1000)vary: Header names to include in the cache key.undefined(default) skipsAuthorization/Cookierequests.[]is URL-only (public GETs only).
app.use("/public-api/*", cache({ ttlMs: 30000 }));
app.use("/me", cache({ ttlMs: 5000, vary: ["authorization"] }));12. session(options)
AES-256-GCM encrypted, cookie-backed user session store. Cookies are always HttpOnly, default SameSite=Lax, maxAge 86400, and Secure when NODE_ENV=production.
secret: Encryption secret key.name: Session cookie name (default:'_session').
app.use(session({ secret: "secure-session-key-32-chars!!" }));13. csrf(options?)
Double-submit CSRF cookie (httpOnly: false, SameSite=Strict) with constant-time header compare and Origin match after default-port normalization. The token is also sent as X-CSRF-Token. Query-string tokens are ignored.
headerName: Header carrying the token (default:'x-csrf-token').
app.use(csrf());14. validate(schema)
Schema validation middleware for incoming request bodies, params, and query strings.
app.post(
"/register",
validate({
email: { type: "email", required: true },
password: { type: "string", required: true, min: 8 },
}),
(ctx) => {
return ctx.json({ success: true });
},
);15. sanitize()
Sanitizes incoming URL query parameters and body values against XSS injection attacks.
app.use(sanitize());16. bodyCleaner(options?)
Cleans incoming JSON payloads by stripping unexpected or blacklisted fields.
app.use(bodyCleaner({ stripHtml: true, trimStrings: true }));17. compress(options?)
Gzip & Deflate response body compression handler for payloads exceeding threshold size.
threshold: Minimum byte size to compress (default:1024bytes).
app.use(compress({ threshold: 1024 }));18. etag(options?)
Automatic ETag header generator (Weak & Strong ETag support) for HTTP caching and 304 Not Modified responses.
app.use(etag());19. conditionalRequest()
Handles If-None-Match and If-Modified-Since conditional headers and sends 304 Not Modified when content is unchanged.
app.use(conditionalRequest());20. requestId(options?)
Generates or forwards unique request correlation IDs (X-Request-ID) for distributed tracing.
headerName: Custom header name (default:'X-Request-ID').
app.use(requestId());21. responseTime()
Injects high-resolution X-Response-Time header (X-Response-Time: 1.23ms) to all outgoing responses.
app.use(responseTime());22. ipFilter(options)
Allows or blocks incoming requests based on IP address lists.
allow: Array of whitelisted IP addresses.block: Array of blacklisted IP addresses.
app.use(ipFilter({ block: ["192.168.1.100"] }));23. hostGuard(allowedHosts)
Rejects requests with unexpected Host header values to prevent DNS rebinding and host-header attacks.
app.use(hostGuard(["api.example.com", "localhost:3000"]));24. userAgentBlocker(options)
Blocks known bots, scrapers, or empty User-Agent strings.
app.use(
userAgentBlocker({ blockEmpty: true, blockedPatterns: [/curl/i, /wget/i] }),
);25. allowedMethods(methods)
Enforces allowed HTTP methods for endpoints and returns 405 Method Not Allowed for unsupported verbs.
app.use(allowedMethods(["GET", "POST", "OPTIONS"]));26. methodOverride(options?)
Allows clients to override HTTP methods using X-HTTP-Method-Override header or _method query parameter.
app.use(methodOverride());27. sizeLimit(maxBytes | options)
Rejects payloads over the limit with 413. Checks both Content-Length and the actual parsed body (the C++ engine also enforces setPayloadLimit).
app.use(sizeLimit(1024 * 1024 * 5)); // 5MB
app.use(sizeLimit({ maxSize: 1024 * 1024 }));28. timeout(ms)
Aborts requests taking longer than the specified timeout duration with 504 Gateway Timeout.
app.use(timeout(10000)); // 10s29. concurrencyLimit(maxConcurrent)
Limits the number of concurrent requests executing simultaneously to prevent resource exhaustion.
app.use(concurrencyLimit(500));30. circuitBreaker(options?)
Circuit breaker pattern that automatically trips open and fails fast when downstream errors spike.
failureThreshold: Failure count threshold before opening circuit.resetTimeoutMs: Timeout before testing recovery.
app.use(circuitBreaker({ failureThreshold: 10, resetTimeoutMs: 15000 }));31. csp(directives)
Generates customizable Content-Security-Policy security headers.
app.use(
csp({
"default-src": ["'self'"],
"script-src": ["'self'", "https://cdn.example.com"],
}),
);32. headerInjector(headers)
Injects static headers across all outgoing responses.
app.use(headerInjector({ "X-Powered-By": "Velociradix-Engine" }));33. redirector(redirectsMap)
Redirects legacy paths or URL patterns to new destinations.
app.use(redirector({ "/old-page": "/new-page" }));34. auditLog(options?)
Creates structured JSON audit logs for security, compliance, and auditing.
app.use(auditLog({ logFn: (entry) => console.log(JSON.stringify(entry)) }));35. favicon(path?)
Serves the favicon.ico icon directly and caches it in memory.
app.use(favicon("./public/favicon.ico"));36. maintenance(options?)
Puts the entire application or specific routes into maintenance mode with 503 Service Unavailable.
enabled: Boolean flag.message: Custom maintenance message or HTML.
app.use(
maintenance({
enabled: false,
message: "Under scheduled maintenance. Back soon!",
}),
);