How to properly redirect in NodeJS/ExpressJS?

When you send an ajax call with either XMLHttpRequest or fetch() and get the response, the browser does not do anything to the current page in the browser based on that response. So, it doesn’t matter whether you send a redirect response to the ajax call or not. The browser won’t change the current page in the browser, no matter what. Ajax responses generate data for your Javascript and your Javascript must then decide what to do with it.

FYI, the browser will change the current page only when the redirect happens from a browser page request or a browser submitted form post (not Javascript submitted). Since that is not how you are logging in, you can’t use a redirect to change the current browser page.

So, if you’re going to use an ajax call on the client for login and you want the client to change pages after a successful Ajax login, then you probably want to send the redirect URL in the login response and have the client process it and set window.location to do the redirect on login.

For example, you could change:

res.send("Success");

to this:

res.json({status: "Success", redirect: "https://stackoverflow.com/"});

And, then have your client code examine the return from the ajax call and if the status is successful, it can grab the redirect property and do something like:

if (ajaxResult.status === "Success") {
    window.location = ajaxResult.redirect;
}

I am curious to why this redirect here would not work? The headers are
not being set anywhere else in this function and the expected result
should be that the redirect would work perfectly fine. Any help is
greatly appreciated.

The message about headers have already been sent means that the whole response has already been sent with res.send("Success"); and you are now trying to send another response. You only get one response for a given request. Once you’ve done res.send("Success");, the http server object has sent the whole response and then closed off that response. You can’t send more data at that point.

Leave a Comment