When stepping into the world of Next.js, the first two concepts you need to master are Directory Structure and Routing Mechanism. These are not just files and foldersβthey are the backbone, the blueprint that shapes your entire application. Understanding them is like an architect knowing the building plan before laying the first brick.
This article will help you master these two core concepts, from the traditional Pages Router
approach to the modern revolution called App Router
.
Why is Directory Structure so Important? ποΈ
In Next.js, the directory structure is not just a place to "throw" your code. It follows the philosophy of "Convention over Configuration". This means:
- File and folder names matter: How you name and organize files will automatically generate routes for your website.
- Predictable: Anyone familiar with Next.js can quickly understand the app's flow just by looking at the folder structure.
- Built-in features: Special files (like
layout.tsx
,page.tsx
,loading.tsx
) are automatically recognized by Next.js and given unique "superpowers".
Think of the directory structure as a contract between you and Next.js. You follow the conventions, and Next.js will handle the rest magically.
The Routing Revolution: App Router vs. Pages Router πΊοΈ
Next.js has evolved significantly with the introduction of the App Router (in the app
directory), replacing the traditional Pages Router (in the pages
directory). New projects should start with the App Router
, but understanding both is important for working on older projects.
1. App Router (Modern Approach - Recommended)
This is the future of Next.js, introduced in version 13 and now the default. It's more powerful, flexible, and built on React Server Components.
Special Files and Folders in app
The app
directory is the center of everything. Each subfolder inside app
corresponds to a segment in the URL.
app/layout.tsx
: REQUIRED file. This is the global "frame" for your entire app. It contains the<html>
and<body>
tags, and is a great place for headers, footers, sidebars, and providers (like Redux, Context API). All other pages are "nested" inside this layout.app/page.tsx
: This is your homepage, corresponding to the/
URL.app/dashboard/page.tsx
: This structure automatically creates a page at/dashboard
.app/blog/[slug]/page.tsx
: This is a Dynamic Route.[slug]
is a dynamic parameter, which can be any string. For example:/blog/first-post
,/blog/learn-nextjs-basics
. You can use theslug
value to fetch corresponding data.
App Router "Superpowers"
Besides page.tsx
, you can create special files in the same folder to automatically handle different UI states:
loading.tsx
: Shows a loading UI (e.g., spinner) while thepage.tsx
data is loading. Next.js will automatically display this file and replace it withpage.tsx
when loading is done.error.tsx
: A "safety net". If an error occurs during page rendering, this file's content will be shown instead of crashing the whole app.not-found.tsx
: Automatically displayed when a user visits a non-existent URL in that segment.template.tsx
: Similar tolayout.tsx
but does not preserve state between page transitions. Useful for page enter/exit animations.
Example of a complete App Router structure:
/app
βββ layout.tsx # Root layout for the entire app
βββ page.tsx # Homepage (/)
β
βββ /blog
β βββ page.tsx # Blog list page (/blog)
β βββ /[slug]
β β βββ page.tsx # Blog detail page (/blog/...)
β β βββ loading.tsx # Loading UI for blog detail
β
βββ /dashboard
β βββ layout.tsx # Separate layout for dashboard area
β βββ page.tsx # Dashboard main page (/dashboard)
β βββ /settings
β β βββ page.tsx # Settings page (/dashboard/settings)
2. Pages Router (Traditional Approach)
If you're working with an older Next.js project, you'll see the pages
directory. Its mechanism is simpler but less flexible.
Special Files and Folders in pages
pages/index.tsx
: Your homepage (/
).pages/about.tsx
: Automatically creates a page at/about
.pages/posts/[id].tsx
: A dynamic route. For example:/posts/123
.pages/_app.tsx
: This file wraps all other pages. It's where you add global layout, CSS, and state. Equivalent toapp/layout.tsx
.pages/_document.tsx
: Customize the root HTML structure (<html>
,<head>
,<body>
). Rarely needs editing.pages/api/
...: Any file in thepages/api
folder becomes an API endpoint, not a UI page. For example:pages/api/user.ts
creates the/api/user
endpoint. This is a powerful feature for building backend APIs right inside Next.js.
Routing in Practice: Basic Patterns π‘
Whether you use App Router or Pages Router, the core routing concepts are similar.
Static Routing
This is the most basic form. One file corresponds to a fixed URL.
app/contact/page.tsx
β/contact
pages/pricing.tsx
β/pricing
Dynamic Routing
When you need to generate pages from data, such as product detail or blog post pages.
- App Router:
app/products/[productId]/page.tsx
- Pages Router:
pages/products/[productId].tsx
Both will match URLs like /products/1
, /products/abc
, etc. You can access productId
from params in your component.
Nested Routing
Create subfolders for nested URLs.
app/dashboard/analytics/page.tsx
β/dashboard/analytics
pages/dashboard/analytics.tsx
β/dashboard/analytics
Navigating Between Pages
To navigate between pages, don't use regular <a>
tags as they reload the whole page. Instead, use Next.js's <Link>
component for super-smooth client-side navigation.
import Link from 'next/link'
function Navbar() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
<Link href="/blog/my-first-post">First Blog Post</Link>
</nav>
)
}
Other Important Folders π
Besides app
and pages
, a typical Next.js project also has:
/public
: Contains static assets like images, fonts,favicon.ico
. Anything here can be accessed directly from the root URL. For example:public/logo.png
is available atyourdomain.com/logo.png
./src
: An optional folder. Many prefer to putapp
(orpages
) and other code folders (like/components
,/lib
,/hooks
) inside/src
for better organization./components
: Where your reusable React components live (buttons, cards, forms, etc.)./lib
or/utils
: Contains utility functions and business logic reusable throughout the app.
Conclusion: Master Directory Structure and Routing
Mastering Directory Structure and Routing in Next.js not only helps you write code more efficiently but also unlocks the full power of the framework. Start with the App Router
for new projects, understand special files like layout
, page
, loading
, and use <Link>
for seamless user experiences.
When your project structure is clear and logical, developing, maintaining, and scaling your app in the future becomes much easier. Good luck on your Next.js journey!