-
Notifications
You must be signed in to change notification settings - Fork 1
Middleware
Within Nexi, middleware are methods that can run before or after 1) any request, 2) an individual route, or 3) a specific group of routes. Nexi uses express middleware and provides several hooks and convinces to add in any step in the request lifecycle. There are three main types of middelware that Nexi supports - pre request: these run before every request, post request: these run after every request, and "application middleware" that can be applied to a specific route or a group of routes. To learn more about how middleware functions should look, and what they have access to, check out the express docs (linked above).
Pre request middleware are applied to the beginning of every request, before the controller action or handler is run. The order that the middleware is applied is the order that it is run. To register pre-request middleware, you just need to add the file src/middleware/pre-request/index.js which will export a method that will be passed app (used to register middleware) and context:
// src/middleware/pre-request/index.js
module.exports = (app, context) => {
const setUserMiddleware = (req, res, next) => {
res.locals.user = { id: 1 }
}
app.use(setUserMiddleware)
}
Post request middleware are applied to the end of every request, and are only executed if the controller action or handler does not send a response (call next() or simply does not have a matching route). Like pre-request middleware, the order that the middleware is applied is the order that it is run. To register post-request middleware, you just need to add the file src/middleware/post-request/index.js which will export a method that will be passed app (used to register middleware) and context:
// src/middleware/pre-request/index.js
module.exports = (app, context) => {
const notFoundMiddleware = (req, res, next) => {
return res.send = "Page not found"
}
app.use(notFoundMiddleware)
}
Unlike pre and post request middleware, application middleware is not "registered" to be applied to every request. Application middleware can be applied to any route or group of routes by the Nexi Router. Each application middleware function must be defined in its own file in the directory src/middlware/app. Once defined, they can be reference by the Nexi Router. For example a middleware defined in the file src/middleware/require-login.js:
// src/middleware/require-login.js
module.exports = (req, res, next) => {
if (!res.locals.user) {
return res.redirect('/')
}
return next()
}
can be accessed by the router by its file name (camel-cased) - router.get('/secret', 'requireLogin', "secretController#reveal"). View the router docs to learn more about how to apply application middleware.