Middleware
LiteNode supports middleware both globally (applied to every request) and per-route (applied to specific routes). Middleware functions receive req and res and run before the final route handler.
Global Middleware — use()
Signature:
use(middleware: RouteHandler): LiteNode
Registers a middleware that runs on every incoming request.
// Request logger
app.use(async (req, res) => {
console.log(`[${req.method}] ${req.url}`)
})
Multiple use() calls are executed in registration order:
app.use(logger)
app.use(authenticate)
app.use(attachRequestId)
Per-Route Middleware
Pass middleware functions as arguments between the route path and the handler:
const addTimestamp = async (req, res) => {
req.timestamp = new Date()
}
app.get("/time", addTimestamp, (req, res) => {
res.txt(`Request at: ${req.timestamp}`)
})
Multiple middleware functions can be chained on the same route:
app.get("/admin/dashboard", authenticate, requireAdmin, (req, res) => {
res.render("admin/dashboard.html", { user: req.user })
})
next()
Middleware functions automatically advance to the next handler when they return. There is no explicit next() call required — just return from the function:
const authenticate = async (req, res) => {
const token = req.headers["authorization"]
if (!token) {
// Ending the response here stops the chain
return res.status(401).json({ error: "Unauthorized" })
}
// Returning without ending the response passes control forward
req.user = await verifyToken(token)
}
app.get("/profile", authenticate, (req, res) => {
res.json({ user: req.user })
})
Middleware with merge() and nest()
Middleware can be scoped to merged or nested routers. See Merge and Nest for full details.
app.merge(apiRouter, rateLimiter)
app.nest("/admin", adminRouter, authenticate)
See the Examples page for auth, logging, and rate-limiting patterns.