Next.js App Router
A Next.js 16 page that renders a list of posts on the server. The browser receives the HTML with the posts in it, and the client cache starts with the same response, so nothing is fetched again after hydration.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
"use client";
import { Hydrate, type HydrateProps, useFetch } from "@hyper-fetch/react";
import { useState } from "react";
import { client, getPostComments, latestPosts } from "@/lib/api";
const Comments = ({ postId }: { postId: number }) => {
// Not part of the server render: this request starts in the browser when a post is opened.
const { data, error, loading } = useFetch(getPostComments.setParams({ postId }));
if (loading && !data) return <p aria-busy="true">Loading comments in the browser...</p>;
if (error) return <p className="error">Could not load comments: {error.message}</p>;
if (!data?.comments.length) return <p className="muted">No comments.</p>;
return (
<ul>
{data.comments.map((comment) => (
<li key={comment.id}>
<strong>@{comment.user.username}</strong> {comment.body}
</li>
))}
</ul>
);
};
const PostList = () => {
const [opened, setOpened] = useState<number[]>([]);
// The first render already has the server data: no loading state and, while it is fresh, no request.
const { data, error, loading, refetch } = useFetch(latestPosts, { revalidate: false });
if (loading && !data) return <p aria-busy="true">Loading posts...</p>;
if (error) return <p className="error">Could not load posts: {error.message}</p>;
return (
<section>
<header className="toolbar muted">
<span>{data?.posts.length} posts, rendered with the HTML</span>
<button type="button" className="outline secondary" onClick={refetch} disabled={loading}>
Refetch in the browser
</button>
</header>
{data?.posts.map((post) => (
<article key={post.id}>
<header>
<strong>{post.title}</strong>
<br />
<small className="muted">
{post.views} views · {post.tags.join(", ")}
</small>
</header>
<p>{post.body}</p>
<details onToggle={(event) => event.currentTarget.open && setOpened((prev) => [...prev, post.id])}>
<summary>Comments</summary>
{opened.includes(post.id) && <Comments postId={post.id} />}
</details>
</article>
))}
</section>
);
};
/** `Hydrate` writes the server responses into the client cache before the hooks below it mount. */
export const Posts = ({ hydration }: { hydration: HydrateProps["data"] }) => (
<Hydrate client={client} data={hydration}>
<PostList />
</Hydrate>
);
npx tiged BetterTyped/hyper-fetch/examples/nextjs/app-router hyper-fetch-nextjs-app-router && cd hyper-fetch-nextjs-app-router && npm install && npm run dev- A server component sends the request with
send()and turns the response into plain data withdehydrate(). Hydrateputs that data into the client cache before the hooks below it mount.useFetchrenders the server data on the first render, with no loading state and no request.- Client-only requests still work as usual: comments load in the browser when you open them.
How it works
-
lib/api.tscreates one client used on both sides. It exportslatestPosts, a request with its query params set, so the server and the browser build the same cache key. -
app/page.tsxis an async server component. It awaitslatestPosts.send()and passes the dehydrated response to the client component:<Posts hydration={[response.success ? latestPosts.dehydrate({ response }) : null]} />Only successful responses are passed, because an
Errorobject cannot cross the server/client boundary. When the server request fails,useFetchfetches in the browser instead. -
app/posts.tsxstarts with"use client". A client instance cannot be passed from a server component, so this file imports the client and renders<Hydrate client={client} data={hydration}>. -
PostListcallsuseFetch(latestPosts, { revalidate: false }). The hydrated data is fresh for the request'sstaleTime(5 minutes by default), so the hook sends nothing. With the defaultrevalidate: trueit would show the server data and refresh it in the background. -
On the server the client runs in server mode, where the cache stores nothing for unscoped requests, so two users rendering at once never see each other's data.
-
next buildgeneratesnext-env.d.ts. Likecreate-next-app, the example lists it in.gitignoretogether with.next.
- Pages that must show data in the first HTML, for SEO or a fast first paint.
- Server components that already have the data and hand it to interactive client components.
- Apps that keep HyperFetch caching and hooks in the browser after a server render.
Related
The server sends the request and dehydrate() packs the response. Hydrate unpacks it into the client cache, so
useFetch starts with the data instead of a loading state.
