2

I have a simple app which has a login page and a section for authenticated users from where unauthenticated users are being redirected back to login. At the end of all my routes, I have app.all('*', ...) which returns 404 error page.

When I am authenticated, everything works fine, but if I log out and try to fetch unexisting route, I am redirected to the login page instead of getting 404 response.

I understand that this is because I added middleware which handles redirection but I would expect it to work only on routes specified in that one exact router - not in all routes (even the app-level ones) which are placed right after middleware.

The only solution I see at the moment is to use this authCheck middleware in every restricted route instead of registering it globally using router.use but I am still wondering if there is a better way?

const express = require('express')

module.exports = (app) => {
  const authRouter = express.Router()

  // ================================
  // ========= Public Routes ========
  // ================================
  app.get('/login', () => { /* ... login route */ })
  app.post('/login', () => { /* ... login route */ })

  // ====================================
  // ========= Restricted Routes ========
  // ====================================
  authRouter.use((req, res, next) => {
    req.isAuthenticated()
      ? next()
      : res.redirect('/login')
  })

  authRouter.get('/', () => { /* restricted route */ })

  // register restricted routes
  app.use(authRouter)

  // ========================================
  // ============ Other routes ==============
  // ========================================

  // error 404 route <--- this works only for authenticated users
  app.get('*', (req, res) => {

    res.status(404)
    res.render('error404')
  })
}

Thanks for any ideas..

4
  • Without changing any code, you could change the flow of execution to get it to work properly.
    – thomann061
    Mar 7, 2018 at 15:07
  • I tried to move app.get('*') to the top but it started returning error 404 on all routes.. How would you change the order?
    – Jan Jůna
    Mar 7, 2018 at 15:23
  • Honestly, I wouldn't recommend changing the order, as it would be confusing. There is most likely a better way.
    – thomann061
    Mar 7, 2018 at 15:25
  • 1
    @JanJůna Your code should not depend on the order of middleware, better go for the generic solution. Mar 7, 2018 at 15:28

3 Answers 3

0

try this, you can create an array of all URLs without auth and check inside middleware.

const authMiddleware = (req, res, next) => {
    /* Urls Without Auth */
    const withoutAuth = ['/login'];
    if (withoutAuth.includes(req.url) || req.isAuthenticated()) {
        next();
    } else {
        res.redirect('/login');
    }
};

app.use(authMiddleware);
0
const express = require('express')
// Note: FWIW I think it's better to organize your middleware
// into separate files and store them into separate directory
// So you could use it like that:
// const verifyAuthMiddleware = require('./middleware/verifyAuthMiddleware);
const verifyAuthMiddleware = (req, res, next) => {
    req.isAuthenticated()
      ? next()
      : res.redirect('/login')
  };

module.exports = (app) => {    
  // ================================
  // ========= Public Routes ========
  // ================================
  app.get('/login', () => { /* ... login route */ })
  app.post('/login', () => { /* ... login route */ })

  // ====================================
  // ========= Restricted Routes ========
  // ====================================    
  // You can add the middleware like that
  app.get('/', [verifyAuthMiddleware], () => { /* restricted route */ });

  // Or you can add a middleware to a group of routes like that
  app.use('/user', [verifyAuthMiddleware]);
  // And then every route that starts with "/user" uses the middleware
  app.get('/user/settings', () => {});
  app.get('/user/wallet', () => {});
  app.get('/user', () => {});
  app.post('/user/wallet', () => {});
  // etc


  // ========================================
  // ============ Other routes ==============
  // ========================================

  // error 404 route <--- this works only for authenticated users
  app.get('*', (req, res) => {

    res.status(404)
    res.render('error404')
  })
}
0

thank you for your replies. In the end, I did it like this:

function authCheck (req, res, next) {
    return req.isAuthenticated()
        ? next()
        : res.redirect('/login')
}

// Product routes
const prodRouter = express.Router()
prodRouter.get('/', products.getlist)
prodRouter.get('/:uuid/:tab?', products.getbyId)
prodRouter.post('/:uuid/:tab?', products.update)

// Register product routes
app.use('/products', [authCheck, prodRouter])

// For all other routes return 404 error page
app.get('*', (req, res) => {
    res.status(404).render('error404')
})

With this approach, the authCheck middleware is being used only on /product routes so when I access /missing-page I get correctly the Error 404 page.

1
  • You might want to use app.use('*', ... rather than app.get('*', ....
    – Rvy Pandey
    Sep 6, 2019 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.