Stream HTML to speed up first byte
Send the page head right away and stream the slow body later with res.write in Node.js, so the browser can start loading CSS before the data is ready.
If a page waits for a slow query before sending anything, the browser sits idle. Sending the <head> first lets it fetch stylesheets and scripts while the server keeps working.
import http from 'node:http';
import { setTimeout as sleep } from 'node:timers/promises';
http.createServer(async (req, res) => {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.write('<!doctype html><html><head><title>Report</title><link rel="stylesheet" href="/app.css"></head><body><h1>Report</h1>');
await sleep(1000); // stands in for a slow database query
res.write('<ul><li>Row 1</li><li>Row 2</li></ul>');
res.end('</body></html>');
}).listen(3000);t=0 ms headers and <head> arrive, browser requests /app.css
t=1000 ms list arrives, page completesThe timings follow from the code, not from a measurement. Without a content-length, Node.js uses chunked transfer encoding, so each write is flushed to the client as it is made.
Errors are harder: once the status line is sent you cannot change it to a 500, so handle failures inside the stream. Some proxies buffer responses and hide the effect, so check yours. Frameworks such as React and Next.js stream for you; see [response.write](https://nodejs.org/api/http.html#responsewritechunk-encoding-callback).