Sometimes, we want to exclude a route from running an Express middleware.
In this article, we’ll look at how to exclude a route from running an Express middleware.
Exclude a Route from Running an Express Middleware
To exclude a route from running an Express middleware, we can create our own function that accepts a route path and middleware function and returns a middleware function that checks the route path before running the middleware function.
For instance, we write:
const express = require('express')
const app = express()
const port = 3000
const unless = (path, middleware) => {
return (req, res, next) => {
if (path === req.path) {
return next();
} else {
return middleware(req, res, next);
}
};
};
const middleware = (req, res, next)=>{
console.log('middleware')
next()
}
app.use(unless('/exclude', middleware));
app.get('/', (req, res) => {
res.send('hello world')
});
app.get('/foo', (req, res) => {
res.send('foo')
});
app.get('/exclude', (req, res) => {
res.send('exclude')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
We create the unless
function that takes the path
route path string and the middleware
middleware function.
In the function, we return a function that checks if the request path which is stored in req.path
is the same as path
.
If it is, then we call next
and stop running the function with return
.
Otherwise we use return
and call middleware
to run the middleware function.
Now if we make a request to any route other than /exclude
, we see 'middleware'
logged.
Conclusion
To exclude a route from running an Express middleware, we can create our own function that accepts a route path and middleware function and returns a middleware function that checks the route path before running the middleware function.