Peter Moses
Peter Moses

Reputation: 2137

How to pass middleware to specified routes in express node.js

I have a middleware (gateMan) that checks if user is logged in, i don't want the middleware (gateMan) to fire on all routes. However, it would be fired on 98% of my routes, how can i achieve this without calling the middleware on each of the route.

Middleware

const gateMan = (req,res,next)=>{
    if(req.user)
        next();
    else{
        res.redirect('/auth/login');
        res.end();
    }
};

Route sample

app.use('/',staticRoute);
app.use('/auth',authRoute);
app.use('/user',gateMan,userRoute);
app.use('/mocks',gateMan,mockRoute);
app.use('/sample2',sample2Route);
app.use('/sample3',sample3Route);
app.use('/sample4',sample4Route);

I want to apply gateMan to all routes except staticRoute and authRoute. I'm thinking if there is a way i can just pass all routes into and array and apply the middleware to them, how possible is this ?

Upvotes: 1

Views: 3985

Answers (2)

Tarabass
Tarabass

Reputation: 3150

You can use app.all('*') and check inside what path is used. From there you can use the logic what's now in the middleware. It is a pretty dynamic solution and you don't have to tell which routes are there.

Something like this (not tested though):

app.all('*', function(req, res, next) {
    if (req.path !== '/' || req.path !== '/auth') {
        if(req.user)
            next()
        else {
            res.redirect('/auth/login')
            res.end()
        }
    }
})

You could then put all unauthorized paths in an array and check in app.all if the path is in that array.

Something like:

var unauthorizedPaths = [ '/', '/auth']

app.all('*', function(req, res, next) {
    if(unauthorizedPaths.indexOf(req.path) === -1) {
        if(req.user)
            next()
        else {
            res.redirect('/auth/login')
            res.end()
        }
    }
})

https://expressjs.com/en/4x/api.html#req.path

https://expressjs.com/en/4x/api.html#app.all

Upvotes: 1

Arbaz Siddiqui
Arbaz Siddiqui

Reputation: 481

You can use express's app.usein your app file. As app.use relies on order, you can define your staticRoute and authRoute first, then your middlewares and then your other routes.

app.use('/',staticRoute);
app.use('/auth',authRoute);
app.use(gateMan)
app.use('/user',userRoute);
app.use('/mocks',mockRoute);
app.use('/sample2',sample2Route);
app.use('/sample3',sample3Route);
app.use('/sample4',sample4Route);

Every route you define after your gateman middleware will use that middleware.

Upvotes: 5

Related Questions