Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js ERR_STREAM_WRITE_AFTER_END: write after end

Write after end means something ended the stream first. Find the double end, guard with writableEnded and let pipeline own the lifecycle.

~5 min readNode.js
#nodejs#streams#express#errors
Bold white headline reading WRITE AFTER END with a Node stream crate sealed by an amber closed valve and a cyan chunk waiting behind it.

Introduction & Quick Summary

Node writes to a stream after that stream has already been ended, and the process prints this:

code
Error [ERR_STREAM_WRITE_AFTER_END]: write after end at write_ (node:internal/streams/writable:698:11) at Writable.write (node:internal/streams/writable:723:25) at /app/src/server.js:42:9 code: 'ERR_STREAM_WRITE_AFTER_END'

Quick answer: find the second end() or the late write(), and guard it with the stream's own state.

js
if (!res.writableEnded) { res.write("late chunk"); res.end(); }

ERR_STREAM_WRITE_AFTER_END is a state error, not a data error. The stream is still an object, the file descriptor may still be open, and the write is refused because writableEnded === true. That means the interesting question is never "how do I write anyway" but "which code path ended this stream earlier". Answering that removes the error instead of hiding it.

Common triggers: res.end() called in both a success handler and an error handler, res.send() after res.json(), a try/catch that ends the response and then falls through, an await inside a stream callback that finishes after the consumer closed, and a helper that calls end() internally while the caller also calls it.

Core Mechanics, Signatures & Reproducible Setup

A Writable moves through four states:

StateMeaningwrite() allowed
openaccepts datayes
writableEndedend() was calledno, throws ERR_STREAM_WRITE_AFTER_END
writableFinishedall buffered data flushedno
writableDestroyeddestroyed or erroredno, ERR_STREAM_DESTROYED

Reproduce without a server:

js
const { Writable } = require("node:stream"); const out = new Writable({ write(chunk, _enc, cb) { cb(); } }); out.write("first\n"); out.end(); console.log(out.writableEnded, out.writableFinished); // true true (sync sink) out.write("second\n"); // Error [ERR_STREAM_WRITE_AFTER_END]

The same sequence over HTTP, which is where it usually appears:

js
app.get("/report", async (req, res) => { try { const rows = await buildReport(); res.write("id,total\n"); res.end(rows.map((r) => `${r.id},${r.total}`).join("\n")); } catch (err) { logger.error(err); res.end("error"); // second end() when the try block already ended } });

end() is idempotent in the sense that the second call does not throw by itself; what throws is a write() after the first end(). Express and the Node HTTP layer sometimes add their own writes, which is why the stack in production rarely points at your line.

Key Comparison Table

The three ways to close a stream, and what each one does to pending data:

CallFlushes buffered dataEmits finishLater write() result
stream.end(data?)yesyesERR_STREAM_WRITE_AFTER_END
stream.destroy()nonoERR_STREAM_DESTROYED
stream.destroy(err)nono, emits errorERR_STREAM_DESTROYED

The message you get tells you which layer refused:

MessageCauseFix
write after endwrite() after end()guard with writableEnded
Cannot call write after a stream was destroyedwrite on a closed socketcheck destroyed, stop the producer
write EPIPEclient closed the connectionignore or abort the job for that client
ERR_STREAM_WRITE_AFTER_END inside pipelinea stage ended earlylet pipeline own the lifecycle
ERR_HTTP_HEADERS_SENTsame double-response bug in res.set()return after the first response

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Double response in Express

js
app.post("/hook", async (req, res) => { if (!req.body?.id) { res.status(400).json({ error: "id required" }); return; // without this line the handler continues } const row = await save(req.body); res.json(row); });

The missing return is the most frequent cause in web apps. Once res.json() has run, any later res.send, res.write or res.end fails. res.headersSent is true at that point and can be used as a defensive check:

js
function safeJson(res, status, body) { if (res.headersSent || res.writableEnded) return; res.status(status).json(body); }

2. Streaming responses: end exactly once

js
app.get("/export", async (req, res) => { res.setHeader("Content-Type", "text/csv"); const cursor = db.collection("orders").stream(); try { for await (const order of cursor) { if (res.writableEnded) break; // client left mid-stream if (!res.write(toCsvLine(order))) { await new Promise((r) => res.once("drain", r)); // backpressure } } } finally { await cursor.close(); if (!res.writableEnded) res.end(); } });

Two details matter here. write() returns false when the internal buffer exceeds highWaterMark; waiting for drain keeps memory flat on large exports. And the finally block ends the response only if nobody else did — that single check removes the whole class of late-end errors on this route.

3. Pipe versus manual writes

source.pipe(res) calls res.end() when the source ends. Adding your own res.end() afterwards is the second end:

js
// bad fs.createReadStream(file).pipe(res); res.end(); // correct: pipe owns it, and pipeline propagates errors await pipeline(fs.createReadStream(file), res);

stream.pipeline is the safer primitive because it destroys every stage when one fails, so a late write cannot happen after an aborted file read.

4. Async callbacks that outlive the request

js
app.get("/slow", (req, res) => { setTimeout(() => { res.write("done"); // request may already have timed out res.end(); }, 30000); });

A proxy with a 15-second timeout closes the socket, the server ends the response, and the timer fires later. Listen for the close event and clear the work:

js
let timer = setTimeout(() => { /* ... */ }, 30000); req.on("close", () => clearTimeout(timer));

The same shape appears in message handlers that acknowledge after res.end(), in Server-Sent Events that write after the client disconnects, and in jobs that stream to a log file that a rotation has already closed.

5. File streams: finish is the signal, not end()

js
const out = fs.createWriteStream("report.log", { flags: "a" }); out.on("error", (err) => logger.error(err)); out.on("finish", () => logger.info("flushed to disk")); out.write("line\n"); out.end(() => logger.info("end callback fired"));

end() schedules the flush; the finish event fires after the last byte reached the sink, and the file descriptor closes afterwards, which is when close fires. Writing to the stream from a close handler throws write-after-end. On Windows, appending from two processes to the same file can also produce late errors when the second process opens the file after the first ended it.

6. Error handling that prevents rather than catches

An 'error' listener is mandatory: an unhandled stream error crashes the process. But the listener does not prevent write-after-end — it only reports it. Prevention comes from making the lifecycle single-owner:

  • one function decides when a response ends, and it examines writableEnded first;
  • producers check destroyed before every write inside a loop;
  • every try/catch around a response path returns immediately after writing the error.

Streamed payloads are easier to inspect if each chunk is valid JSON — the JSON formatter checks one line at a time, and binary frames can be decoded with the Base64 encoder before comparing headers. For an HTTP endpoint under test, the cURL builder reproduces the exact request that triggers the double response, including the timeout that closes the socket early.

Common Compilation/Runtime Mistakes & Version Gotchas

Wrapping the write in try/catch and retrying. The stream will not reopen. Create a new one, or fix the caller that ended it.

Assuming res.end() twice is harmless. The method itself tolerates a repeat call, but any framework code that writes afterwards — Express's finaliser, a compression middleware, an access log that appends to the body — will throw.

Using stream.write() after pipeline() returns. pipeline ends the destination when the source finishes. Anything held by reference is now closed.

Ignoring backpressure. Writing 100,000 rows without checking the boolean return value does not cause write-after-end, but it does cause MaxListenersExceededWarning and out-of-memory crashes on the same code path, which are often reported as the same incident.

Version notes. Node 14 introduced writableEnded and writableFinished (replacing the older finished property), so guards written before that read undefined and never short-circuit. Node 16 changed stream.pipeline to prefer promises and to destroy the destination on error. Node 18 added stream.Readable.from improvements and res.writableNeedDrain. Node 20 dropped the automatic error re-emission for some pipe cases, which turned silent failures into explicit exceptions. If a guard uses res.finished, replace it: the property still exists on the HTTP response for compatibility, but the stream's own writableEnded is the value that matches the error you are seeing.

Reference material: Stream and Node.js errors.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.