Skip to Content
Nextjs3.3 Pages Router Data Fetching

Pages Router Data Fetching 📚

Even if you live in the App Router, interviewers still ask about classic data fetching methods. Here’s the cheat sheet.

getStaticProps (SSG) 🏗️

Runs at build time to generate static HTML.

export async function getStaticProps() { const posts = await fetchCMS(); return { props: { posts }, revalidate: 60, // optional ISR }; }
  • Uses the same props on every request until rebuilt.
  • revalidate (seconds) enables Incremental Static Regeneration (see below).
  • Great for marketing pages, blogs, docs.

getStaticPaths 🗺️

Used with dynamic routes to pre-render specific paths.

export async function getStaticPaths() { const slugs = await fetchPostSlugs(); return { paths: slugs.map(slug => ({ params: { slug } })), fallback: 'blocking', }; }
  • fallback: false → only listed paths, others 404.
  • fallback: true → render fallback UI, then cache generated page.
  • fallback: 'blocking' → wait for server-rendered HTML before responding.

getServerSideProps (SSR) ⚡

Runs on every request.

export async function getServerSideProps({ req, res, params }) { const session = await getSession(req); const data = await fetchPersonalized(session.userId); return { props: { data } }; }
  • Access request headers, cookies, query params.
  • Best for personalized dashboards, A/B testing, auth-heavy routes.

Incremental Static Regeneration (ISR) ♻️

  • Combine getStaticProps with revalidate to regenerate pages in the background.
  • First request after the timer triggers a rebuild; subsequent requests see fresh content.
  • Works with fallback: 'blocking' for on-demand generation.

On-demand Revalidation

Use API route + secret token to trigger rebuilds:

// pages/api/revalidate.ts export default async function handler(req, res) { if (req.query.secret !== process.env.REVALIDATE_SECRET) { return res.status(401).json({ message: 'Invalid token' }); } await res.revalidate(`/blog/${req.body.slug}`); return res.json({ revalidated: true }); }

Decision Table 🧮

RequirementMethod
Static content, rarely changesgetStaticProps
Static content with dynamic routesgetStaticProps + getStaticPaths
Needs request-time datagetServerSideProps
Static but should refresh periodicallygetStaticProps + revalidate
Mix static shell + client fetchomit data fetching, use CSR (SWR/React Query)

Analogy: Think of getStaticProps as baking pastries overnight, getServerSideProps as cooking made-to-order dishes, and ISR as rebaking pastries when they get stale.

Even in App Router interviews, showing fluency with these older APIs proves you can maintain legacy codebases. 💪

Last updated on