Search code examples
javascriptnode.jsexpressmiddleware

Access a route, send an error alert, and redirect


I'm using nodejs, expressjs, javascript...

I have this "middleware" function to use when someone tries to access one route that doesn't have access when it is not logged in, but I can't send an alert, and redirect, as well as a response, how can I do it?

function isLoggedIn (req, res, next) 
{

    if (req.isAuthenticated()) {
        return next();
    }

    res.send('<script>alert("You need to be authenticated to access this page")</script>'); 
    res.redirect('/');

}

Solution

  • I dont recommend doing that (sending html in server side response) Instead: Send a json with a variable that will tell you in the client side to make an alert:

    res.json({ success: false });
    

    Ans then in the client side you can alert a message if !success and redirect.