Next.js directory layout
Next.js offers flexibility in structuring your project, and the best structure depends on your specific application's needs. Here's an example of a well-organized Next.js directory layout using the app directory (recommended for new projects):
Code
my-app/
├── app/
│ ├── layout.tsx # Root layout for the entire application
│ ├── page.tsx # Root page of your application
│ ├── api/ # Server-side API routes
│ │ └── hello.ts
│ ├── components/ # Reusable UI components
│ │ ├── Button.tsx
│ │ └── Header.tsx
│ ├── dashboard/ # Nested route for the dashboard
│ │ ├── layout.tsx # Layout specific to the dashboard
│ │ ├── page.tsx # Dashboard page
│ │ └── settings/ # Nested route under dashboard
│ │ └── page.tsx
│ ├── about/ # Route for the About page
│ │ └── page.tsx
│ ├── styles/ # Global styles
│ │ └── globals.css
│ └── utils/ # Utility functions
│ └── formatDate.ts
├── public/ # Public assets like images, fonts, etc.
│ └── favicon.ico
├── next.config.js # Next.js configuration file
└── package.json # Project dependencies and scripts
Key points:
app directory: The
app
directory contains your routes, layouts, and other components related to routing.page.tsx: The
page.tsx
file defines the content of a specific route.layout.tsx: The
layout.tsx
file defines shared UI elements like headers, footers, and navigation, which are applied to multiple pages.Nested routes: Folders within the
app
directory create nested routes, allowing you to organize your application's structure logically.components directory: This directory houses your reusable UI components.
api directory: This directory is for server-side API routes.
public directory: Static assets like images, fonts, and other files that should be served directly by the browser are placed here.
utils directory: This directory is for utility functions that can be used across your application.