Core

Middleware

Async middleware chain with error handling.

1 min readUpdated DocumentationEdit this page
On this page5

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.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY