Pages Router (Legacy) 🕰️
Before the App Router, Next.js used /pages for routing. Many production apps still do, so knowing the basics helps with maintenance and migration.
File-Based Routing 📁
pages/
├─ index.tsx → /
├─ about.tsx → /about
├─ blog/
│ ├─ index.tsx → /blog
│ └─ [slug].tsx → /blog/:slug
└─ 404.tsx → custom not-found page- Dynamic routes:
[id].tsx, catch-all:[...slug].tsx. - Each file exports a React component;
getStaticProps,getServerSideProps,getStaticPathscontrol data fetching.
Special Files 🧱
_app.tsx: wraps every page (global styles, providers)._document.tsx: customize<html>structure (meta tags, lang, fonts). Runs on server only._error.tsx: fallback error page.
API Routes 🍳
pages/api/hello.tsimport type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ message: 'Hello' });
}- Each file becomes
/api/...endpoint. - Runs on Node environment (not Edge unless using middleware).
Data Fetching Summary 🧪
| Method | When it runs | Use case |
|---|---|---|
getStaticProps | Build time (SSG) | Marketing pages, blogs |
getServerSideProps | Each request (SSR) | Personalization, auth |
getStaticPaths | Build time to pre-render dynamic routes | Blog posts list |
getInitialProps | Legacy universal data fetching | Avoid unless necessary |
Migration Mindset 🔄
- You can mix
pages/andapp/during gradual migrations. - Pages Router remains supported, but new features land in App Router first.
- Understand
_appand_documentto faithfully port providers/head logic intoapp/layout.tsx.
Analogy: think of the Pages Router as a trusty classic car—no fancy autopilot, but still reliable. Knowing how it works keeps legacy fleets running while you build the EV (App Router) future.
Last updated on