Next.jsEasy
What is getServerSideProps and when do you use it?
getServerSideProps is a Pages Router function that runs on the server for every request to a page, before it renders. Use it when the page needs request-specific data such as cookies, the current user or always-fresh values.
Key facts
- Export it from a page in
pages/. It runs only on the server, so secrets and database calls are safe. - The
contextincludesreq,res,params,query,resolvedUrl,localeanddraftMode. - Return
{ props },{ notFound: true }or{ redirect: { destination, permanent } }. - On client-side navigation, Next.js calls it via a JSON request, so the page still gets fresh data without a full reload.
- You can set caching headers on
res, for exampleCache-Control: s-maxage=10, stale-while-revalidate=59, to let a CDN cache the response.
Costs
- Time to first byte includes your data fetching on every request.
- The whole page waits; there is no per-component streaming.
- Pages using it cannot be served from a static CDN cache by default.
When to use it
Personalized dashboards, auth-gated pages, pages depending on headers (geo, A/B buckets) and data that must never be stale.
App Router equivalent
Read cookies() or headers() in an async Server Component. With Cache Components, only the component that reads request data runs per request, inside <Suspense>; the rest of the page stays in the static shell. That is usually faster than whole-page SSR.
Code example
tsx
1// pages/account.tsx2import type { GetServerSideProps, InferGetServerSidePropsType } from "next";3import { getSession } from "@/lib/session";45type User = { name: string; plan: string };67export const getServerSideProps = (async ({ req, res }) => {8 const session = await getSession(req.cookies.session);9 if (!session) {10 return { redirect: { destination: "/login", permanent: false } };11 }1213 // Private, per-user response: do not let shared caches store it14 res.setHeader("Cache-Control", "private, no-store");1516 const user: User = await fetch(`https://api.example.com/users/${session.userId}`).then((r) =>17 r.json()18 );19 return { props: { user } };20}) satisfies GetServerSideProps<{ user: User }>;2122export default function Account({ user }: InferGetServerSidePropsType<typeof getServerSideProps>) {23 return <h1>Welcome {user.name} ({user.plan})</h1>;24}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.