JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext
nextjs
junior
routing

How does file-based routing work in Next.js?

nextjs
routing
file-based
dynamic-routes
app-router
Quick Answer

Next.js uses a file-system based router where files and folders in the `app/` (or `pages/`) directory automatically become routes - `app/about/page.tsx` becomes `/about`.

Detailed Explanation

File-based Routing Basics:

Next.js has two routing systems:

  1. App Router (recommended) - Uses app/ directory with page.tsx files
  2. Pages Router (legacy) - Uses pages/ directory where each file is a route

App Router Conventions:

  • page.tsx - Makes a route publicly accessible
  • layout.tsx - Shared UI for a segment and its children
  • loading.tsx - Loading UI while content loads
  • error.tsx - Error UI for a segment
  • not-found.tsx - 404 UI

Route Types:

  • Static routes: app/about/page.tsx → /about
  • Dynamic routes: app/posts/[id]/page.tsx → /posts/123
  • Catch-all routes: app/docs/[...slug]/page.tsx → /docs/a/b/c
  • Optional catch-all: app/shop/[[...slug]]/page.tsx → /shop or /shop/a/b

Route Groups:

  • Folders in parentheses like (marketing) organize routes without affecting URL

Code Examples

App Router folder structure
app/
├── page.tsx              # / (home)
├── layout.tsx            # Root layout (wraps all pages)
├── about/
│   └── page.tsx          # /about
├── blog/
│   ├── page.tsx          # /blog (list)
│   └── [slug]/
│       └── page.tsx      # /blog/my-post (dynamic)
├── docs/
│   └── [...slug]/
│       └── page.tsx      # /docs/intro/getting-started (catch-all)
└── (marketing)/          # Route group (no URL segment)
    ├── pricing/
    │   └── page.tsx      # /pricing
    └── features/
        └── page.tsx      # /features

Resources

Next.js Routing Documentation

docs

Dynamic Routes

docs

Related Questions

How do you navigate between pages in Next.js?

junior
navigation

How do you create dynamic routes with static generation in Next.js?

mid
routing
Previous
What is Next.js and how does it differ from React?
Next
How do you navigate between pages in Next.js?