Home > Back-end >  Express.js router - How to process same path with different middlewares?
Express.js router - How to process same path with different middlewares?

Time:12-20

I have two routes to register users, actually they aren't two routes since they have the same path but they have different middlewares. Since they have the same path, one of them will have precedence over other and other route will not work. Here are the routes:

// Register a new user as an admin
router.post('/', [auth, authAdmin], async function(req, res, next) { ... });
// Sign in route
router.post('/', async function(req, res, next) { ... });

How can I solve this conflict between these two routes?

CodePudding user response:

You cannot achieve this with identical paths - as you've described the first will take precedence over the other.

You should define specific endpoints for both use cases, e.g.:

// Register a new user as an admin
router.post('/register', [auth, authAdmin], async function(req, res, next) { ... });
// Sign in route
router.post('/sign-in', async function(req, res, next) { ... });
  • Related