Skip to content

Middlewares

Middleware is a method that is called after a request has been received by the server and before a response is sent to that request. Essentially, every request handler (or Router) is a middleware itself.

Writing your own middleware

Here is example of middleware:

import { RequestHandler } from '@shelepuginivan/lunatic'
const myMiddleware: RequestHandler = (req, _res, next) => {
console.log(`Handled ${req.method} request at ${Date.now()}`)
next() // call next middleware
}
app.use(myMiddleware)

You can specify request method and path that certain middleware should handle (see Routing):

import { RequestHandler } from '@shelepuginivan/lunatic'
const blockTrace: RequestHandler = (_req, res) => {
res.status(405).json({ message: 'TRACE is not allowed' })
}
app.trace(blockTrace) // blocks all TRACE requests

Built-in middleware functions

Lunatic comes with several common middlewares bundled: