Next.js blank page after res.redirect()

By

Fix the blank page you get after calling res.redirect() in a Next.js API route on Vercel by switching to res.writeHead() with a 302 Location header instead.

~~~

If a Next.js API route redirects to a blank page after a form submit, the fix is to send an explicit 302 redirect with res.writeHead() instead of calling res.redirect() with just a path.

Here’s the full story. I had an API route and after responding to a form submit, the API called

res.redirect('/')

It worked great locally in development, but when I shipped it to Vercel, the redirect ended up to a blank page. The URL was correct, but it took a refresh to show the content.

I fixed this by using res.writeHead() instead:

res.writeHead(302, { Location: '/' }).end()

The 302 Found HTTP code is a common way of performing URL redirection.

Why does this happen?

When you call res.redirect() in a Next.js API route without a status code, Next.js uses 307 Temporary Redirect as the default.

The difference between 307 and 302 matters a lot here.

A 307 redirect tells the browser to repeat the request to the new URL with the same HTTP method. My form submitted with POST, so the browser followed the redirect by sending a POST request to the homepage. The homepage is a regular page, not something that answers a POST, so I got a blank page.

A 302 redirect is different in practice. When browsers follow a 302 after a POST, they switch the method to GET. That’s exactly what we want after a form submit: the browser loads the destination page normally.

This is the classic POST/redirect/GET pattern. Submit the form, redirect, land on a fresh page loaded with GET.

The shorter fix

You can also keep res.redirect() and pass the status code explicitly:

res.redirect(302, '/')

This does the same thing as the writeHead() version. Both send a 302 with a Location: / header.

One thing to watch out for

Make sure the response actually ends after the redirect. If your handler keeps running and later calls res.json() or res.send(), you’ll get a “headers already sent” error in the logs.

Put a return in front of the redirect call when there’s more code below it:

return res.redirect(302, '/')

That closes the response and stops the handler right there.

Tagged: Next.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about next: