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
Key Folders and Files
-
app/:
- The core of your app, housing routes, layouts, and components.
- Each folder inside
app/
represents a route, and eachpage.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.
-
public/:
- Contains static assets like images, fonts, and other media files. Files in this folder are accessible via the root path (
/
).
- Contains static assets like images, fonts, and other media files. Files in this folder are accessible via the root path (
-
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.
-
next.config.js:
- The configuration file for Next.js, allowing you to customize features like Webpack and environment variables.
-
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
Key Additions
-
api/:
- Stores API route handlers (serverless functions). Each file in this folder represents a backend API endpoint (
/api/route
).
- Stores API route handlers (serverless functions). Each file in this folder represents a backend API endpoint (
-
dashboard/:
- Represents a nested route (
/dashboard
) with a custom layout and a profile sub-route (/dashboard/profile
).
- Represents a nested route (
-
blog/:
- Implements a blog section with a dynamic route (
/blog/[slug]
), which fetches individual blog posts using theslug
parameter.
- Implements a blog section with a dynamic route (
-
auth/:
- Authentication routes (
/auth/login
and/auth/register
).
- Authentication routes (
-
components/:
- Stores reusable UI components like headers, footers, buttons, etc., ensuring modularity and reusability across multiple routes.
-
utils/:
- Utility functions like
fetcher.ts
for API requests andconstants.ts
for app-wide constants.
- Utility functions like
-
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 aslug
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>;
}
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");
}
}
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
Additional Folders and Files
-
context/:
- Stores global state management using React Context API (e.g., authentication context).
-
hooks/:
- Contains custom React hooks that encapsulate reusable logic (e.g., useAuth).
-
services/:
- Contains service layers for handling API calls (e.g., apiService).
-
tests/:
- Stores unit tests to ensure component functionality remains intact during development.
Best Practices for Organizing Your Next.js App with the App Directory
Use Layouts for Reusable Content: Create layouts for sections like dashboards or blogs to keep your code DRY (Don’t Repeat Yourself).
Optimize Client and Server Components: Use Server Components by default for performance; only use Client Components when necessary.
Organize Code by Feature: Group related components, styles, and utilities by feature (e.g., blog, auth) rather than by file type.
Leverage Middleware for Authentication: Use middleware to handle authentication checks before rendering protected routes.
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:
- Next.js Documentation
- MDN Web Docs - Using Middleware
- Vercel Blog - Introducing Next.js 13
- CSS-Tricks - Understanding Next.js
- Smashing Magazine - Building Apps with Next.js
If you found this guide useful, please consider sharing it with others! 😊
Top comments (0)