Middleware
Async middleware chain with error handling.
1 min readEdit this page
Basic middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.path}`)
next()
}
app.use(logger)Route-specific
app.get('/admin', authCheck, requireAdmin, handler)Error handling
app.use((error, req, res, next) => {
res.status(error.statusCode || 500).json({
error: { code: error.code, message: error.message }
})
})Built-in middleware
import { helmet, rateLimit, sanitize } from '@restjs/security'
app.use(helmet())
app.use(cors({ origin: '*' }))
app.use(rateLimit({ max: 100 }))
app.use(sanitize())Warning
If middleware does not call next() and does not send a response, the request hangs.