'write after end' crashes or logs errors in a Node.js server
Error [ERR_STREAM_WRITE_AFTER_END]: write after endShort 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.
Fix it fast
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); });2Match what you see, then jump to its fix
- 1
Two 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
The stack trace starts in a timer, a database callback or an event handlerAn async callback writes after the response is already finishedFix - 3
It appears under load, with streaming or long polling, and clients navigate away or time outThe client closed the connection and the code keeps writingFix
- 1
What does the error look like?
Error [ERR_STREAM_WRITE_AFTER_END]: write after endError: 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/*.js2Fix
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
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/*.js2Fix
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/slowConfirmed by raw.githubusercontent.com
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/*.js2Fix
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/streamConfirmed by raw.githubusercontent.com
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 fixBack end
ng fails with Cannot find module @angular/cli/bin/ng
Cannot find module '@angular/cli/bin/ng'
The ng command is the entry point to the Angular CLI package.
2 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack 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 fixBack end
Angular build says it cannot resolve '@angular/localize/init'
Can't resolve '@angular/localize/init' in '/usr/src/app/src'
The build imports @angular/localize, and that package is not in node_modules.
2 causes, each with a fixBack end
The command npm run build -- --prod exited with code 1 (Angular)
The command "npm run build -- --prod" exited with code 1
Exit code 1 only says the build failed; the real message is above it.
2 causes, each with a fix