Middleware pipeline
Understand how LykosJS executes middleware functions, controls request flow and composes the request processing pipeline.
What is a middleware pipeline?
The MiddlewarePipeline is responsible for executing registered middleware functions in sequence before reaching the final route handler.
Each middleware can inspect the request context, perform operations, execute additional logic before or after the next middleware, and return a response.
Understand the middleware signature
A middleware receives three arguments: the request context, the response helper and the next function.
1import type { ContextMiddleware } from 'lykosjs'2 3const myMiddleware: ContextMiddleware = async (4 ctx,5 reply,6 next,7) => {8 // Before the next middleware9 10 const response = await next()11 12 // After the next middleware13 14 return response15}- ctx — The current request context shared throughout the middleware pipeline.
- reply — The response helper available to middleware functions.
- next — Advances execution to the next middleware or the final route handler.
Register middleware
The MiddlewarePipeline class provides ause() method to register middleware functions. Each call appends the middleware to the pipeline and returns the same pipeline instance, allowing method chaining.
1import { MiddlewarePipeline } from 'lykosjs'2 3const pipeline = new MiddlewarePipeline()4 5pipeline6 .use(firstMiddleware)7 .use(secondMiddleware)8 .use(thirdMiddleware)Middleware functions execute in the same order in which they were registered.
Execution order
When the pipeline executes, the first registered middleware runs first. Calling await next() transfers execution to the next middleware. This continues until all middleware functions have completed and the final handler is reached.
1const firstMiddleware: ContextMiddleware = async (ctx, reply, next) => {2 console.log('First: before')3 4 const response = await next()5 6 console.log('First: after')7 8 return response9}10 11const secondMiddleware: ContextMiddleware = async (ctx, reply, next) => {12 console.log('Second: before')13 14 const response = await next()15 16 console.log('Second: after')17 18 return response19}20 21pipeline22 .use(firstMiddleware)23 .use(secondMiddleware)For a successful request, the execution order is:
1First: before2Second: before3Route handler4Second: after5First: afterThis execution model is commonly called the middleware onion pattern: execution moves forward through the pipeline and then unwinds in reverse order.
Continue execution with next()
The next() function advances execution to the next registered middleware. When no middleware remains, it invokes the final handler.
1const timingMiddleware: ContextMiddleware = async (ctx, reply, next) => {2 const started = performance.now()3 4 const response = await next()5 6 const duration = performance.now() - started7 8 console.log(`Request completed in ${duration.toFixed(2)}ms`)9 10 return response11}Awaiting next() is important when you need to access the downstream response or perform operations after the route handler finishes.
Stop the pipeline
A middleware can return a response without callingnext(). This stops execution of the remaining middleware functions and prevents the final handler from running.
1const maintenanceMiddleware: ContextMiddleware = async (ctx, reply, next) => {2 const maintenanceMode = true3 4 if (maintenanceMode) {5 return reply.ServiceUnavailable({6 message: 'Service is temporarily unavailable.',7 })8 }9 10 return next()11}Prevent multiple next() calls
LykosJS prevents a middleware from advancing the same execution chain more than once. If next()is called again after the pipeline has already advanced to that position, it throws an Error.
1// Incorrect: calling next() twice2const invalidMiddleware: ContextMiddleware = async (ctx, reply, next) => {3 await next()4 5 return next()6}7 8// Correct: call next() once9const validMiddleware: ContextMiddleware = async (ctx, reply, next) => {10 const response = await next()11 12 return response13}Handle errors in middleware
Middleware functions can use standard JavaScripttry/catch blocks to handle errors from downstream execution. If an error is not handled, it propagates to the caller of the pipeline.
1const errorLoggingMiddleware: ContextMiddleware = async (ctx, reply, next) => {2 try {3 return await next()4 } catch (error) {5 console.error('Request pipeline failed:', error)6 throw error7 }8}Rethrowing the error allows the framework's surrounding request handling layer to process it through its error handling mechanism.
Pipeline without middleware
When no middleware has been registered, the pipeline uses a fast path and executes the final handler directly. No middleware dispatch functions are created in this case.
1const pipeline = new MiddlewarePipeline()2 3const response = await pipeline.execute(4 ctx,5 reply,6 finalHandler,7)Common mistakes
1// Incorrect: not awaiting next() when downstream work is required2const incorrectMiddleware: ContextMiddleware = async (ctx, reply, next) => {3 next()4 return Response.json({ message: 'Done' })5}6 7// Correct: await next() and return its response8const correctMiddleware: ContextMiddleware = async (ctx, reply, next) => {9 const response = await next()10 return response11}12 13// Incorrect: continuing without returning a Response14const missingResponse: ContextMiddleware = async (ctx, reply, next) => {15 await next()16}17 18// Correct: return the downstream response19const returnedResponse: ContextMiddleware = async (ctx, reply, next) => {20 return await next()21}