Streaming HTML
Send the top of the page before the bottom of it exists, and know which metric that actually moves.
In this chapter: chunked responses on the wire · out-of-order streaming · TTFB against FCP against LCP · what silently disables streaming · the headers you can no longer set
💡 The Core Idea
An HTTP response does not have to be assembled before it is sent. The server can write the first bytes, keep the connection open, and write more as it goes. Browsers have parsed HTML in pieces since the 1990s. They render what has arrived and keep going.
Streaming uses that old ability on purpose. The server does not wait for the slowest query on the page. It flushes the shell (<head>, layout, navigation) at once. Then it flushes each region as its data resolves.
The user sees the page in the order the server can produce it, not in the order of the slowest thing on it. Nothing about the page got faster. The waiting was rearranged so that most of it happens behind something the user can already read.
How It Works
On the wire
A non-streamed response carries Content-Length and arrives in one piece. A streamed response uses Transfer-Encoding: chunked (HTTP/1.1) or a stream of DATA frames (HTTP/2 and HTTP/3), and its length is unknown until it ends.
The first chunk pays for the paint; the rest pays for the content.
The first chunk matters out of proportion to its size. It contains the <head>, so the browser's preload scanner can start fetching CSS, fonts and the JavaScript bundle while the server is still waiting on the database. Those downloads now overlap the query instead of queueing behind it.
Out-of-order streaming
A naive stream follows document order. The server cannot send the footer before the middle. That is a problem when the middle is the slow part.
Frameworks solve it with a placeholder-and-swap trick. The slow region is emitted as an empty placeholder with an identifier. When its data resolves, the server appends the real markup at the end of the document plus a tiny inline script that moves it into place.
What actually goes over the wire:
<main>
<div id="reviews"><!--fallback skeleton--></div>
</main>
<!-- ...later in the same response... -->
<template id="chunk:reviews"><ul><li>Great product</li></ul></template>
<script>document.getElementById('reviews').replaceWith(
document.getElementById('chunk:reviews').content)</script>This is what React does behind a <Suspense> boundary, and it is why regions can arrive in completion order rather than document order. Suspense, Streaming and Error Boundaries covers the React-side API. This chapter is about the transport underneath it.
Producing a stream in TypeScript
Every server runtime exposes the same shape: a stream you write into, which the framework flushes.
A hand-rolled streaming response with the Web Streams API:
export async function handler(): Promise<Response> {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller: ReadableStreamDefaultController<Uint8Array>) {
// Chunk 1 — flush immediately. The preload scanner starts work here.
controller.enqueue(encoder.encode('<!doctype html><head>...</head><body><nav>...</nav>'));
const reviews: string = await renderReviews(); // the slow part
controller.enqueue(encoder.encode(`<main>${reviews}</main></body>`));
controller.close();
},
});
return new Response(stream, {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}The example shows one rule: do not await anything before the first enqueue. One awaited call above that line turns a streamed response back into a buffered one. Nothing reports an error.
Which metric moves
| Metric | What it measures | Does streaming help? |
|---|---|---|
| TTFB | First byte of the response | Yes, dramatically — the shell no longer waits for data |
| FCP | First pixel of content | Yes, if the shell contains visible content and its CSS |
| LCP | The largest element paints | Only if the largest element is in the shell |
| INP | Response to interaction | No — that is hydration, not streaming |
This table answers the most common rendering interview question. Streaming is a time to first byte technique that also helps first paint. It does nothing for the hero image. That is a Caching and Asset Delivery problem. It does nothing for interactivity, which is a The Rendering Spectrum and the Cost of Hydration problem.
⚠️ Streaming can make LCP worse. If the largest element is inside a streamed region, the browser paints a skeleton first, then the real content. LCP is measured at the second paint, after the data arrived. A buffered page would have painted once, later, but with a better LCP. Keep the LCP element out of the slow region.
The headers you gave up
Once the first byte is out, the response status and headers are fixed. That has three consequences worth saying out loud in a design round:
- A failure after the flush cannot become a 500. The best you can do is stream an error message into the page. This is why streaming frameworks push you towards error boundaries.
- A redirect after the flush is not possible. Authentication checks and redirects must happen before the shell goes out. This is the real reason they live in middleware.
Set-Cookieafter the flush is ignored. Session rotation belongs above the render.
What silently disables it
Streaming is unusually easy to break without an error, because a buffered response is a valid response.
| Cause | Symptom |
|---|---|
An await before the first flush | TTFB equals the slowest query |
| A proxy or WAF that buffers the body | Works locally, buffered in production |
| Compression configured to buffer whole responses | Same, and often blamed on the CDN |
| A framework middleware that reads the response body | Buffered, and hard to find |
| Serving through a platform that caches whole responses | Correct output, no streaming |
The check is one command. Run curl -N on the route and watch whether bytes arrive in groups. If everything lands at once, something between your code and the terminal is buffering.
When to Use It
| Situation | Stream? | Why |
|---|---|---|
| Page with one slow region and a fast shell | Yes | The textbook case |
| Every query is fast (under ~50 ms) | No | The complexity buys nothing measurable |
| Fully static or ISR-cached page | No | There is nothing to wait for |
| Page whose largest element depends on the slow query | Careful | You may trade LCP for TTFB |
| API returning JSON to a client | Different problem | See Real-Time and Streaming APIs |
Common Mistakes
❌ Awaiting data in the layout. ✅ A layout that awaits blocks the shell, so nothing streams. Push the await down into the component that needs it, behind a boundary.
❌ Putting a boundary around the whole page. ✅ One boundary containing everything is a buffered page with a spinner. Boundaries should wrap the parts that are actually slow.
❌ Streaming without a fallback that reserves space. ✅ With a zero-height skeleton, the content pushes the page down when it arrives. You have turned a latency win into a layout shift.
❌ Assuming crawlers cannot read a streamed page. ✅ They can. Chunked transfer is ordinary HTTP. The caveat is different and is covered in Choosing a Rendering Strategy per Route, with SEO.
❌ Declaring streaming works because it works locally. ✅ Local has no CDN, no WAF and no reverse proxy. Verify against the deployed URL.
🔑 Key Takeaways
- Streaming flushes the shell before the data resolves, so downloads overlap queries instead of queueing.
- Out-of-order delivery uses a placeholder plus an inline script, which is why regions can land early.
- It moves TTFB and usually FCP. It moves LCP only if the largest element is in the shell.
- After the first byte, the status, redirects and cookies are already decided.
- A single
awaitabove the first flush, or one buffering proxy, silently turns it off.
Interview Questions
Q: Your TTFB is 1.8 seconds on a server-rendered page. What do you do?
Find out what the server is waiting for before its first byte. Usually one query in a layout blocks the whole render. Flush the shell first and move the slow region behind a boundary. TTFB then becomes the cost of rendering the layout, not the cost of the slowest query on the page.
Q: Can streaming make a page worse?
Yes, in two ways. If the largest contentful element is in a streamed region, LCP is measured after the swap and gets worse. And a fallback that does not reserve the right space turns the wait into cumulative layout shift. Streaming pays off when the shell is worth looking at.
Q: Why can't a streamed response redirect when authentication fails halfway through?
The status line and headers went out with the first chunk and cannot be recalled. Anything that changes the response as a whole (status, redirect, Set-Cookie) must be decided before the shell is flushed. That is why authentication checks sit in middleware above the render.
Q: How would you prove that streaming is actually happening in production?
Request the deployed URL with curl -N and watch for bytes arriving in distinct groups. Check that the response uses chunked transfer, not a Content-Length. Compare TTFB in field data with the duration of the slowest query. If they match, something in the path is buffering the response.
What to Read Next
- Suspense, Streaming and Error Boundaries — the React API that drives the boundaries
- Choosing a Rendering Strategy per Route, with SEO — where streaming fits among the alternatives
- Core Web Vitals — the definitions behind the metric table