DEV Community

Cover image for Mastering Next.js App Directory Structure (2024 Edition)
Vishal Yadav
Vishal Yadav

Posted on

Mastering Next.js App Directory Structure (2024 Edition)

Next.js introduced the App Directory as a replacement for the Pages Directory to streamline development and provide better server-side capabilities. The App Directory brings flexibility and encourages modular file organization, allowing developers to build scalable, well-organized projects effortlessly.

In this blog, we will cover:

  • The basic folder structure using the App Directory.
  • A detailed explanation of each folder and file.
  • Advanced folder structure for complex applications.
  • Best practices for organizing your Next.js app with the App Directory.

Basic Folder Structure Using the App Directory

After setting up a Next.js app using the latest version (create-next-app), here is the minimal structure you’ll see:

my-next-app/
├── app/
│   ├── layout.tsx
│   ├── page.tsx
│   ├── favicon.ico
├── public/
│   └── images/
│       └── logo.png
├── styles/
│   ├── globals.css
│   └── Home.module.css
├── next.config.js
├── package.json
├── tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Key Folders and Files

  1. app/:

    • The core of your app, housing routes, layouts, and components.
    • Each folder inside app/ represents a route, and each page.tsx file within a folder represents a page.
    • layout.tsx: Defines layout components that persist across multiple pages.
    • page.tsx: Renders the content of individual pages.
  2. public/:

    • Contains static assets like images, fonts, and other media files. Files in this folder are accessible via the root path (/).
  3. styles/:

    • Contains global styles and CSS modules for specific components or pages.
    • globals.css: Global CSS styles that affect the entire app.
    • Home.module.css: CSS module for styling specific components on the home page.
  4. next.config.js:

    • The configuration file for Next.js, allowing you to customize features like Webpack and environment variables.
  5. tsconfig.json:

    • TypeScript configuration file, required if you're using TypeScript in your project.

Enhanced Folder Structure for a Growing Project

As your project scales, you will likely need a more comprehensive structure to manage routes, APIs, and components efficiently. Here’s an enhanced folder structure using the App Directory:

my-next-app/
├── app/
│   ├── layout.tsx
│   ├── page.tsx
│   ├── favicon.ico
│   ├── api/
│   │   └── route.ts
│   ├── dashboard/
│   │   ├── layout.tsx
│   │   └── page.tsx
│   ├── profile/
│   │   └── page.tsx
│   ├── blog/
│   │   ├── layout.tsx
│   │   ├── page.tsx
│   │   └── [slug]/
│   │       └── page.tsx
│   ├── auth/
│       ├── login/
│       │    └── page.tsx
│       └── register/
│            └── page.tsx
├── components/
│    ├── Header.tsx
│    ├── Footer.tsx
│    └── Button.tsx
├── public/
│    └── images/
│        └── logo.png
├── styles/
│    ├── globals.css
│    └── Home.module.css
├── utils/
│    ├── fetcher.ts
│    └── constants.ts
├── middleware.ts
├── next.config.js
├── tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Key Additions

  1. api/:

    • Stores API route handlers (serverless functions). Each file in this folder represents a backend API endpoint (/api/route).
  2. dashboard/:

    • Represents a nested route (/dashboard) with a custom layout and a profile sub-route (/dashboard/profile).
  3. blog/:

    • Implements a blog section with a dynamic route (/blog/[slug]), which fetches individual blog posts using the slug parameter.
  4. auth/:

    • Authentication routes (/auth/login and /auth/register).
  5. components/:

    • Stores reusable UI components like headers, footers, buttons, etc., ensuring modularity and reusability across multiple routes.
  6. utils/:

    • Utility functions like fetcher.ts for API requests and constants.ts for app-wide constants.
  7. middleware.ts:

    • Middleware functions that run before certain routes are processed, useful for authentication or logging.

Explanation of Key Concepts in the App Directory

1. Route-based File Organization

Unlike the Pages Directory, where each file in the pages/ folder becomes a route, the App Directory organizes routes based on the folder structure. This allows for more flexibility and modularity.

  • app/dashboard/page.tsx: Maps to /dashboard.
  • app/dashboard/profile/page.tsx: Maps to /dashboard/profile.

2. Layouts

The layout.tsx file enables reusable layouts across multiple pages. For example, you can define a global layout in app/layout.tsx that wraps all pages, and a more specific layout for the dashboard in app/dashboard/layout.tsx.

Layouts are persistent, meaning components like headers and sidebars defined in layouts don’t get re-rendered when navigating between pages, improving performance.

3. Nested Routes

Nested routes are created using subfolders in the app/ directory. This allows for clear and organized routing. For instance:

  • app/blog/[slug]/page.tsx represents a dynamic blog post page with a slug parameter (/blog/my-post).

4. API Routes in the App Directory

Next.js API routes are now part of the app/api/ folder, where each file or folder becomes an API endpoint. For example:

  • app/api/route.ts becomes an API endpoint /api/.

5. Server and Client Components

By default, components in the App Directory are Server Components, meaning they are rendered on the server. If you need to use a component that interacts with the client (e.g., event listeners), you can define it as a Client Component by adding "use client"; at the top of the file.

// app/components/Button.tsx

"use client";

export default function Button() {
  return <button>Click Me</button>;
}
Enter fullscreen mode Exit fullscreen mode

6. Custom Middleware

Next.js supports middleware that runs before rendering specific pages. For example, you can use middleware for authentication or logging by placing the middleware.ts file in your project root.

// middleware.ts

import { NextResponse } from "next/server";

export function middleware(req) {
  const token = req.cookies.get("token");

  if (!token) {
    return NextResponse.redirect("/auth/login");
  }
}
Enter fullscreen mode Exit fullscreen mode

Advanced Folder Structure for Complex Applications

As your project scales further, you might need additional features such as advanced authentication, API service layers, and more testing capabilities. Here’s how an advanced folder structure could look:

my-next-app/
  app/
    api/
      - route.ts
    dashboard/
      - layout.tsx
      - page.tsx
      profile/
        - page.tsx
    blog/
      - layout.tsx
      - page.tsx
      [slug]/
        - page.tsx
    auth/
      - login/
        - page.tsx
      - register/
        - page.tsx
  components/
    - Header.tsx
    - Footer.tsx
    - UI/
      - Button.tsx
      - Input.tsx
  context/
    - AuthContext.tsx
  hooks/
    - useAuth.ts
  services/
    - apiService.ts
  utils/
    - fetcher.ts
    - constants.ts
  styles/
    - globals.css
  tests/
    - components/
  middleware.ts
  next.config.js
  tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Additional Folders and Files

  1. context/:

    • Stores global state management using React Context API (e.g., authentication context).
  2. hooks/:

    • Contains custom React hooks that encapsulate reusable logic (e.g., useAuth).
  3. services/:

    • Contains service layers for handling API calls (e.g., apiService).
  4. tests/:

    • Stores unit tests to ensure component functionality remains intact during development.

Best Practices for Organizing Your Next.js App with the App Directory

  1. Use Layouts for Reusable Content: Create layouts for sections like dashboards or blogs to keep your code DRY (Don’t Repeat Yourself).

  2. Optimize Client and Server Components: Use Server Components by default for performance; only use Client Components when necessary.

  3. Organize Code by Feature: Group related components, styles, and utilities by feature (e.g., blog, auth) rather than by file type.

  4. Leverage Middleware for Authentication: Use middleware to handle authentication checks before rendering protected routes.

  5. Document Your Structure: Maintain clear documentation of your folder structure to help team members understand how to navigate your codebase efficiently.


Conclusion

The introduction of the App Directory in Next.js marks a significant improvement in how developers structure their applications. By understanding its capabilities and best practices, you can build scalable high-performance applications that are easier to maintain and extend.

Embrace these new features to streamline your development process while enhancing user experience!


References:

  1. Next.js Documentation
  2. MDN Web Docs - Using Middleware
  3. Vercel Blog - Introducing Next.js 13
  4. CSS-Tricks - Understanding Next.js
  5. Smashing Magazine - Building Apps with Next.js

If you found this guide useful, please consider sharing it with others! 😊

Top comments (0)