Recent Post:
Categories:
Next.js has a well-defined folder structure that simplifies the development process. Understanding and following this structure helps in maintaining a clean and organized codebase. Here's a detailed breakdown:
The pages directory is the heart of a Next.js project. Each file in this directory corresponds to a route in the application. For example, pages/index.js becomes the homepage.
code
// pages/index.js
export default function HomePage() {
return (
<div>
{' '}
<h1>Welcome to the Home Page</h1>{' '}
</div>
);
}
The public directory is used to serve static assets such as images, fonts, and other files. Files in this directory can be accessed directly with a URL.
This directory contains CSS files for styling your application. Next.js supports CSS Modules, Sass, and other styling options.
code
/* styles/global.css */
body
{
margin: 0;
font-family: Arial, sans - serif;
}
This directory is where you store reusable React components. Keeping components separate makes the code more modular and maintainable.
code
// components/Header.js
export default function Header() {
return (
<header>
{' '}
<h1>My Application</h1>{' '}
</header>
);
}
The api directory, located inside pages, is used for creating API routes. Each file in this directory maps to an API endpoint.
code
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello, world!' });
}
The lib directory is often used for utility functions and shared code that is not related to a specific component.
code
// lib/db.js
import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGO_URL);
export async function connectToDatabase() {
if (!client.isConnected()) await client.connect();
return client.db('mydatabase');
}
By following this folder structure, you can maintain a clean and scalable Next.js project. Each directory has a specific purpose, making it easier to locate files and understand the project's architecture.