[Next.js Tutorial] Basic Directory Structure and Routing in Your Project

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.

Basic Directory Structure and Routing in Next.js

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".

Optimized folder structure for Next.js

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.

App Router vs. Pages Router

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 the slug 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 the page.tsx data is loading. Next.js will automatically display this file and replace it with page.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 to layout.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 to app/layout.tsx.
  • pages/_document.tsx: Customize the root HTML structure (<html>, <head>, <body>). Rarely needs editing.
  • pages/api/...: Any file in the pages/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.

Next.js Routing

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 at yourdomain.com/logo.png.
  • /src: An optional folder. Many prefer to put app (or pages) 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!

Related Posts

[Next.js Tutorial] Layouts: A Detailed Guide to Optimizing Your Website UI

Want to manage your Next.js website layout flexibly and efficiently? This article will guide you on using layouts to speed up development and improve user experience.

[Next.js Tutorial] The Complete Guide to Styling: Which Option is Best for You?

Step-by-step guide to styling in Next.js. This article covers best practices and performance tips to help you build beautiful and fast UIs.

[Next.js Tutorial] Navigation and Linking: How to Use for Optimal Performance

This article will help you master Navigation and Linking in Next.js with ease. Learn in detail how to use Next/link and useRouter for page navigation and optimize your app’s performance.

[Next.js Tutorial] What is Next.js? Why Should You Choose It in 2025?

Curious about Next.js? This article explains what Next.js is, why it matters for SEO and performance, and the outstanding benefits of using it.