Nitish Phanse
Nitish Phanse

Reputation: 562

Selectively apply middleware in express

I have a route /users as a parent suffix in my router, all subsequent routes will append the the parent eg. /users/details

In my app.js

app.use('/api/v1/users', userRoutes);

In my userRoutes

import express from 'express';
import users from '../controllers/user_controller';

import { authenticateRoute, authenticateSignedRoute, aclAuthenticator } from './../middlewares/AuthenticationMiddleware';

const router = express.Router();


//user routes
router.get('/details', authenticateRoute, aclAuthenticator, users.getDetails);
router.get('/posts', authenticateRoute, aclAuthenticator, users.getPosts);


module.exports = router;

WHAT I WOULD LIKE TO DO

Is there a way for me to add the authenticateRoute and the aclAuthenticator middleware to the parent prefixed route, and then for one particular route have an exception where only a third middleware is applied and not the first two.

For eg app.use('/api/v1/users', authenticateRoute, aclAuthenticator, userRoutes);

My new router file

router.get('/details', applyOnlyThisMiddleWare, users.getDetails);
router.get('/posts', No MiddleWareAtAll, users.getPosts);

I'm basically trying to overide the initial middleware, is this possible?

Upvotes: 2

Views: 3220

Answers (2)

Dhruv Kumar Jha
Dhruv Kumar Jha

Reputation: 6567

This is how i explicitly disable middleware for specific routes

'use strict';

const ExpressMiddleware = ( req, res, next ) => {

    // dont run the middleware if the url is present in this array
    const ignored_routes = [
        '/posts',
        '/random-url',
    ];

    // here i am checking for request method as well, you can choose to remove this
    // if( ! ignored_routes.includes(req.path) ) {
    if( req.method === 'GET' && ! ignored_routes.includes(req.path) ) {
        // do what you gotta do.
        // next();
    }
    else {
        next();
    }

}


export default ExpressMiddleware;

And in your server/routes file

app.use( ExpressMiddleware );

Ofcourse you might have to change the code, if you're using dynamic routes.. but that shouldn't be difficult.

Upvotes: 5

jfriend00
jfriend00

Reputation: 708106

The only way I know of to do that is to apply the first two middlewares directly to your router with no path prefix:

router.use(middleware1, middleware2);

Then, in each of those middlewares, check the path of the URL and if it is the special path that you want to skip those middlewares for, then just call next().

if (req.path.indexOf("/somepath") === 0) { return next() };

Then, you can register your third middleware only for the path you are interested in:

router.use("/somepath", middleware3);

The first two middewares will skip the ones you want them to skip and the third one will only get called for your specific route.

Upvotes: 1

Related Questions