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>;
}