Skip to the content

Lesson 176 of 296

What Next.js is; routing, layouts and dynamic routes

What you will learn

  • What a framework adds to React
  • The App Router and its special files
  • Pages, layouts and nested routes
  • Links and navigation
  • Dynamic routes and params
  • Route groups and not-found pages
On this page

What is Next.js?

React (Part 12) is a library for building UI. To build a full website you also need routing, a build setup, server rendering, data loading, API endpoints and SEO. Next.js is a framework built on React, made by Vercel, that provides all of these.

NeedReact aloneNext.js
Pages and URLsAdd a router libraryFolders become URLs
HTML on first loadBrowser downloads JS, then renders (empty page first)Server sends ready HTML
Data loadingFetch in effects or a libraryFetch directly in server components
API endpointsA separate back endRoute handlers and server actions
SEOHard: search engines may see an empty pageMetadata API, server-rendered HTML
Build toolingVite or similarBuilt in (Turbopack is the default bundler since Next.js 16)

Start a project: npx create-next-app@latest (TypeScript, Tailwind CSS, ESLint and the App Router are the defaults). Next.js 16 needs Node.js 20.9 or newer.

Two routers

Next.js has two routing systems:

  • App Router (the app folder), introduced in Next.js 13: the modern one, built on React Server Components. Use this for new projects.
  • Pages Router (the pages folder): the older one, still supported. You will meet it in older codebases (getServerSideProps, getStaticProps).

This part teaches the App Router.

Folders are routes

Inside app, each folder is a URL segment, and a folder becomes a public page when it contains a page.tsx file:

app/
  layout.tsx            → wraps every page
  page.tsx              → /
  about/
    page.tsx            → /about
  blog/
    page.tsx            → /blog
    [slug]/
      page.tsx          → /blog/any-post-name
  dashboard/
    layout.tsx          → wraps all /dashboard pages
    page.tsx            → /dashboard
    settings/
      page.tsx          → /dashboard/settings

A folder without page.tsx is not a route, so you can keep components and helpers next to the pages that use them (colocation).

Special files

FilePurpose
page.tsxThe UI of a route; makes the route public
layout.tsxShared UI that wraps pages and stays mounted between navigations
loading.tsxLoading UI while the page streams in (Lesson 180)
error.tsxError UI for the segment (Lesson 180)
not-found.tsxUI for "404 not found"
route.tsAn API endpoint (Lesson 181)
template.tsxLike a layout but re-mounts on every navigation (rarely needed)
default.tsxFallback for parallel routes (advanced)

Pages

A page is a React component exported as default:

TSX
export default function AboutPage() {
  return (
    <main>
      <h1>About JobPrep</h1>
      <p>A free course that takes you from zero to job-ready.</p>
    </main>
  );
}

Layouts

A layout wraps its pages (and child layouts) through children. The root layout (app/layout.tsx) is required and must contain <html> and <body>:

TSX
import type { ReactNode } from "react";
import Link from "next/link";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en-GB">
      <body>
        <header>
          <nav aria-label="Main">
            <Link href="/">Home</Link> <Link href="/lessons">Lessons</Link>
          </nav>
        </header>
        <main>{children}</main>
        <footer>© 2026 JobPrep</footer>
      </body>
    </html>
  );
}

Key facts:

  • Layouts nest: /dashboard/settings is wrapped by the root layout, then the dashboard layout.
  • When you navigate between pages that share a layout, the layout does not re-render or lose state. Only the page part changes. This makes navigation fast.
TSX
import Link from "next/link";

export function LessonNav({ prev, next }: { prev?: string; next?: string }) {
  return (
    <nav aria-label="Lesson navigation">
      {prev && <Link href={`/lessons/${prev}`}>Previous</Link>}
      {next && <Link href={`/lessons/${next}`}>Next</Link>}
    </nav>
  );
}
  • <Link> renders a normal <a> (good for accessibility and SEO), but navigates without a full page reload (client-side navigation).
  • Links visible on screen are prefetched in the background in production, so clicking feels instant.
  • To navigate from code (for example after a form), use useRouter() from next/navigation in a Client Component: router.push("/dashboard"). In server code, use redirect("/login") from next/navigation.

Dynamic routes

A folder name in square brackets is a dynamic segment. app/blog/[slug]/page.tsx matches /blog/hello, /blog/react-tips and so on.

The page receives params. In Next.js 15 and 16, params is a Promise, so you await it:

TSX
import { notFound } from "next/navigation";

type Post = { slug: string; title: string; body: string };

const POSTS: Post[] = [
  { slug: "hello", title: "Hello", body: "First post" },
  { slug: "react-tips", title: "React tips", body: "Keep state minimal" }
];

export default async function PostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = POSTS.find((p) => p.slug === slug);
  if (!post) notFound();
  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </article>
  );
}
  • notFound() stops rendering and shows the nearest not-found.tsx with a 404 status. TypeScript knows it never returns, so post is not undefined after it.
  • Next.js also generates a helper type: PageProps<"/blog/[slug]">, which types params for you.
FolderMatchesparams
[slug]/blog/a{ slug: "a" }
[...slug] (catch-all)/docs/a/b/c{ slug: ["a", "b", "c"] }
[[...slug]] (optional catch-all)/docs and /docs/a/b{ slug: undefined } or an array

Search params (the query string)

/products?sort=price&page=2. Pages receive searchParams, also a Promise:

TSX
export default async function ProductsPage({
  searchParams
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const { sort, page } = await searchParams;
  const sortBy = sort === "price" ? "price" : "name";
  const pageNumber = Math.max(1, Number(page) || 1);
  return <p>Sorted by {sortBy}, page {pageNumber}</p>;
}

Values come from the user, so validate them (Lesson 114). Using searchParams makes a page dynamic (rendered per request, Lesson 183). In Client Components, read them with the useSearchParams() hook.

Route groups and private folders

  • Route group (name): a folder in brackets organises routes without adding to the URL. app/(marketing)/about/page.tsx is still /about. Each group can have its own layout, for example (marketing) with a big header and (app) with a sidebar.
  • Private folder _name: excluded from routing completely, for helpers such as _components.

How to say it in an interview

"Next.js is a React framework that adds file-based routing, server rendering, data fetching, caching, API endpoints and SEO tools. In the App Router, folders are URL segments, page.tsx makes a route public and layout.tsx wraps pages and stays mounted between navigations. Dynamic segments like [slug] give params, which are a Promise in Next.js 15 and 16, and I call notFound() when the record does not exist. Link does client-side navigation with prefetching, and route groups organise folders without changing the URL."

Key words

WordMeaning
FrameworkA complete structure for building apps, built here on React
App RouterThe modern Next.js router, in the app folder
SegmentOne part of a URL path, one folder
LayoutShared UI that wraps pages and keeps its state
Dynamic routeA route with a variable part like [slug]
Route groupA (folder) that organises routes without changing the URL
PrefetchingLoading a linked page in the background before it is clicked

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.