Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally use a middleware depending on request parameter express

I am trying to decide on a middleware to use based on request query parameter.

in the main module I have something like this:

app.use(function(req, res){   if (req.query.something) {     // pass req, res to middleware_a   } else {     // pass req, res to middleware_b   } }); 

middleware_a and middleware_b are both express apps themselves created by express() function and not regular middleware functions (function(req, res, next))

can't find a way to do it

like image 862
Michael Avatar asked Jan 21 '14 23:01

Michael


People also ask

What objects does middleware have access to through its parameters?

Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle.

How many middleware can be on a single route?

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

How do I skip the middleware in Express?

To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

Does Express support middleware?

Middleware functions are an integral part of an application built with the Express framework (henceforth referred to as Express application). They access the HTTP request and response objects and can either terminate the HTTP request or forward it for further processing to another middleware function.


2 Answers

There is nothing magical about connect/express 'middleware': they are just functions - and you can call them as you would call any other function.

So in your example:

app.use(function(req, res, next){   if (req.query.something) {     middlewareA(req, res, next);   } else {     middlewareB(req, res, next);   } }); 

That said, there might be more elegant ways of constructing hierarchical express applications. Check out TJ's video

like image 192
pirxpilot Avatar answered Sep 22 '22 20:09

pirxpilot


I know this issue is old, but I would like to share my solution. I solved this by making a function that returned a Middleware with a callback.

Example middleware:

function isAdminUser(callback){     return function(req, res, next){         var userId = callback(req);         // do something with the userID         next();     } } 

Then you can do the following in the express router object

app.use(isAdminUser(function(req){     return req.body.userId     }); 
like image 44
Christian Avatar answered Sep 22 '22 20:09

Christian