Skip to content
jshacks.dev
Performance

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.

1 min read
Summarize in AI

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.

server.jsJavaScript
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);
Text
t=0 ms     headers and <head> arrive, browser requests /app.css
t=1000 ms  list arrives, page completes

The 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).

Also inAsync
Taggednode 24
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.