Core
Middleware
Async middleware chain with error handling.
Basic middleware
TypeScript
TS
1const logger = (req, res, next) => {
2 console.log(`${req.method} ${req.path}`)
3 next()
4}
5
6app.use(logger)Route-specific
TypeScript
TS
app.get('/admin', authCheck, requireAdmin, handler)Error handling
TypeScript
TS
1app.use((error, req, res, next) => {
2 res.status(error.statusCode || 500).json({
3 error: { code: error.code, message: error.message }
4 })
5})Built-in middleware
TypeScript
TS
1import { cors } from '@axiljs/core'
2import { helmet, rateLimit, sanitize } from '@axiljs/security'
3
4app.use(helmet())
5app.use(cors({ origin: '*' }))
6app.use(rateLimit({ max: 100 }))
7app.use(sanitize())Warning
If middleware does not call next() and does not send a response, the request hangs.
Related
- Static Files: serve a folder with
serveStatic() - Error Handling: 4-argument error middleware and HTTP error classes
- SSE Streaming
- Security middleware
Was this page helpful?