Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Streaming and Performance

Streaming with Promises and Suspense

Stream slow data in Remix and React Router: return unawaited promises from a loader, show fallbacks with Suspense and Await, handle rejected promises and know when not to stream.

A page is only as fast as its slowest loader, unless you let the slow part arrive later. Suppose a product page needs the product (a quick query) and personalized recommendations (a slow service). If the loader awaits both, the visitor stares at a blank tab until the recommendations finish. With streaming, the loader returns the quick data as normal values and the slow data as an unawaited promise. The server sends the page shell immediately, and the promise's result is streamed in later and slotted into place.

This is one of the best features of the framework, and it works with plain promises: no special wrapper. The real code is read-only here; the runnable examples model what the server and the browser do.

Return a promise, do not await it

TSX
// app/routes/product.$id.tsx (React Router framework mode, read-only)
import { Suspense } from "react";
import { Await } from "react-router";
import type { Route } from "./+types/product.$id";

export async function loader({ params }: Route.LoaderArgs) {
  const product = await db.product.find(params.id);      // awaited: needed for the first paint
  const recommendations = fetchRecommendations(params.id); // NOT awaited: a promise

  return { product, recommendations };
}

export default function Product({ loaderData }: Route.ComponentProps) {
  const { product, recommendations } = loaderData;
  return (
    <main>
      <h1>{product.name}</h1>

      <Suspense fallback={<p>Loading recommendations...</p>}>
        <Await resolve={recommendations} errorElement={<p>Could not load recommendations.</p>}>
          {(items) => (
            <ul>
              {items.map((item) => <li key={item.id}>{item.name}</li>)}
            </ul>
          )}
        </Await>
      </Suspense>
    </main>
  );
}

What happens, step by step:

  1. The loader awaits only the product, then returns right away, carrying the pending promise.
  2. The server renders HTML with the heading and the Suspense fallback, and starts sending it.
  3. The connection stays open. When the promise settles, the server writes a small extra chunk with the resolved value.
  4. In the browser, Await receives the value and replaces the fallback. No second request is made.
sequenceDiagram
  participant B as Browser
  participant S as Server
  B->>S: GET /product/7
  S-->>B: HTML shell + fallback (first bytes at 40 ms)
  Note over S: slow service still working
  S-->>B: chunk: recommendations ready (at 900 ms)
  B->>B: Await swaps fallback for the list

The first paint no longer waits for the slow part.

Node.js Stand-in: awaiting everything versus streaming

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.

(Times vary a little between runs; the point is the order and the gap.)

Errors in streamed promises

A rejected promise does not break the whole page. The errorElement of that Await renders instead, and the rest of the page stays as it was. If you omit errorElement, the rejection bubbles to the route's error boundary. One caveat: the promise starts running as soon as the loader calls it, so a rejection that happens before React attaches a handler is still handled, because the framework observes the promise for you.

Node.js Stand-in: a rejected streamed promise

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.

Where streaming fits (and where it does not)

Stream data that is slow and not essential to the first impression: recommendations, comments, analytics, reviews. Await data that:

  • decides what the page is (the product itself, whether the user is signed in),
  • is needed for the page title or meta tags (they live in the head, which has already been sent),
  • is critical for SEO. Crawlers that execute JavaScript will see streamed content, but the safest approach is to await what you want indexed.

Streaming also changes status codes. The status and headers go out with the first bytes, so you cannot turn a streamed failure into a 404 afterwards; check for missing records with an awaited call and throw before returning.

Streaming works for navigation too

On a client-side link click, the router also receives promises through its single fetch response and renders the fallback while they resolve. Combine it with pending UI to avoid blank screens. You can also stream from clientLoader in the browser; the pattern is identical.

Hosting needs

Streaming requires a server that does not buffer responses. Node servers, Cloudflare Workers and Vercel support it. Some reverse proxies buffer unless told otherwise, which makes a streamed page appear all at once; see Deployment Targets.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you stream data from a loader?

    Promises in loader data are serialized specially. The shell is sent first and the resolved value follows on the same response.
  2. 2. What renders when a streamed promise rejects and Await has an errorElement?

    Errors are scoped to the Await boundary when an errorElement is given.
  3. 3. Which data should you await before returning rather than stream?

    Status codes and headers are sent first, so anything that decides them must be awaited.
  4. 4. Why can streaming fail to show progressively behind some proxies?

    Buffering proxies hold the response until it completes; disable response buffering for streamed routes.

Summary

  • Return slow, non-critical data as unawaited promises; await what shapes the page and its status code.
  • Use Suspense with Await and a fallback; add errorElement to isolate failures.
  • Streaming rides on the same response; no extra request is made.
  • Your host and proxies must not buffer responses.

Next: HTTP Caching and Headers