next.js: Error: Can't set headers after they are sent. in version 5 and higher for next/express app

Expected Behavior

No error on terminal.

Current Behavior

Getting error on terminal for next 5.0.0, 5.0.1-canary.8 but not 4.3.0-canary.1:

{ Error: Can't set headers after they are sent.
    at SendStream.headersAlreadySent (/home/tima/apps/builderbook/book/4-end/node_modules/send/index.js:390:13)
    at SendStream.send (/home/tima/apps/builderbook/book/4-end/node_modules/send/index.js:618:10)
    at onstat (/home/tima/apps/builderbook/book/4-end/node_modules/send/index.js:730:10)
    at FSReqWrap.oncomplete (fs.js:153:5) expose: false, statusCode: 500, status: 500 }

I’ve read this issue https://github.com/zeit/next.js/issues/2152 However I don’t redirect inside getInitialProps.

My app has express/next server. Link

Steps to Reproduce (for bugs)

  1. Start app with different versions of next 5.0.0, 5.0.1-canary.8, 4.3.0-canary.1
  2. When app uses 5.0.0, 5.0.1-canary.8 versions of next (but not 4.3.0-canary.1) then you see above error object in terminal

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 15
  • Comments: 29 (11 by maintainers)

Most upvoted comments

I just saw this issue on my side and determined it was being caused by the compression plugin. I think it’s interfering with the hot module reloading. I worked around it like so:

const app = express();
if (process.env.NODE_ENV === "production") {
  app.use(compression());
}

I’m unfortunately getting this using now dev without a custom backend.

I can confirm that the error only happens when Chrome Dev tools is open. At the contraries of what most people report, we don’t use compression, still, we can experience the error with next@6.0.2.

Mine crashes without compression O_o

I’ve noticed this in multiple projects, as well.

FWIW this is only happening to me when I have Chrome Inspector open. If it’s closed, no problem. If it’s open, I get this error on every page load.

Same problem here after update to next 5 and it cause by compression.

Same problem, not using compression plugin at all. Looks like it has something to do with session? I’m also using session.

For those still facing this error (even with Next.js 8), make sure that you don’t res multiple requests, that was my problem:

if (req.url && ROOT_STATIC_FILES.includes(req.url)) {
  const path = join('static', 'root', req.url);
  app.serveStatic(req, res, path);

  return; // <- THIS is important
}

nextHandler(req, res);

FYI, A similar problem was also confirmed in Next.js + Koa.js. This Error message is displayed when koa-session or koa-session-minimal is enabled.

next@6.0.2 koa@2.5.1 koa-session@5.8.2 koa-session-minimal@3.0.4

I want a solution too.

Adding compression as the very last line, just before server.listen() get’s rid of the message for me. Next 5.1.0, compression 1.7.2 and express 4.15.2. Hope it helps.