Middleware
Extend request processing with reusable middleware, registered globally or on individual routes and route groups.
Middleware overview
Middleware functions run during request processing and can inspect the request context, perform operations, modify the response flow, or stop execution before reaching the route handler.
Middleware signature
1import type { ContextMiddleware } from 'lykosjs'2 3const timingMiddleware: ContextMiddleware = async (ctx, reply, next) => {4 const started = performance.now()5 const response = await next()6 7 console.log(8 ctx.method,9 ctx.path,10 performance.now() - started,11 )12 13 return response14}Register middleware
1// Global middleware2app.use(loggerMiddleware)3 4// Route-level middleware5app.GET('/private', handler, auth.middleware)6 7// Group-level middleware8app.group('/api/admin', configureAdminRoutes, auth.middleware)Global middleware is registered before route-specific middleware. Middleware executes in registration order, and callingnext() continues the pipeline.
Middleware pipeline
LykosJS uses a middleware pipeline to execute middleware functions sequentially. Each middleware can pass execution to the next one, perform operations after it completes, or return a response early to stop further execution.
Learn more about execution order and request flow in the Middleware Pipeline documentation.
Built-in middleware
corsMiddleware(options) — Configure cross-origin access and preflight handling.
loggerMiddleware — Log incoming requests and execution details.
AuthMiddleware — Authenticate requests using cookies or Bearer tokens.