Skip to main content

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.

intermediatenextjsssruseFetchcache
"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>
);
Run locallynpx tiged BetterTyped/hyper-fetch/examples/nextjs/app-router hyper-fetch-nextjs-app-router && cd hyper-fetch-nextjs-app-router && npm install && npm run dev
What it shows
  1. A server component sends the request with send() and turns the response into plain data with dehydrate().
  2. Hydrate puts that data into the client cache before the hooks below it mount.
  3. useFetch renders the server data on the first render, with no loading state and no request.
  4. Client-only requests still work as usual: comments load in the browser when you open them.

How it works​

  1. lib/api.ts creates one client used on both sides. It exports latestPosts, a request with its query params set, so the server and the browser build the same cache key.

  2. app/page.tsx is an async server component. It awaits latestPosts.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 Error object cannot cross the server/client boundary. When the server request fails, useFetch fetches in the browser instead.

  3. app/posts.tsx starts 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}>.

  4. PostList calls useFetch(latestPosts, { revalidate: false }). The hydrated data is fresh for the request's staleTime (5 minutes by default), so the hook sends nothing. With the default revalidate: true it would show the server data and refresh it in the background.

  5. 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.

  6. next build generates next-env.d.ts. Like create-next-app, the example lists it in .gitignore together with .next.

When to use it
  • 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.

Summary

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.