Streaming

Remix supports the web streaming API as a first-class citizen. Additionally, JavaScript server runtimes have support for streaming responses to the client.

NOTE: Deferred UX goals rely on streaming responses. Some popular hosts do not support streaming responses. In general, any bare metal / VM provider will support streaming. Make sure your hosting platform supports before using this API.

The problem

Imagine a scenario where one of your routes’ loaders needs to retrieve some data that for one reason or another is quite slow. For example, let’s say you’re showing the user the location of a package that’s being delivered to their home:

  1. import type { LoaderArgs } from "@remix-run/node"; // or cloudflare/deno
  2. import { json } from "@remix-run/node"; // or cloudflare/deno
  3. import { useLoaderData } from "@remix-run/react";
  4. import { getPackageLocation } from "~/models/packages";
  5. export async function loader({ params }: LoaderArgs) {
  6. const packageLocation = await getPackageLocation(
  7. params.packageId
  8. );
  9. return json({ packageLocation });
  10. }
  11. export default function PackageRoute() {
  12. const { packageLocation } =
  13. useLoaderData<typeof loader>();
  14. return (
  15. <main>
  16. <h1>Let's locate your package</h1>
  17. <p>
  18. Your package is at {packageLocation.latitude} lat
  19. and {packageLocation.longitude} long.
  20. </p>
  21. </main>
  22. );
  23. }

We’ll assume that getPackageLocation is slow. This will lead to initial page load times and transitions to that route to take as long as the slowest bit of data. Before reaching for rendering a fallback we recommend exploring ways to speed up that slow data, though not always possible here are a few things to explore first:

  • Speed up the slow thing (😅).
    • Optimize DB queries.
    • Add caching (LRU, Redis, etc).
    • Use a different data source.
  • Load data concurrently loading with Promise.all (we have nothing to make concurrent in our example, but it might help a bit in other situations).

If initial page load is not a critical metric for your application, you can also explore the following options that can improve the perceived performance of your application client side only:

  • Use the prefetch prop on .
  • Add a global transition spinner.
  • Add a localized skeleton UI.

If these approaches don’t work well, then you may feel forced to move the slow data out of the Remix loader into a client-side fetch (and show a skeleton fallback UI while loading). In this case you’d render the fallback UI on the server render and fire off the fetch for the data on the client. This is actually not so terrible from a DX standpoint thanks to useFetcher. And from a UX standpoint this improves the loading experience for both client-side transitions as well as initial page load. So it does seem to solve the problem.

But it’s still sub-optimal for two reasons:

  1. Client-side fetching puts your data request on a waterfall: document -> JavaScript -> data fetch
  2. Your code can’t easily switch between client-side fetching and server-side rendering (more on this later).

The solution

Remix takes advantage of React 18’s streaming and server-side support for <Suspense /> boundaries using the defer Response utility and component / useAsyncValue hook. By using these APIs, you can solve both of these problems:

  1. Your data is no longer on a waterfall: document & data (in parallel) -> JavaScript
  2. Your can easily switch between streaming and waiting for the data

Graphs showing how document and slow data requests sent over the same response significantly speed up the largest contentful paint

Let’s take a dive into how to accomplish this.

Enable React 18 Streaming

First, to enable streaming with React 18, you’ll update your entry.server.tsx file to use renderToPipeableStream. Here’s a simple (and incomplete) version of that:

  1. import { PassThrough } from "stream";
  2. import { Response } from "@remix-run/node"; // or cloudflare/deno
  3. import type {
  4. AppLoadContext,
  5. EntryContext,
  6. Headers,
  7. } from "@remix-run/node"; // or cloudflare/deno
  8. import { RemixServer } from "@remix-run/react";
  9. import { renderToPipeableStream } from "react-dom/server";
  10. export default function handleRequest(
  11. request: Request,
  12. responseStatusCode: number,
  13. responseHeaders: Headers,
  14. remixContext: EntryContext,
  15. loadContext: AppLoadContext
  16. ) {
  17. return new Promise((resolve) => {
  18. const { pipe } = renderToPipeableStream(
  19. <RemixServer
  20. context={remixContext}
  21. url={request.url}
  22. />,
  23. {
  24. onShellReady() {
  25. const body = new PassThrough();
  26. responseHeaders.set("Content-Type", "text/html");
  27. resolve(
  28. new Response(body, {
  29. status: responseStatusCode,
  30. headers: responseHeaders,
  31. })
  32. );
  33. pipe(body);
  34. },
  35. }
  36. );
  37. });
  38. }

For a more complete example, expand this

This handles errors and properly disables streaming for bots which you typically want to force waiting, so you can display all the content for SEO purposes.

  1. import { PassThrough } from "stream";
  2. import { Response } from "@remix-run/node"; // or cloudflare/deno
  3. import type {
  4. EntryContext,
  5. Headers,
  6. } from "@remix-run/node"; // or cloudflare/deno
  7. import { RemixServer } from "@remix-run/react";
  8. import isbot from "isbot";
  9. import { renderToPipeableStream } from "react-dom/server";
  10. const ABORT_DELAY = 5000;
  11. export default function handleRequest(
  12. request: Request,
  13. responseStatusCode: number,
  14. responseHeaders: Headers,
  15. remixContext: EntryContext,
  16. loadContext: AppLoadContext
  17. ) {
  18. // If the request is from a bot, we want to wait for the full
  19. // response to render before sending it to the client. This
  20. // ensures that bots can see the full page content.
  21. if (isbot(request.headers.get("user-agent"))) {
  22. return serveTheBots(
  23. request,
  24. responseStatusCode,
  25. responseHeaders,
  26. remixContext
  27. );
  28. }
  29. return serveBrowsers(
  30. request,
  31. responseStatusCode,
  32. responseHeaders,
  33. remixContext
  34. );
  35. }
  36. function serveTheBots(
  37. request: Request,
  38. responseStatusCode: number,
  39. responseHeaders: Headers,
  40. remixContext: EntryContext
  41. ) {
  42. return new Promise((resolve, reject) => {
  43. const { pipe, abort } = renderToPipeableStream(
  44. <RemixServer
  45. context={remixContext}
  46. url={request.url}
  47. abortDelay={ABORT_DELAY}
  48. />,
  49. {
  50. // Use onAllReady to wait for the entire document to be ready
  51. onAllReady() {
  52. responseHeaders.set("Content-Type", "text/html");
  53. const body = new PassThrough();
  54. pipe(body);
  55. resolve(
  56. new Response(body, {
  57. status: responseStatusCode,
  58. headers: responseHeaders,
  59. })
  60. );
  61. },
  62. onShellError(err: unknown) {
  63. reject(err);
  64. },
  65. }
  66. );
  67. setTimeout(abort, ABORT_DELAY);
  68. });
  69. }
  70. function serveBrowsers(
  71. request: Request,
  72. responseStatusCode: number,
  73. responseHeaders: Headers,
  74. remixContext: EntryContext
  75. ) {
  76. return new Promise((resolve, reject) => {
  77. let didError = false;
  78. const { pipe, abort } = renderToPipeableStream(
  79. <RemixServer
  80. context={remixContext}
  81. url={request.url}
  82. abortDelay={ABORT_DELAY}
  83. />,
  84. {
  85. // use onShellReady to wait until a suspense boundary is triggered
  86. onShellReady() {
  87. responseHeaders.set("Content-Type", "text/html");
  88. const body = new PassThrough();
  89. pipe(body);
  90. resolve(
  91. new Response(body, {
  92. status: didError ? 500 : responseStatusCode,
  93. headers: responseHeaders,
  94. })
  95. );
  96. },
  97. onShellError(err: unknown) {
  98. reject(err);
  99. },
  100. onError(err: unknown) {
  101. didError = true;
  102. console.error(err);
  103. },
  104. }
  105. );
  106. setTimeout(abort, ABORT_DELAY);
  107. });
  108. }

Then on the client you need to make sure you’re hydrating properly with the React 18 hydrateRoot API:

  1. import { RemixBrowser } from "@remix-run/react";
  2. import { hydrateRoot } from "react-dom/client";
  3. hydrateRoot(document, <RemixBrowser />);

With just that in place, you’re unlikely to see any significant performance improvement. But with that alone you can now use React.lazy to SSR components but delay hydration on the client. This can open up network bandwidth for more critical things like styles, images, and fonts leading to a better LCP and TTI.

Using defer

With React streaming set up, now you can start adding Await usage for your slow data requests where you’d rather render a fallback UI. Let’s do that for our example above:

  1. import type { LoaderArgs } from "@remix-run/node"; // or cloudflare/deno
  2. import { defer } from "@remix-run/node"; // or cloudflare/deno
  3. import { Await, useLoaderData } from "@remix-run/react";
  4. import { Suspense } from "react";
  5. import { getPackageLocation } from "~/models/packages";
  6. export function loader({ params }: LoaderArgs) {
  7. const packageLocationPromise = getPackageLocation(
  8. params.packageId
  9. );
  10. return defer({
  11. packageLocation: packageLocationPromise,
  12. });
  13. }
  14. export default function PackageRoute() {
  15. const data = useLoaderData<typeof loader>();
  16. return (
  17. <main>
  18. <h1>Let's locate your package</h1>
  19. <Suspense
  20. fallback={<p>Loading package location...</p>}
  21. >
  22. <Await
  23. resolve={data.packageLocation}
  24. errorElement={
  25. <p>Error loading package location!</p>
  26. }
  27. >
  28. {(packageLocation) => (
  29. <p>
  30. Your package is at {packageLocation.latitude}{" "}
  31. lat and {packageLocation.longitude} long.
  32. </p>
  33. )}
  34. </Await>
  35. </Suspense>
  36. </main>
  37. );
  38. }

Alternatively, you can use the `useAsyncValue` hook:

If you’re not jazzed about bringing back render props, you can use a hook, but you’ll have to break things out into another component:

  1. import type { SerializeFrom } from "@remix-run/node"; // or cloudflare/deno
  2. export default function PackageRoute() {
  3. const data = useLoaderData<typeof loader>();
  4. return (
  5. <main>
  6. <h1>Let's locate your package</h1>
  7. <Suspense
  8. fallback={<p>Loading package location...</p>}
  9. >
  10. <Await
  11. resolve={data.packageLocation}
  12. errorElement={
  13. <p>Error loading package location!</p>
  14. }
  15. >
  16. <PackageLocation />
  17. </Await>
  18. </Suspense>
  19. </main>
  20. );
  21. }
  22. function PackageLocation() {
  23. const packageLocation = useAsyncValue() as SerializeFrom<
  24. typeof loader
  25. >["packageLocation"];
  26. return (
  27. <p>
  28. Your package is at {packageLocation.latitude} lat and{" "}
  29. {packageLocation.longitude} long.
  30. </p>
  31. );
  32. }

Evaluating the solution

So rather than waiting for the whole document -> JavaScript -> hydrate -> request cycle, with streaming we start the request for the slow data as soon as the document request comes in. This can significantly speed up the user experience.

Remix treats any Promise values as deferred data. These will be streamed to the client as each Promise resolves. If you’d like to prevent streaming for critical data, just use await and it will be included in the initial presentation of the document to the user.

  1. return defer({
  2. // critical data (not deferred):
  3. packageLocation: await packageLocationPromise,
  4. // non-critical data (deferred):
  5. packageLocation: packageLocationPromise,
  6. });

Because of this, you can A/B test deferring, or even determine whether to defer based on the user or data being requested:

  1. export async function loader({
  2. request,
  3. params,
  4. }: LoaderArgs) {
  5. const packageLocationPromise = getPackageLocation(
  6. params.packageId
  7. );
  8. const shouldDefer = await shouldDeferPackageLocation(
  9. request,
  10. params.packageId
  11. );
  12. return defer({
  13. packageLocation: shouldDefer
  14. ? packageLocationPromise
  15. : await packageLocationPromise,
  16. });
  17. }

That shouldDeferPackageLocation could be implemented to check the user making the request, whether the package location data is in a cache, the status of an A/B test, or whatever else you want. This is pretty sweet 🍭

Also, because this happens at request time (even on client transitions), makes use of the URL via nested routing (rather than requiring you to render before you know what data to fetch), and it’s all just regular HTTP, we can prefetch and cache the response! Meaning client-side transitions can be much faster (in fact, there are plenty of situations when the user may never be presented with the fallback at all).

Another thing that’s not immediately recognizable is if your server can finish loading deferred data before the client can load the JavaScript and hydrate, the server will stream down the HTML and add it to the document before React hydrates, thereby increasing performance for those on slow networks. This works even if you never add <Scripts /> to the page thanks to React 18’s support for out-of-order streaming.

FAQ

Why not defer everything by default?

The Remix defer API is another lever Remix offers to give you a nice way to choose between trade-offs. Do you want a better TTFB (Time to first byte)? Defer stuff. Do you want a low CLS (Content Layout Shift)? Don’t defer stuff. You want a better TTFB, but also want a lower CLS? Defer just the slow and unimportant stuff.

It’s all trade-offs, and what’s neat about the API design is that it’s well suited for you to do easy experimentation to see which trade-offs lead to better results for your real-world key indicators.

When does the fallback render?

The <Await /> component will only throw the promise up the <Suspense> boundary on the initial render of the <Await /> component with an unsettled promise. It will not re-render the fallback if props change. Effectively, this means that you will not get a fallback rendered when a user submits a form and loader data is revalidated. You will get a fallback rendered when the user navigates to the same route with different params (in the context of our above example, if the user selects from a list of packages on the left to find their location on the right).

This may feel counter-intuitive at first, but stay with us, we really thought this through and it’s important that it works this way. Let’s imagine a world without the deferred API. For those scenarios you’re probably going to want to implement Optimistic UI for form submissions/revalidation.

When you decide you’d like to try the trade-offs of defer, we don’t want you to have to change or remove those optimizations because we want you to be able to easily switch between deferring some data and not deferring it. So we ensure that your existing optimistic states work the same way. If we didn’t do this, then you could experience what we call “Popcorn UI” where submissions of data trigger the fallback loading state instead of the optimistic UI you’d worked hard on.

So just keep this in mind: Deferred is 100% only about the initial load of a route and it’s params.