Code Reference

Pages Router

Next.js · Reference cheat sheet

Pages Router

Next.js · Reference cheat sheet


📋 Overview

The Pages Router is the original Next.js routing model: each file under pages/ maps to a URL. Still supported and common in older codebases.

🔧 Core concepts

File / patternURL
pages/index.tsx/
pages/about.tsx/about
pages/blog/[id].tsx/blog/:id
pages/api/hello.ts/api/hello
pages/_app.tsxApp wrapper
pages/_document.tsxCustom HTML document
pages/404.tsxCustom 404
Data APIWhen it runs
getStaticPropsBuild time (SSG)
getStaticPathsBuild time paths for dynamic SSG
getServerSidePropsEvery request (SSR)

💡 Examples

Static page with props:

export async function getStaticProps() {
  return { props: { title: "Home" } };
}

export default function Home({ title }: { title: string }) {
  return <h1>{title}</h1>;
}

Dynamic SSR:

export async function getServerSideProps(ctx: { params: { id: string } }) {
  return { props: { id: ctx.params.id } };
}

API route:

// pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ ok: true });
}

⚠️ Pitfalls

  • Don't put secrets in getStaticProps props — they ship to the client HTML.
  • _document.tsx only runs on the server; no React context/hooks from _app there.
  • Prefer App Router for new projects unless you have a Pages-only constraint.

On this page