HTTP

response.writeHead()

Commits the status and headers for an HTTP response. Call before sending body data and only once. If headers were stored earlier using setHeader, explicit header values supplied here take precedence. Tested on Node.js 22.16.0. Example output (one line per entry): ["201 ready created"].

Formal Syntax & Structure

nodejs syntaxnodejs
response.writeHead(statusCode[, statusMessage][, headers])

Parameters & Attributes

NameTypeDescription
statusCodenumberResponse status.
statusMessagestringOptional reason phrase.
headersobject | ArrayHeaders to send.

Return Value

http.ServerResponse

The response instance.

Working Example

Example Snippetnodejs
import http from 'node:http';const server = http.createServer((req, res) => { res.setHeader('X-Mode', 'draft'); res.writeHead(201, { 'X-Mode': 'ready' }); res.end('created'); });await new Promise(r => server.listen(0, '127.0.0.1', r));const url = 'http://127.0.0.1:' + server.address().port;try {    const r = await fetch(url);    console.log(r.status, r.headers.get('x-mode'), await r.text());}finally {    server.closeAllConnections();    await new Promise(r => server.close(r));}
Node.js Reference