🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Dynamic Routes, Route Groups, and Interception

Next.js NavigationđŸŸĸ Free Lesson

Dynamic Routes, Route Groups, and Interception

The file system is Next.js's router table, and the bracket syntax is only the beginning. Once you move past one-param-per-page sites, the App Router offers catch-all segments for trees of unknown depth, route groups for organizing code without changing URLs, parallel slots for rendering independent panes in one layout, and intercepting routes that let a detail view appear as a modal while the list URL stays shareable. Each convention solves a problem that otherwise ends in a maze of hand-rolled query params and conditional layout code.

This lesson treats those conventions as design tools. You will learn how params arrive in pages and handlers, when a catch-all beats multiple dynamic segments, how parallel routes pass data through slot props, and how intercepting routes produce the read-then-modal pattern that news and commerce sites use everywhere.

Prerequisites

  • !Next.js intro lesson: pages, layouts, and the route tree
  • !Understanding of URL structure and query parameters
  • !Comfort with React props and children

What You'll Learn

  • 1Build dynamic and catch-all routes with correctly awaited params
  • 2Organize large apps with route groups and optional segments
  • 3Render parallel slots and pass data between them
  • 4Implement modal detail views with intercepting routes

Dynamic segments and how params arrive

A folder named with square brackets captures one URL segment. The resolved values are delivered to your page, layout, or route handler through the params object, which in current Next.js versions is a Promise — you await it before use. Generating static pages for known ids happens through generateStaticParams, and unknown ids fall back to dynamic rendering if the segment allows it.

// app/blog/[slug]/page.js
import { notFound } from 'next/navigation';
import { getPost, getAllSlugs } from '@/lib/posts';

export async function generateStaticParams() {
  const slugs = await getAllSlugs();
  return slugs.map((slug) => ({ slug }));
}

export default async function BlogPost({ params }) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();

  return (
    <article>
      <h1>{post.title}</h1>
      <time dateTime={post.publishedAt}>{post.formattedDate}</time>
      <div>{post.body}</div>
    </article>
  );
}

notFound() is not just an exception: it renders the nearest not-found.js with a 404 status, so search engines and monitoring see the truth instead of a soft 200. Pairing generateStaticParams with a sensible dynamicParams setting decides whether unknown ids render on demand or 404 immediately — a choice that protects databases from scraping bots on sites with millions of possible ids.

Catch-all and optional catch-all segments

Three dots capture the rest of the path as an array. This is the right tool for documentation trees, product catalogs with categories and subcategories, and anything where the depth is data, not structure. An optional catch-all with surrounding brackets also matches the bare prefix with an empty array.

// app/docs/[...path]/page.js
export default async function DocsPage({ params }) {
  const { path } = await params;
  // /docs/getting-started/install → path = ['getting-started', 'install']

  const doc = await getDocByPath(path);
  if (!doc) notFound();

  return (
    <DocsShell toc={doc.toc}>
      <h1>{doc.title}</h1>
      <article>{doc.content}</article>
    </DocsShell>
  );
}
ConventionFolder exampleMatchesParams shape
Staticpricing//pricingnone
Dynamic[id]//42id = '42'
Catch-all[...path]//a, /a/b, /a/b/cpath = array
Optional catch-all[[...path]]/also the parent itselfpath may be empty
Route group(marketing)/any, no URL changenone
Private folder_components/not routablenone

Route groups reorganize without rewriting URLs

Parenthesized folders exist so the file tree can match the organization chart even when the URL should not. The classic split is one group with a marketing layout for landing and pricing pages, and another with an app shell for the signed-in product — same domain, different chrome, zero URL churn during a redesign. Groups also let you place several pages with the same segment name under different layouts without collisions at the folder level.

Parallel routes: slots in one layout

A parallel route is a named slot the layout receives alongside children. Both slots render in the same pass, each with its own loading and error states, which is how dashboards show a main pane and a live sidebar without nesting two routers or lifting all state to the parent.

// app/(dashboard)/layout.js
export default function DashboardLayout({ children, analytics }) {
  return (
    <div className="grid gap-6 lg:grid-cols-[1fr_320px]">
      <section>{children}</section>
      <aside>{analytics}</aside>
    </div>
  );
}

// app/(dashboard)/@analytics/page.js
import { getLiveAnalytics } from '@/lib/analytics';

export default async function AnalyticsSlot() {
  const data = await getLiveAnalytics();
  return <AnalyticsPanel data={data} />;
}

The @analytics folder maps to the analytics prop. When a route does not define the slot, Next.js can render a fallback through default.js in the slot folder — important because a missing slot would otherwise break the layout's expectations when a user navigates to a page that does not supply it.

Interception: modal over the list

The pattern users love: clicking a result opens the detail in a modal, but copying the URL and reloading gives a full detail page. Intercepting routes make one route tree serve both. A sibling route with (..) captures navigation that would have gone to the full page, renders a modal layout, and the canonical URL stays intact for refresh and sharing.

// app/(feed)/photos/page.js — the grid
import { getPhotos } from '@/lib/photos';
import Link from 'next/link';

export default async function PhotosPage() {
  const photos = await getPhotos();
  return (
    <div className="grid grid-cols-3 gap-2">
      {photos.map((p) => (
        <Link key={p.id} href={`/photos/${p.id}`} className="block">
          <img src={p.thumbnail} alt={p.caption} />
        </Link>
      ))}
    </div>
  );
}

// app/(feed)/photos/@modal/(.)photos/[id]/page.js — the intercepted modal
import { getPhoto } from '@/lib/photos';

export default async function PhotoModal({ params }) {
  const { id } = await params;
  const photo = await getPhoto(id);
  return (
    <div className="fixed inset-0 bg-black/70 flex items-center justify-center">
      <div className="bg-white rounded-xl p-4 max-w-3xl">
        <img src={photo.url} alt={photo.caption} />
        <p>{photo.caption}</p>
      </div>
    </div>
  );
}

Navigation from within the feed matches the interception pattern and renders the modal slot. A hard reload does not come through the intercepted path, so the real photos/[id]/page.js renders as a full page. The mental model is: interception applies to soft navigations from matching segments, not to cold loads.

Route handlers share the same conventions

Dynamic folders are not page-only. A route.js inside [id] serves /api/items/42 with the same params semantics, so your REST surface mirrors your page tree. Keeping both under one folder also means a segment can be a page for the browser and an API for a mobile client without maintaining two parallel structures.

Production pitfalls

Teams hit three snags repeatedly. Parallel slots missing a default.js throw when a page omits the slot. Interception patterns silently fail because the path depth in (..) was counted wrong — each dot climbs one segment, and an off-by-one means the modal never matches. And catch-all routes collide with sibling static folders: /docs/pricing hits the catch-all instead of a hand-written pricing page depending on folder order, which is resolved by giving the static page its own folder outside the catch-all.

How Next.js resolves a URL to a file

When two folders could plausibly match the same path, resolution rules decide the winner, and knowing them prevents hours of confusion. Static segments take priority over dynamic ones, and dynamic segments take priority over catch-alls. An optional catch-all matches last of all. Route groups do not participate in matching at all — they are purely organizational, so two groups can contain pages for the same path only if you never define the same path twice, which the build will reject. Private folders prefixed with an underscore are excluded from routing entirely, which makes them the right home for colocated components and fixtures that would otherwise look like routes to a new teammate. A practical way to internalize the rules is to sketch the tree for a small e-commerce app: marketing group with landing and pricing, catalog with dynamic product segments, a catch-all for filtered category trees, and a dashboard group with parallel slots. Draw each URL you expect, trace the file it should hit, and you will have designed your router before writing a line of config — because in the App Router, the folder names are the config.

Common Mistakes

Forgetting params is async and reading .slug directly

Fix: Await params in pages, layouts, and route handlers; the property access on an unresolved Promise yields undefined.

Creating a parallel slot without a default.js fallback

Fix: Add default.js in the slot folder so layouts render cleanly when a page does not provide that slot.

Counting (..) segments incorrectly in intercepting routes

Fix: Each .. climbs one URL segment; draw the URL path and the folder path side by side before committing the pattern.

Letting a catch-all shadow an important static route

Fix: Give the static page its own folder at the same level; Next.js prefers more specific segments, but explicit folders prevent surprises.

Best Practices

  • Call notFound() for unknown params instead of rendering empty shells
  • Use generateStaticParams for enumerable ids so the build produces real HTML
  • Group routes by layout, not by type — marketing and app trees deserve separate shells
  • Test intercepting routes with both soft navigation and a hard refresh of the detail URL

Interview Questions

Q1: What is the difference between a catch-all and an optional catch-all segment?

A catch-all requires at least one segment, so it does not match the bare parent path. An optional catch-all also matches the parent, delivering an empty array for params.

Q2: How does a parallel route slot differ from a normal children prop?

Slots are named props resolved from @folder files; each can have its own loading and error boundaries and can be omitted, in which case default.js renders instead.

Q3: Why does an intercepted modal disappear on refresh?

Interception applies to client-side navigation matching the pattern. A cold request falls through to the real page route, which is exactly the desired shareable behavior.

Key Takeaways

  • Dynamic segments deliver params as a Promise; await them and call notFound() for misses.
  • Catch-all routes model trees of unknown depth, and optional catch-alls also match the empty path.
  • Route groups and private folders reorganize code without adding URL segments.
  • Parallel slots let one layout render independent panes with their own boundaries; provide default.js fallbacks.
  • Intercepting routes implement modal-over-list UX while keeping detail URLs refresh-safe.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement