Skip to content

How to understand a Next.js (Pages Router) codebase

Pages Router projects map files under `pages/` to URLs. Each page is a React component, and data fetching happens in exported functions such as `getServerSideProps` or `getStaticProps` that run on the server before the component renders. Many production apps still run on it, often alongside a newer `app/` directory.

How to tell it's Next.js (Pages Router)

  • A pages/ directory with _app.tsx and often _document.tsx
  • Exports named getServerSideProps, getStaticProps or getStaticPaths in page files
  • API endpoints under pages/api/

Where things usually live

pages/_app.tsx
Wraps every page: global CSS, providers, layout components and per-page layout patterns.
pages/_document.tsx
Customises the HTML document, rendered only on the server.
pages/**/*.tsx
Routes. pages/blog/[slug].tsx serves /blog/:slug; [...all].tsx catches everything below.
pages/api/**
Serverless API routes with a (req, res) handler.
components/
Shared React components.
lib/
Data fetching, database clients and helpers used by data functions and API routes.
middleware.ts
Edge middleware that runs before matching pages.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. pages/_app.tsx, to find providers and global layout
  2. The page file for the route, starting with its data function (getServerSideProps or getStaticProps)
  3. pages/api/ handlers the page calls from the browser

How a request moves through the code

  1. 1middleware.ts runs first if present.
  2. 2Next.js matches the URL to a file under pages/.
  3. 3For server-rendered pages, getServerSideProps runs on each request; for static pages, getStaticProps ran at build time or during revalidation.
  4. 4The returned props are passed to the page component, wrapped by _app.tsx.
  5. 5In the browser, the page may call pages/api/* endpoints with fetch for further data.

Questions to ask about the repository

  • Which pages are statically generated and which are rendered per request?
  • What does _app.tsx set up for every page?
  • Which API routes write to the database, and who calls them?
  • Is there an app/ directory as well, and which routes live there?
  • How does the app handle authentication on server-rendered pages?

What trips people up

  • Code inside getServerSideProps never reaches the browser, but code in the component body does; secrets must stay in the data function or API routes.
  • getStaticProps with revalidate serves cached HTML, so stale data is often expected behaviour rather than a bug.
  • Projects mid-migration have both pages/ and app/; the same URL can't be defined in both, so check which tree owns a route.