Next.js streaming
A dashboard with three sections whose data takes 0.3, 1.5 and 3 seconds to load. The page shell reaches the browser at once, and each section streams in on its own as soon as its request finishes on the server. In the browser, every section's hooks start with the streamed data and send no request.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
"use client";
import { useFetch } from "@hyper-fetch/react";
import { currentUser, latestPosts, topProducts } from "@/lib/api";
// Each hook starts with the data streamed from the server: no loading state and, while it is fresh, no request.
export const Profile = () => {
const { data, error } = useFetch(currentUser, { revalidate: false });
if (error || !data) return <p className="error">Could not load the profile.</p>;
return (
<p>
<strong>
{data.firstName} {data.lastName}
</strong>
, {data.company.title}
<br />
<small className="muted">{data.email}</small>
</p>
);
};
export const Posts = () => {
const { data, error, loading, refetch } = useFetch(latestPosts, {
revalidate: false,
});
if (error || !data) return <p className="error">Could not load posts.</p>;
return (
<>
<ul>
{data.posts.map((post) => (
<li key={post.id}>
{post.title} <small className="muted">{post.views} views</small>
</li>
))}
</ul>
{/* The hook is live after hydration: this sends the request from the browser. */}
<button type="button" className="outline secondary" onClick={refetch} aria-busy={loading} disabled={loading}>
Refetch in the browser
</button>
</>
);
};
export const Products = () => {
const { data, error } = useFetch(topProducts, { revalidate: false });
if (error || !data) return <p className="error">Could not load products.</p>;
return (
<ul>
{data.products.map((product) => (
<li key={product.id}>
{product.title}{" "}
<small className="muted">
${product.price}, rated {product.rating}
</small>
</li>
))}
</ul>
);
};
npx tiged BetterTyped/hyper-fetch/examples/nextjs/streaming hyper-fetch-nextjs-streaming && cd hyper-fetch-nextjs-streaming && npm install && npm run dev- One Suspense boundary per section: a slow request only delays its own section.
- Async server components send the request with
send()and pack the response withdehydrate(). Hydrateper section puts each response into the client cache when that section arrives.- Live hooks after streaming:
useFetchrenders the server data, andrefetch()still works in the browser.
How it works
-
lib/api.tscreates one client for both sides and exports three prepared requests. Their query params include adelaythat makes dummyjson answer slowly. The server and the browser import the same request objects, so their cache keys match. -
app/page.tsxrenders the heading right away and wraps each section in its own<Suspense>with a fallback. Next.js sends the shell with the three fallbacks first, then each section as it resolves. The header of every section shows how long after the start it was streamed. -
Sectionis an async server component. It awaitsrequest.send()and passes the dehydrated response down:const hydration = [response.success ? request.dehydrate({ response }) : null];<HydrateClient data={hydration}>{children}</HydrateClient>;Only successful responses are passed, because an
Errorcannot cross into a client component. When a request fails, the hook fetches it in the browser instead. -
app/hydrate-client.tsxis a small client component around<Hydrate client={client}>. A server component can't pass the client instance, so this file imports it on the client side. -
app/sections.tsxholds the client components. Each callsuseFetch(request, { revalidate: false })and renders the streamed data on its first render, with no loading state. "Refetch in the browser" callsrefetch()to show that the hook works normally after hydration. -
On the server the client runs in server mode, which caches nothing for unscoped requests, so parallel renders for different users never share data.
- Pages that combine fast and slow data, where the fast parts should not wait for the slowest request.
- Dashboards, product pages and feeds that need content in the first HTML and interactive hooks after it.
- Without streaming, see Next.js App Router, which renders everything in one response.
Related
Each Suspense boundary awaits one HyperFetch request on the server and streams its section when it is ready. Hydrate
fills the client cache section by section, so the hooks start with data and stay fully interactive.
