Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns
Node.js http.ServerResponse class
Reference for http.ServerResponse: statusCode, headers, write(), end(), headersSent, writableEnded, streaming replies, and common mistakes like double-ending.
http.ServerResponse is the res object a server hands to your request listener. You use it to set the status code and headers and to write the body. It is a Writable stream, so you can pipe() a file or any readable into it.
A response has three phases. First you can change the status and headers freely. The first write() or end() (or an explicit writeHead()) sends the headers and locks them. Finally end() finishes the message. Every request must be answered with exactly one end().
import http from "node:http"; http.createServer((req, res) => { res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.write("part one, "); res.end("part two"); });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
class http.ServerResponse extends http.OutgoingMessage
| Member | Description |
|---|---|
res.statusCode |
Status code sent with the headers. Default 200. |
res.statusMessage |
Reason phrase; defaults to the standard text for the code. |
res.setHeader(name, value), getHeader(), getHeaders(), hasHeader(), removeHeader(), appendHeader() |
Manage headers before they are sent. |
res.writeHead(status, [message], [headers]) |
Sets status and headers and queues them for sending. |
res.write(chunk, [encoding], [callback]) |
Sends part of the body; returns false when you should wait for drain. |
res.end([data], [encoding], [callback]) |
Optionally writes a last chunk and finishes the response. |
res.flushHeaders() |
Sends the headers right now. |
res.writeContinue(), res.writeEarlyHints() |
Send 100 Continue or 103 Early Hints. |
res.addTrailers(headers) |
Headers sent after a chunked body. |
res.headersSent |
true once the headers went out. |
res.writableEnded |
true after end() was called. |
res.writableFinished |
true after all data was flushed to the system. |
res.setTimeout(ms, callback?) |
Socket timeout for this response. |
Errors and edge cases:
- Changing headers after they were sent throws
ERR_HTTP_HEADERS_SENT. - An invalid status code outside 100-999 throws
ERR_HTTP_INVALID_STATUS_CODE; a header name that is not a valid token throwsERR_INVALID_HTTP_TOKEN, and a header value with a line break throwsERR_INVALID_CHAR. - Calling
end(data)orwrite()after the response ended produces anERR_STREAM_WRITE_AFTER_ENDerror on the response.end()without data a second time is harmless. - With status
204,304and responses toHEAD, no body is sent even if you pass one.
Usage notes
- Without a
Content-Lengthheader, Node sends a body inTransfer-Encoding: chunkedform when you usewrite()orpipeline. A singleend(data)after no writes lets Node computeContent-Length. - Honor backpressure for large bodies: check the result of
write()and wait fordrain, or usepipeline(), which does this for you. - Always set
Content-Typeand include a charset for text; browsers otherwise guess. - Send errors as complete responses (
res.statusCode = 500; res.end(...)) only ifres.headersSentisfalse; otherwise destroy the socket, since the status can no longer change. - User-supplied text in a header value must never contain line breaks. Node rejects them, which prevents header injection, but validate input anyway.
res.on("close")fires when the underlying connection closes, which is useful for cleaning up when a client leaves a long-lived response early.res.writeHead()andres.setHeader()can be combined:writeHead()headers win on conflict.