next.js: "Can't set headers after they are sent" when calling `res.redirect` from `getInitialProps`

Hi folks, really loving Next so far, just ran into one issue:

When I redirect on the server from getInitialProps, like this:

import React from 'react'

export default class extends React.Component {
  static getInitialProps ({ res }) {
    // assume we're on the server for this example, obviously this won't work on the client
    res.redirect('/')
    return {}
  }
  render () {
    return <h1>Hello</h1>
  }
}

I get a server-side error:

Error: Can't set headers after they are sent.
    at ServerResponse.setHeader (_http_outgoing.js:371:11)
    at sendHTML (/Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/next/dist/server/render.js:422:7)
    at Server._callee17$ (/Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/next/dist/server/index.js:767:73)
    at tryCatch (/Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/regenerator-runtime/runtime.js:65:40)
    at Generator.invoke [as _invoke] (/Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/regenerator-runtime/runtime.js:303:22)
    at Generator.prototype.(anonymous function) [as next] (/Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/regenerator-runtime/runtime.js:117:21)
    at step (/Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
    at /Users/booker/Code/next-minimal-oauth-authentication-demo/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13
> Building page: /

Also note that this code works (the user is redirected to /), but I see this error in the console. Weird!

Also note that I’m using express and next (the npm lib, not the cli)

Any thoughts?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 1
  • Comments: 38 (14 by maintainers)

Most upvoted comments

@bookercodes @timneutkens are you setting res.finished = true after you’ve sent the response? e.g.

if (res) {
  res.redirect(`/article/${doc.id}/${doc.slug}`)
  res.finished = true
}
return {}

I am starting to notice that this happens sporadically now, eek!

@bookercodes @iaincollins https://github.com/timneutkens/next-universal-redirect/blob/master/index.js#L6-L30 I made this a while back 👍 And haven’t had the errors you’re seeing.

Just published the latest version if you want to check it out: https://github.com/bookercodes/next-minimal-oauth-authentication-demo

Remember to yarn install and to create .env if you want to run it locally:

GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
SESSION_SECRET=123123123123123123123123123123123123123123123123
PORT=8080

It works really well aside from a few harmless but irksome errors in the terminal. I counted three (harmless) errors so far, will work through them and see if a better “structure” emerges