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.tsxand often_document.tsx - Exports named
getServerSideProps,getStaticPropsorgetStaticPathsin 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].tsxserves/blog/:slug;[...all].tsxcatches 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
pages/_app.tsx, to find providers and global layout- The page file for the route, starting with its data function (
getServerSidePropsorgetStaticProps) pages/api/handlers the page calls from the browser
How a request moves through the code
middleware.tsruns first if present.- Next.js matches the URL to a file under
pages/. - For server-rendered pages,
getServerSidePropsruns on each request; for static pages,getStaticPropsran at build time or during revalidation. - The returned
propsare passed to the page component, wrapped by_app.tsx. - In the browser, the page may call
pages/api/*endpoints withfetchfor further data.
Questions to ask about the repository
- Which pages are statically generated and which are rendered per request?
- What does
_app.tsxset 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
getServerSidePropsnever reaches the browser, but code in the component body does; secrets must stay in the data function or API routes. getStaticPropswithrevalidateserves cached HTML, so stale data is often expected behaviour rather than a bug.- Projects mid-migration have both
pages/andapp/; the same URL can't be defined in both, so check which tree owns a route.