Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

'write after end' crashes or logs errors in a Node.js server

ErrorError [ERR_STREAM_WRITE_AFTER_END]: write after end

Short answer

Node.js raises write after end (ERR_STREAM_WRITE_AFTER_END) when write() is called after end() on the same stream. In an HTTP server that means a response was finished and something wrote to it again: a second res.end(), a late async callback, or a write after the client closed. Make every path end the response once.

  • Applies to Node.js 22, Node.js 24
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Get the stack trace of the late write. Run with a handler that prints it, then read which file called write().

    process.on('uncaughtException', (err) => {
      console.error(err.code, err.stack);
    });
  2. 2Match what you see, then jump to its fix

    1. 1Two code paths run for one request, for example an if branch without a return, or a callback called twiceThe same request ends the response twiceFix
    2. 2The stack trace starts in a timer, a database callback or an event handlerAn async callback writes after the response is already finishedFix
    3. 3It appears under load, with streaming or long polling, and clients navigate away or time outThe client closed the connection and the code keeps writingFix

What does the error look like?

  • Error [ERR_STREAM_WRITE_AFTER_END]: write after end
  • Error: write after end

Cause 1 of 3

The same request ends the response twice

1Check

Node's errors page defines the code as a write attempted after stream.end(). Check the flag the response exposes.

grep -nE "res[.](end|send|write)" src/routes/*.js

2Fix

Return right after sending, so no later line touches res. Guard shared helpers with res.writableEnded.

app.get('/report', (req, res) => {
  if (!req.query.id) {
    return res.status(400).end('id is required');   // return stops the handler
  }
  res.end('ok');
});

function send(res, text) {
  if (!res.writableEnded) res.end(text);
}

3Verify

Hit the route with and without the id: one response each, no error.

curl -i "http://localhost:3000/report"

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 2 of 3

An async callback writes after the response is already finished

1Check

res.end() must be called once the body is complete. A handler that ends the response on a timeout, and a callback that writes later, collide.

grep -nE "setTimeout|setImmediate" src/routes/*.js

2Fix

Await the work before writing, and make the timeout path and the success path mutually exclusive.

app.get('/slow', async (req, res) => {
  const data = await loadData();
  if (res.writableEnded) return;
  res.end(JSON.stringify(data));
});

3Verify

Trigger the slow path under a timeout and confirm there is only one end().

curl -i --max-time 2 http://localhost:3000/slow

Confirmed by raw.githubusercontent.com

Did this fix it?

Cause 3 of 3

The client closed the connection and the code keeps writing

1Check

Node.js emits 'close' on the response when the connection is terminated prematurely. A loop that keeps writing after that point writes to a dead stream.

grep -nE "setInterval|[.]pipe[(]" src/routes/*.js

2Fix

Stop work when the response closes, and clear timers there.

const timer = setInterval(() => {
  if (!res.writableEnded) res.write('tick\n');
}, 1000);
res.on('close', () => clearInterval(timer));

3Verify

Open the stream with curl, press Ctrl+C, and confirm the server logs no error.

curl -N http://localhost:3000/stream

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Use return before every res.end() or res.send() in a branch.
  • Register res.on('close') cleanup for every timer, interval or pipe in a handler.
  • Add an error handler on streams you create. The Node.js docs say no further events except 'close' follow an 'error'.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.