How to prevent a middleware for a specific route

I have a middleware, which checks to admin logged in or not. And it’s works for all /admin routes.

But I have a route for admin logins and it has a route like this: /admin/login. That’s why login page is not opening. I want to prevent that middleware on this specific route. How can I do this?

These are my routes:

app.use('/', favoriteBlogsMW, indexGetRoutes, indexPostRoutes)
app.use('/admin', adminAuthMW, adminGetRoutes, adminPostRoutes)

Here is login page route, which I want to prevent middleware for in adminGetRoutes.

//this route works like this: /admin/login
router.get('/login', (req, res) => {
    
    if(req.cookies.jwt){
        res.redirect('/admin')
    } else {
        res.render('admin/login')
    }

}) 

Answer

You could set the middleware after defining the /login route.

Create a separate file that contains all the routes and export Router from this file.

// adminRoutes.js
const express = require("express");
const router = express.Router();

// define "/login" route
router.get('/login', (req, res) => { ... });

// add the middleware
router.use(adminAuthMW);

// define the routes that need the "adminAuthMW" middleware
router.post(...)
router.get(...)
...

module.exports.adminRouter = router;

And in the main file,

Change

app.use('/admin', adminAuthMW, adminGetRoutes, adminPostRoutes)

to

app.use('/admin', adminRouter);