logologo

Three-D

☕Sign in

    Recent Post:

    Categories:

    nextjsjavascriptthreejshonoreactjs
    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    A Guide to Next.js Folder Structure

    July 1, 2024

    547

    image

    Think you know it all?

    Take quiz!

    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:

    1. pages/ Directory

    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>
     );
    }

    2. public/ Directory

    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.

    3. styles/ Directory

    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;
    }

    4. components/ Directory

    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>
     );
    }

    5. api/ Directory

    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!' });
    }

    6. lib/ Directory

    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.