SSG with SWR in NextJS 15 App Router #4134
Unanswered
DriptaSenapati
asked this question in
General
Replies: 1 comment
-
|
SWR is a client-side data fetching library, so it does not run in Server Components directly. But you can combine server-side data fetching with SWR in the App Router using the The idea: fetch data in a Server Component using your ORM, then pass it to a Client Component as SWR fallback data so it hydrates instantly and revalidates in the background. 1. Server Component (fetches data with your ORM)// app/posts/page.tsx (Server Component)
import { db } from "@/lib/db"; // your ORM (Prisma, Drizzle, etc.)
import { PostList } from "./post-list";
export default async function PostsPage() {
const posts = await db.post.findMany({ take: 20 });
return <PostList fallbackData={posts} />;
}2. Client Component (uses SWR with fallback)// app/posts/post-list.tsx
"use client";
import useSWR from "swr";
const fetcher = (url: string) => fetch(url).then((r) => r.json());
export function PostList({ fallbackData }: { fallbackData: Post[] }) {
const { data: posts } = useSWR("/api/posts", fetcher, {
fallbackData, // renders immediately with server data
revalidateOnMount: true, // then revalidates in the background
});
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}3. API Route (for client-side revalidation)// app/api/posts/route.ts
import { db } from "@/lib/db";
import { NextResponse } from "next/server";
export async function GET() {
const posts = await db.post.findMany({ take: 20 });
return NextResponse.json(posts);
}Alternatively, if you want to provide fallback for multiple keys at once, use "use client";
import { SWRConfig } from "swr";
export function SWRProvider({ fallback, children }) {
return <SWRConfig value={{ fallback }}>{children}</SWRConfig>;
}// Server Component
export default async function Page() {
const posts = await db.post.findMany();
return (
<SWRProvider fallback={{ "/api/posts": posts }}>
<PostList />
</SWRProvider>
);
}This gives you the best of both worlds: instant server-rendered content for SEO and fast initial load, plus automatic client-side revalidation. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
As per documentation of swr SSG example is mentioned is for pages router. I need one example of app router in server component with data fetching using ORM, not using NextJS fetch.
Beta Was this translation helpful? Give feedback.
All reactions