Labs ICT
โญ Pro Login

File-Based Routing

File-Based Routing

One of Next.js's most intuitive features is file-based routing. Instead of configuring routes in a separate file, you create files in your project structure, and Next.js automatically creates routes for you.

This approach is elegant because your file structure mirrors your URL structure. When you look at your project, you can immediately understand how the application is organized.

How It Works

In the app directory, every file you create becomes a route. The file name determines the URL path.

Here's a simple example:

app/
โ”œโ”€โ”€ page.js          # Home page (about: /)
โ”œโ”€โ”€ about/
โ”‚   โ””โ”€โ”€ page.js      # About page (route: /about)
โ””โ”€โ”€ contact/
    โ””โ”€โ”€ page.js      # Contact page (route: /contact)

The page.js file name is special in Next.js. Only files named page.js are treated as pages. Other files in the directory are ignored for routing purposes.

Creating Pages

Let's create a simple about page. Create a new directory called about in your app directory, then create a page.js file inside it:

// app/about/page.js
export default function About() {
  return (
    <div>
      <h1>About Us</h1>
      <p>Welcome to our website!</p>
    </div>
  );
}

Now you can visit http://localhost:3000/about and see your new page. It's that simple!

Nested Routes

You can create nested routes by creating nested directories. For example, to create a route at /blog/first-post, you would create:

app/
โ””โ”€โ”€ blog/
    โ””โ”€โ”€ first-post/
        โ””โ”€โ”€ page.js

This structure gives you complete control over your URL hierarchy. You can nest as deep as you need to organize your content.

Next.js also supports route groups using parentheses. For example, (marketing) creates a group without affecting the URL. This is useful for organizing related routes.

Special Files

Next.js recognizes several special file names that serve different purposes:

page.js - Creates a route and makes it publicly accessible.

layout.js - Defines a layout that wraps child routes. This is perfect for shared UI elements.

loading.js - Shows a loading state while the page content loads.

error.js - Catches errors and displays a fallback UI.

These special files give you powerful tools for building robust applications with proper loading states and error handling.

๐Ÿงช Quick Quiz

What is file-based routing in Next.js?