Next.js SSR Data Fetching with getServerSideProps
Fetch data server-side in Next.js using getServerSideProps for SEO-friendly pages with fresh data on every request. Includes error handling, TypeScript.
Code
import { GetServerSideProps, InferGetServerSidePropsType } from 'next';
interface Post { id: number; title: string; body: string; }
export const getServerSideProps: GetServerSideProps<{ posts: Post[] }> = async (ctx) => {
try {
const res = await fetch('https://api.example.com/posts');
if (!res.ok) return { notFound: true };
const posts = await res.json() as Post[];
ctx.res.setHeader('Cache-Control', 's-maxage=60, stale-while-revalidate=300');
return { props: { posts } };
} catch {
return { notFound: true };
}
};
export default function Page({ posts }: InferGetServerSidePropsType<typeof getServerSideProps>) {
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}What the code does
Count the function Page as the entire surface area of Next.js SSR Data Fetching with getServerSideProps.
The asynchronous flow is linearized with await, keeping failure handling local. The import line is the dependency contract: GetServerSideProps, InferGetServerSidePropsType come from next and nothing else.
It builds and returns a fresh value rather than reusing its inputs.
What to watch for
- Requires
nextas a package; the snippet will not run without it. - Uses
fetch, so it needs a browser context — it will not run as-is in Node without shims. - The guard
!res.okshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Signature: export const getServerSideProps: GetServerSideProps<{ posts: Post[] }> = async (ctx)
The surface worth importing is getServerSideProps; the helpers around it are private to the snippet.
Statements that matter
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
const res = await fetch('https://api.example.com/posts');
const posts = await res.json() as Post[];
FAQ
- Does `getServerSideProps` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Are there third-party dependencies?
- `next` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.