File-Based Routing in Next.js

When working with Next.js, you don’t have to configure routes manually like in React Router. Instead, the file structure inside your pages folder automatically becomes your website routes. This is called file-based routing, and it’s one of the coolest features of Next.js. Let’s break it down step by step.

Vivek Rastogi

8/14/20252 min read

1. The Basics – pages/index.js becomes your homepage
  • In Next.js, you have a pages folder inside your project.

  • Any .js (or .tsx) file inside this folder automatically maps to a route.

Example:

pages/ index.js, about.js, contact.js

  • / → pages/index.js

  • /about → pages/about.js

  • /contact → pages/contact.js

So if you create a pages/index.js with:

When you open http://localhost:3000/ → you’ll see Welcome to my homepage!

2. Nested Routes – Making folder = URL path

What if you want something like /blog/first-post?
Just create folders inside pages!

Example:

  • /blog → pages/blog/index.js

  • /blog/first-post → pages/blog/first-post.js

pages/blog/index.js

export default function Blog() {

return <h1>All blog posts go here</h1>;

}

pages/blog/first-post.js:

Now open:

3. Dynamic Routes – Using [id].js

Sometimes you don’t know the page name in advance — like /blog/101 or /blog/hello-world.
Instead of creating separate files for each, you create a dynamic route file with square brackets:

Inside pages/blog/[id].js:

Now open:

The [id] acts like a placeholder parameter — very similar to :id in Express or React Router.

4. Catch-All Routes – Using [...slug].js

What if your URL can have any depth? For example:

  • /docs/getting-started/install

  • /docs/getting-started/configure

  • /docs/api/v1/endpoints

You don’t know how many segments there will be! In that case, you use a catch-all route with three dots inside the brackets:

pages/docs/....slug.js

Inside pages/docs/[...slug].js:

Now open:

The [...slug] file captures any number of path segments in an array.

Quick Recap
  • pages/index.js → / (homepage)

  • pages/about.js → /about

  • pages/blog/[id].js → /blog/anything (dynamic route)

  • pages/docs/[...slug].js → /docs/*/*/* (catch-all route)

No extra configuration needed. Next.js automatically figures out the routes from your file structure!