Search code examples
javascriptnode.jsexpressmiddleware

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 ?


Solution

  • 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.