Skip to article content
LESSON 07 / 28

Dynamic, parallel, and intercepted routes

Build routes that handle variable resources, nested fallbacks and modal navigation without breaking direct URLs.

What you will be able to do

  • Distinguish dynamic segments, catch-all segments and optional catch-all segments.
  • Explain parallel slots and intercepted navigation as composition rules.
  • Test missing resources and hard navigation as first-class cases.

Treat route parameters as an input contract

A folder such as catalog/[id] matches one path segment and makes that segment available as a parameter. A catch-all segment represents several segments; an optional catch-all also permits the route without those segments. These shapes are different types of input. Do not treat every route parameter as a string and hope the compiler or a fallback hides the mismatch. Await current App Router params and validate values before using them in a query.

A matching URL does not guarantee an existing record. /catalog/unknown can match the route while the product lookup returns nothing. That is a resource-level absence and should follow the intended not-found experience. A route that does not match any page is a different failure. Include both cases in tests, along with encoded or malformed values supported by your application contract. A folder name is routing structure, not authorization.

Server execution

app/catalog/[id]/page.tsx
import { notFound } from 'next/navigation';
const products = [
  { id: 'keyboard', title: 'Mechanical keyboard' },
  { id: 'monitor', title: 'Wide monitor' }
];
export default async function ProductPage({ params }: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params;
  const product = products.find(item => item.id === id);
  if (!product) notFound();
  return <main><h1>{product.title}</h1></main>;
}

Organize routes without inventing URLs

Route groups organize layout composition without adding their group label to the URL. Private folders can keep implementation detail outside the routing surface. This lets marketing and application sections use different shells while keeping clear public addresses. Be careful with multiple root layouts: crossing an actual root-document boundary has different navigation implications from changing a nested page.

Special files define fallback and recovery boundaries. loading represents pending content, error catches eligible failures below its boundary, and not-found represents missing resources. Their placement matters. A page-level error component cannot be assumed to catch a failure in its own enclosing layout. The errors lesson develops recovery in depth; here the key habit is to draw which subtree each boundary owns before deciding where files belong.

PAUSE AND PREDICT

The folder app/catalog/[id] exists. A request for /catalog/unknown matches it, but no such product is found. What should the implementation do?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Parallel routes compose independently changing panes

A parallel route slot lets a layout receive more than one routed subtree. Think of a dashboard with independent panes, each of which may have its own loading or error behavior. The slot name is not an ordinary URL segment. A refresh can lack the client navigation history that previously established an active subpage in a slot, so a default fallback is part of the route contract, not decorative boilerplate.

Use parallel routing when route-driven composition provides useful behavior. If two widgets merely load independent data inside one page, ordinary components and Suspense boundaries may be easier. The extra routing machinery creates more states to verify: matching paths, unmatched slots, loading, errors and hard refreshes. Explain that cost when discussing architecture instead of adding advanced routes solely to demonstrate familiarity with the feature.

A modal route needs a complete standalone route

An intercepted route can show a resource in a modal when reached from a particular navigation context while retaining the background page. Opening the resource directly or refreshing it should have a meaningful full-page representation. The URL belongs to the resource, not to a fragile sequence of previous clicks. Browser Back should restore the expected context, and close controls need deliberate history behavior.

Test opening from the catalogue, copying the URL into a fresh tab, reloading while the modal is open, moving between resources and pressing Back. Then test keyboard focus and dismissal. A modal that looks correct but traps focus after closing is incomplete. The kata below only practices dynamic-segment shape; the real project extension is where Next routing, history and accessibility must work together.

PAUSE AND PREDICT

A dashboard slot works after several client navigations but shows an unexpected fallback on refresh. Which issue should you investigate?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGERoute groups and parallel slot names become ordinary URL segments.
A more accurate model

They express composition and organization. Public path segments must be reasoned about separately from those conventions.

How to check it

N03 and the advanced-routing lesson distinguish route organization from matched URL segments.

CLAIM TO CHALLENGEA catch-all and optional catch-all have identical empty-path behavior.
A more accurate model

The required catch-all needs captured segments; the optional form permits their absence. Validate the resulting parameter shape.

How to check it

The dynamic-path exercise includes separate required-empty and optional-empty fixtures; N03 covers route parameter conventions.

Mistakes to catch in your own code

  • A dynamic route match is not proof that its resource exists.
  • Slot names and route-group names are not ordinary URL segments.
  • A modal route must work as a direct URL without prior navigation state.

Write it by hand

JavaScript logic playground

Match a dynamic path shape

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Implement solve({pattern,path}) for slash-separated paths. Patterns contain static segments, [name], a terminal [...name], or a terminal [[...name]]. Values are already decoded; ignore leading/trailing slashes.
  2. Return {matched:true,params} on a complete match, otherwise {matched:false,params:{}}. A single dynamic value is a string; a catch-all value is an array. Omit an optional catch-all key when it captures nothing.
  3. This deliberately small matcher does not implement Next routing precedence, route groups, encoding, slots or interception.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 5 test cases
  1. Single resource

    Input

    {
      "pattern": "/catalog/[id]",
      "path": "/catalog/keyboard"
    }

    Expected

    {
      "matched": true,
      "params": {
        "id": "keyboard"
      }
    }
  2. Required catch-all

    Input

    {
      "pattern": "/docs/[...parts]",
      "path": "/docs/react/state"
    }

    Expected

    {
      "matched": true,
      "params": {
        "parts": [
          "react",
          "state"
        ]
      }
    }
  3. Catch-all requires a value

    Input

    {
      "pattern": "/docs/[...parts]",
      "path": "/docs"
    }

    Expected

    {
      "matched": false,
      "params": {}
    }
  4. Optional catch-all may be absent

    Input

    {
      "pattern": "/docs/[[...parts]]",
      "path": "/docs/"
    }

    Expected

    {
      "matched": true,
      "params": {}
    }
  5. Complete match required

    Input

    {
      "pattern": "/catalog/[id]",
      "path": "/catalog/a/extra"
    }

    Expected

    {
      "matched": false,
      "params": {}
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const split = value => value.split('/').filter(Boolean);
  const pattern = split(input.pattern);
  const path = split(input.path);
  const params = {};
  let cursor = 0;
  const fail = () => ({ matched: false, params: {} });
  for (const part of pattern) {
    const optional = part.match(/^\[\[\.\.\.(.+)\]\]$/);
    const rest = part.match(/^\[\.\.\.(.+)\]$/);
    const dynamic = part.match(/^\[(.+)\]$/);
    if (optional || rest) {
      const values = path.slice(cursor);
      if (rest && values.length === 0) return fail();
      if (values.length) params[(optional || rest)[1]] = values;
      cursor = path.length;
    } else {
      if (cursor >= path.length) return fail();
      if (dynamic) params[dynamic[1]] = path[cursor];
      else if (part !== path[cursor]) return fail();
      cursor++;
    }
  }
  return cursor === path.length ? { matched: true, params } : fail();
}

The cursor proves whether every path segment was consumed, preventing a valid prefix from being mistaken for a complete match.

Real Next.js route behavior must be tested using actual files and navigation; this kata only isolates parameter-shape reasoning.

Verify it in a real Next.js application

Next.js application lab

Verify the shipped modal and standalone product routes

Open the local application route /catalog/keyboard after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Open /catalog?q=keyboard and activate Mechanical keyboard with the keyboard. The shipped @modal/(.)[id] route opens a native dialog while retaining the catalogue behind it.
  2. Use Escape, the close button and browser Back in separate runs. Inspect focus restoration and confirm that the visible URL follows the navigation.
  3. Copy /catalog/keyboard into a new tab and reload it. Inspect the standalone app/catalog/[id]/page.tsx route, then test an unknown product ID.
  4. Read @modal/default.tsx, @modal/page.tsx and the catch-all slot route. Explain the fallback for hard navigation and how an old modal is cleared. As an extension, add a second independently navigable slot and test its unmatched-route behavior.

Check the behavior

  • The product works as a standalone direct visit without a prior catalogue navigation.
  • Soft catalogue navigation shows the dialog, while reloading the product URL shows a full page.
  • Closing the modal leaves useful focus and correct history behavior; a missing product has an absence view.
  • If a second slot is added, hard navigation and unmatched state have an explicit fallback.
Review the application reasoning

Parallel and intercepted routes are already implemented in this project. The first task is to trace and verify their different entry paths; only the second slot is a new build assignment.

A route can render a not-found state after streaming has begun. Inspect both the UI and response timing before assuming every absence must have the same HTTP delivery.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01How do the three dynamic-segment forms differ?

    A single dynamic segment captures one value. A catch-all captures one or more segments as a list. An optional catch-all also permits no captured segments. I give the page the corresponding input shape, await current params and validate the values rather than using one untyped string conversion for every route.

    Follow-up questions

    • What should /docs match for an optional catch-all?
    • How would you validate a resource ID?
  2. 02Why can a matching route still return not found?

    The router can identify the page implementation before the data lookup establishes that the requested resource exists. A missing product should invoke the intended resource absence behavior. I test an unknown URL pattern separately from an unknown ID inside a valid pattern because they follow different paths.

    Follow-up questions

    • What should metadata do for a missing product?
    • How does streaming affect status-code reasoning?
  3. 03Why does a parallel slot need a default fallback?

    A hard visit may not provide enough route context to recover an active unmatched slot that existed during client navigation. A default defines what that pane should render in the fallback case. I verify both soft navigation and refresh instead of treating successful in-app clicks as sufficient coverage.

    Follow-up questions

    • Could ordinary Suspense solve the same UI need?
    • Which pane owns its error boundary?
  4. 04What should happen when an intercepted modal URL is refreshed?

    The resource needs a standalone route, so the fresh visit can render a complete page without the previous background context. The modal is a contextual navigation presentation. I test Back, close, direct entry and keyboard focus, because history and accessibility are part of the feature rather than optional polish.

    Follow-up questions

    • Should next/previous modal navigation push or replace?
    • Where does focus return after closing?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

A product opens in an intercepted modal from the catalogue. What should a shared direct URL to that product provide?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.