Next.js Pages Router
A list of posts and a page for each post, built with the Next.js Pages Router. Both pages fetch in getServerSideProps,
so the HTML already contains the data, and the HyperFetch hooks in the browser start with the same responses. Clicking a
post navigates on the client, and the post still comes from the server.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { useFetch } from "@hyper-fetch/react";
import type { GetServerSideProps } from "next";
import Link from "next/link";
import type { HydrationProps } from "../_app";
import { getPost } from "@/lib/api";
type Props = HydrationProps & { postId: number };
export const getServerSideProps: GetServerSideProps<Props, { postId: string }> = async ({ params }) => {
const postId = Number(params?.postId);
const request = getPost.setParams({ postId });
const response = await request.send();
if (response.status === 404) return { notFound: true };
return {
props: {
postId,
hydration: response.success ? [request.dehydrate({ response })] : [],
},
};
};
export default function PostPage({ postId }: Props) {
// Same params as on the server, so the same cache key: the hydrated post renders at once.
const { data, error, loading, refetch } = useFetch(getPost.setParams({ postId }), { revalidate: false });
return (
<>
<nav>
<Link href="/">Back to posts</Link>
</nav>
{loading && !data && <p aria-busy="true">Loading post...</p>}
{error && <p className="error">Could not load the post: {error.message}</p>}
{data && (
<article>
<header>
<strong>{data.title}</strong>
<br />
<small className="muted">{data.views} views</small>
</header>
<p>{data.body}</p>
<footer>
<button
type="button"
className="outline secondary"
onClick={refetch}
aria-busy={loading}
disabled={loading}
>
Refetch in the browser
</button>
</footer>
</article>
)}
</>
);
}
npx tiged BetterTyped/hyper-fetch/examples/nextjs/pages-router hyper-fetch-nextjs-pages-router && cd hyper-fetch-nextjs-pages-router && npm install && npm run devgetServerSidePropssends the request withsend()and returnsrequest.dehydrate({ response })as props.- One
Hydratein_appwrites thehydrationprop of every page into the client cache. useFetchrenders the server data on the first render, with no loading state and no request.- Client navigation: a
LinkrunsgetServerSidePropson the server and hydrates the new page the same way.
How it works
-
lib/api.tscreates one client and exports the requests.latestPostshas its query params set, so the server and the page build the same cache key. -
pages/index.tsxawaitslatestPosts.send()ingetServerSidePropsand returns the dehydrated response:hydration: response.success ? [latestPosts.dehydrate({ response })] : [],A failed response is left out, and
useFetchfetches it in the browser instead. -
pages/_app.tsxrenders<Hydrate client={client} data={pageProps.hydration}>around every page. The exportedHydrationPropstype keeps the prop name the same in all pages. -
The page calls
useFetch(latestPosts, { revalidate: false }). The hydrated data is fresh for the request'sstaleTime, so the hook sends nothing. With the defaultrevalidate: trueit would show the server data and refresh it in the background. -
pages/posts/[postId].tsxreadsparams.postId, sendsgetPost.setParams({ postId })and returns{ notFound: true }for a404. The component builds the same request from thepostIdprop, so it finds the hydrated post. "Refetch in the browser" callsrefetch()to show the hook is live after hydration. -
On a
Linkclick, Next.js callsgetServerSidePropsthrough/_next/data/...json, and_apphydrates the new props. The browser never calls the API for these pages.
- Apps on the Pages Router that need data in the first HTML, for SEO or a fast first paint.
- Moving a Pages Router app to HyperFetch without changing how pages load their data.
- For the App Router, see Next.js App Router.
Related
getServerSideProps sends the request and returns dehydrate() as props. One Hydrate in _app puts every page's
responses into the client cache, so useFetch starts with the server data on first load and after client navigation.
