Sub topic 17
Streaming slow data with Await
This chapter shows how to send fast data to the browser right away and stream slow data later. It uses Await and Suspense. It assumes you know how loaders and loaderData work, can read a route module, and understand promises and async/await in TypeScript. It also assumes you know basic React Suspense.
The problem: one slow query blocks the page
A loader normally awaits everything it needs before the server sends HTML. If one query is slow, the user sees nothing until it finishes.
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId); // 20 ms
const stats = await getContactStats(params.contactId); // 2000 ms
return { contact, stats };
}The page cannot render until both calls finish. The contact name is ready after 20 ms, but the user waits about two seconds for it.
Streaming fixes this. The loader returns a promise without awaiting it. React Router sends the HTML shell and the resolved data first. When the promise settles, the server sends the result over the same HTTP response, and the browser fills in the missing part.
Returning a promise from a loader
Await the data that is needed for the first paint. Do not await the slow data. Return its promise inside the object.
import { Suspense } from "react";
import { Await } from "react-router";
import type { Route } from "./+types/detail";
import { getContact, getContactStats } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
const stats = getContactStats(params.contactId); // no await
return { contact, stats };
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
const { contact, stats } = loaderData;
return (
<div>
<h1>{contact.name}</h1>
<Suspense fallback={<p>Loading stats...</p>}>
<Await resolve={stats} errorElement={<p>Could not load stats.</p>}>
{(value) => <p>{value.messageCount} messages</p>}
</Await>
</Suspense>
</div>
);
}The pieces work together as follows:
contactis awaited, so it is plain data in the component.statsis a promise. React Router serializes it and keeps the connection open until it settles.Suspenseshowsfallbackwhile the promise is pending.Awaittakes the promise inresolve. Its child function receives the resolved value.errorElementrenders if the promise rejects.
Top-level promises in the returned object are streamed. Promises nested deeper are not, so keep them at the top level of the object.
How it works on the wire
On the first request, the server renders HTML with the fallback in place. It then keeps the response open. When stats resolves, the server writes a small script chunk that delivers the value, and React replaces the fallback.
During client-side navigation, the loader runs through a data request. The response streams the same way, and the route renders once the awaited data is ready.
Awaiting versus streaming: a decision rule
Not every value should be streamed. Use this table to decide.
| Data | Approach | Reason |
|---|---|---|
| Needed for the title, meta tags, or a 404 check | `await` | The loader must decide before rendering |
| Core content the page makes no sense without | `await` | A fallback would be a poor experience |
| Slow, secondary content such as stats or recommendations | Return the promise | The page stays useful while it loads |
| Data that decides a redirect | `await` | A redirect cannot happen after streaming starts |
Edge cases and gotchas
- Status codes are fixed early. The HTTP status and headers are sent before the promise settles. A rejected promise cannot turn a 200 into a 500. Handle it with
errorElement. - A thrown error in an awaited call still reaches the route
ErrorBoundary. Only rejected promises passed toAwaituseerrorElement. - Unhandled rejections. If a streamed promise rejects and nothing renders an
Awaitfor it, you may see unhandled rejection warnings. Always render each streamed promise withAwait. metacannot depend on streamed data. Meta runs from resolved loader data, so await anything the title needs.- Server timeouts. Long-running streams can be cut by hosting platforms. If a promise can take very long, add your own timeout in the loader.
- Buffering proxies. Some proxies or CDNs buffer responses. Streaming then appears to wait until everything is done. Test in your real deployment.
- Static output. Prerendered pages and SPA mode have no server to stream from at request time. Streamed data does not suit them.
Using the `use` hook instead
React 19 also lets a component read a promise with use. In framework mode, Await is the documented path and works with Suspense and errorElement in one component. Use use only if you prefer React's own API, and then wrap the component in Suspense and an error boundary yourself.
Adding a timeout to protect the page
A slow dependency that never answers keeps the stream open. Wrap the slow call with a timeout so the fallback eventually gives way to the error element.
export function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error(`Timed out after ${ms} ms`)),
ms,
);
promise.then(
(value) => {
clearTimeout(timer);
resolve(value);
},
(error) => {
clearTimeout(timer);
reject(error);
},
);
});
}In the loader, use const stats = withTimeout(getContactStats(params.contactId), 3000);. After three seconds the errorElement renders instead of an endless loading message.
Exercises
Exercise
A loader returns { contact, stats }. contact is awaited and stats is a promise for a query that takes three seconds. Which parts of the page appear first, and what renders in place of stats until it resolves?
Show answer
The HTML with the contact data appears first, because it was awaited. The Suspense fallback renders in place of stats until the promise resolves, and then Await renders its child with the resolved value.
Exercise
Your streamed stats promise rejects after the page has loaded. What status code does the response have, and how do you show an error to the user?
Show answer
The status is whatever was sent when streaming began, normally 200, because the status cannot change afterward. Pass an errorElement to Await so the failed section shows an error message.
Exercise
The page title must include the contact's name and the number of messages, and the message count is slow. Should the count be streamed? Explain.
Show answer
No. meta runs from resolved loader data, so the data used in the title must be awaited. Stream only content that is not needed for the title, or leave the count out of the title.