Middleware
Middleware in Pikku follows an onion model - each middleware wraps around the next, running before and after your function executes. This is the same pattern used by Koa and Hono.
Think of it like layers wrapping a core: the request passes through each outer layer to reach the function at the center, then unwinds back out through the same layers to send the response.
Your First Middlewareβ
Let's write middleware that tracks response time:
import { pikkuMiddleware } from '#pikku/pikku-types.gen.js'
export const responseTime = pikkuMiddleware(async ({ logger }, interaction, next) => {
const start = Date.now()
// Call next middleware/function
await next()
// After function completes
const duration = Date.now() - start
logger.info(`Request completed in ${duration}ms`)
// For HTTP, you can set headers
if (interaction.http) {
interaction.http.response.setHeader('X-Response-Time', `${duration}ms`)
}
})
The middleware:
- Destructures
loggerfrom services (tree-shaking benefit) - Has access to the
interactionobject (http, channel, queue, etc.) - Calls
next()to continue the chain - Can run code before and after the function