after.js: Redirecting from getInitialProps with res.redirect() causes error
When using res.redirect() in getInitialProps(), I get the following error:
(node:73586) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: Can't set headers after they are sent.
The code is simply:
static async getInitialProps({ req, res, match, history, location, ...ctx }) {
res.redirect('/');
}
The redirect does occur, but am I missing something due to the error?
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 16 (2 by maintainers)
You can also check if
res.finishedand if so return early. That’s how I ended up handling it. Sorry I didn’t put code above maybe would have saved you some timeBut anyway I’ve moved on from Afterjs because of basic things like this and decided to make my own solution 😃 will be releasing soon
The way to redirect in render by the way is:
Check the react-router docs if you need to know more.
🎉
Just got this to work without throwing an error.
problem 😫
As you noted, @alidcastano, the default behaviour of the
.getroute is to always returnres.send(html). As noted elsewhere, if you callres.sendorres.redirectmultiple times in a row, then express is unhappy.So, if we write
(ignoring that we have an infinite loop) then we get
Error: Can't set headers after they are sent.Instead, we have to explicitly return the response when we are done with it
So that’s what we want.
When we’re in the
getInitialPropsfor a component, we aren’t able to return theresto end the request. Writingreturn res.redirect('/')ingetInitialPropswill just take us to component’s constructor earlier. We’re still queuing up ares.redirectfollowed by ares.sendonce we’re back in the server. This is why we get theError: we’re doing the same thing as in scenario 1.solution 💡
We can do the redirect here if we figure out a way to pass a value back.
So I was clicking around the express docs when I found
res.locals. This is pretty much exactly what we want.So now we can do an error-free server-side redirect:
Hope that helps you out! (Might also be useful for your other issue, #146 as well)
getInitialProps must be able to run on both client and server. You could check for res and all res.redirect but if it’s undefined call window.location.replace