Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use specific middleware in Express for all paths except a specific one

I am using the Express framework in node.js with some middleware functions:

var app = express.createServer(options); app.use(User.checkUser); 

I can use the .use function with an additional parameter to use this middleware only on specific paths:

app.use('/userdata', User.checkUser); 

Is it possible to use the path variable so that the middleware is used for all paths except a specific one, i.e. the root path?

I am thinking about something like this:

app.use('!/', User.checkUser); 

So User.checkUser is always called except for the root path.

like image 992
Thomas Avatar asked Oct 16 '12 19:10

Thomas


People also ask

How do I exclude a route from 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.

How many middlewares you can use?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app. METHOD() .

How many parameters you should pass in the middleware function?

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function.

How does middleware work in Express?

Middleware literally means anything you put in the middle of one layer of the software and another. Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the HTTP request and response for each route (or path) it's attached to.


1 Answers

I would add checkUser middleware to all my paths, except homepage.

app.get('/', routes.index); app.get('/account', checkUser, routes.account); 

or

app.all('*', checkUser);      function checkUser(req, res, next) {   if ( req.path == '/') return next();    //authenticate user   next(); } 

You could extend this to search for the req.path in an array of non-authenticated paths:

function checkUser(req, res, next) {   const nonSecurePaths = ['/', '/about', '/contact'];   if (nonSecurePaths.includes(req.path)) return next();    //authenticate user   next(); } 
like image 94
chovy Avatar answered Oct 21 '22 22:10

chovy