Routing in Next.js (File-Based Routing)

In Next.js routing is based on the file system. The folder structure inside the app directory directly defines the application URLs. No separate router configuration is needed.

Basic Routing

Each folder in app is a URL segment. A page.tsx file makes that segment accessible:

FileURL
app/page.tsx/
app/docs/page.tsx/docs
app/problems/page.tsx/problems

Dynamic Routes

Square brackets are used for dynamic segments:

// app/docs/[slug]/page.tsx
export default async function DocPage({
  params
}: {
  params: { slug: string }
}) {
  const doc = await getDoc(params.slug)
  return <article>{doc.content}</article>
}

The URL /docs/what-is-nextjs passes { slug: 'what-is-nextjs' } to params.

Catch-All Routes

Use [...slug] to capture multiple segments:

// app/docs/[...slug]/page.tsx
export default function DocPage({
  params
}: {
  params: { slug: string[] }
}) {
  // /docs/next/ssg → slug = ['next', 'ssg']
  // /docs/react/hooks/useState → slug = ['react', 'hooks', 'useState']
  return <div>{params.slug.join(' / ')}</div>
}

The [[...slug]] variant (double brackets) also matches the root path without segments.

Route Groups

Parentheses allow grouping routes without affecting the URL:

(marketing) and (platform) do not appear in the URL. The /about page is at app/(marketing)/about/page.tsx. This allows using different layouts for different page groups.

Parallel Routes

Parallel routes let you render multiple pages simultaneously in one layout. Defined through slots with @:

// app/dashboard/layout.tsx
export default function DashboardLayout({
  children,
  stats,
  activity
}: {
  children: React.ReactNode
  stats: React.ReactNode
  activity: React.ReactNode
}) {
  return (
    <div>
      {children}
      <div className="grid grid-cols-2 gap-4">
        {stats}
        {activity}
      </div>
    </div>
  )
}

Each slot loads and streams independently.

Intercepting Routes

Allow intercepting navigation to show a route in a different context (for example, in a modal):

(.) — intercept at the same level
(..) — one level up
(..)(..) — two levels up
(...) — from the app root

Typical example: clicking a problem card on Hack Frontend opens a modal with a preview, while direct URL access shows the full page.

Special Files

FilePurpose
page.tsxPage UI
layout.tsxShared layout for a segment
loading.tsxLoading UI (Suspense fallback)
error.tsxError handling
not-found.tsx404 page
template.tsxLike layout but recreated on navigation
route.tsAPI endpoint (Route Handler)

Important:

A page.tsx file is required for a segment to be accessible as a page. A folder without page.tsx is only used for organization (colocation) and does not create a route.

Useful Resources