'res.redirect() does not end request and causes error: "Cannot set headers after they are sent to the client "

My route that handles get requests for the login page checks to see if the user is already logged in. If they are, redirect them to /userprofile, if not, render the login.ejs view.

From what I was reading, res.redirect() should end the http request, but in this example I've been getting some weird behavior. When the user is logged in, I get the error "Cannot set headers after they are sent to the client" multiple times. Here's the code:

app.get("/login", (req, res) => {
    if (req.session.user) { res.redirect('/userprofile') };
    res.render('login');
})

But I realized that if

  • I just include a return before res.redirect() or
  • negate the if statement and invert the order of the responses

the code works fine.

Could anyone explain why? Thanks



Solution 1:[1]

It is caused by you redirecting the user, to /userprofile before rendering login. A way you could avoid this would be to do the redirect frontend, in your fetch.

fetch('login', {
 method: 'POST',
})
.then(() => {
window.location.href = '/userprofile'
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sejrskild