Search code examples
node.jsexpressexpress-jwt

How to redirect to unauthenticated user using express-jwt


This is my first express app. I am trying to implement authentication for some of the routes. Ideally, if users are not authenticated, they will be redirected to the home page. So I wrote this middleware:

var jwt = require('express-jwt');

app.get('/protected',
  jwt({secret: 'shhhhhhared-secret'}),      //express-jwt middleware
  function(req, res, next) {                //redirection middleware
    if(!req.user._id){
      console.log('authentication failed')
      res.redirect('/home')
    }else{
      next()
    };
  });

If the user is logged in, the code works. However, if user is not logged in, the browser simply show a 401 unauthorized error. There is no redirection. The process failed at the express-jwt middleware and did not continue to my redirection middleware.

Is there some configuration which i need to set within the jwt function? Or do is there a way to set a global redirection if 401 is encountered.


Solution

  • If user is not authenticated error is thrown and node.js stops code execution. After that you would be able to catch it in express error handler:

      app.use(function(err, req, res, next) {
        if(401 == err.status) {
            res.redirect('/home')
        }
      });