Next.js Folder Structure, File Uses, and Errors – Complete Guide

Objectives: Next.js Folder Structure, File Uses, and Errors – Complete Guide

Next.js Folder Structure, File Uses, and Errors – Complete Guide

Next.js Folder Structure, File Uses, Real-life Examples and Common Errors

1. Introduction

Next.js uses an official folder structure to make projects organized, scalable, and SEO-friendly. Each folder has a special role, and placing files incorrectly may cause errors or unexpected behavior. Below we describe all main folders, file types, real-life examples, and what happens if files are misplaced.

2. Main Folders in Next.js (App Router)

  • app/ – Core folder for pages, layouts, and components.
  • public/ – Static files (images, videos, fonts) accessible by browser.
  • node_modules/ – Installed packages (do not edit manually).
  • prisma/ – Optional, for database schema (if using Prisma).
  • lib/ – Optional, utility files like database clients, helpers.
  • styles/ – Optional, global CSS or component-specific CSS.
  • package.json – Project dependencies and scripts.
  • next.config.js – Next.js configuration.

3. app/ Folder

This is the heart of a Next.js App Router project. It contains:

  • page.js – Represents a page. Automatically routed based on folder name. Example: app/about/page.js/about.
  • layout.js – Wraps pages, contains persistent UI like navigation or footer.
  • globals.css – Global styles applied to all pages.
  • components/ – Optional folder for reusable UI components.
  • api/ – Optional backend API routes. Example: app/api/users/route.js/api/users.
  • actions/ – Optional folder for server actions.

Real-life Example

Think of the app/ folder as the "restaurant building":

  • page.js → Tables with menus (pages the customers see)
  • layout.js → Restaurant interior design (navigation, footer)
  • components → Waiters and staff (reusable elements)
  • api/ → Kitchen (backend logic)
  • actions → Special chefs (server-side actions)

4. What Happens If Files Are Misplaced

  • Placing page.js outside app/ → page will not be recognized → 404 error.
  • Placing layout.js outside app/ → persistent layout won't work → page renders but without global layout.
  • Placing api route outside app/api → API route unavailable → 404 API error.
  • Placing components anywhere → allowed, but must import correctly.
  • Missing globals.css → no global styling applied, only default browser styles.
  • Importing layout.js incorrectly → build-time error.

5. public/ Folder

All static files like images, icons, fonts go here. Files can be accessed directly by URL. Example: public/logo.pnghttp://localhost:3000/logo.png

  • Placing a JS file here → will not run as module.
  • Placing image outside public → require import in React code.

Real-life Example

Think of public/ as a showcase window outside a store. Customers can see photos and signs directly.

6. lib/ Folder

Optional folder to store reusable logic, such as database clients, API helpers, etc.

  • Example: lib/prisma.js – Prisma client instance.
  • Can be used anywhere using import.
  • Placing in app/ is okay, but lib/ keeps project organized.

7. styles/ Folder

Optional folder for CSS or Sass files.

  • globals.css – imported in layout.js → affects all pages.
  • Component-specific CSS can also be placed here.
  • Real-life analogy → paint and decorations in restaurant.

8. prisma/ Folder

Contains schema.prisma for database models.

  • Placing schema outside prisma → Prisma CLI won't find → migration error.
  • Optional if not using database.
  • Real-life analogy → kitchen blueprint for data storage.

9. node_modules/

  • Stores all dependencies.
  • Do not edit manually.
  • Deleting folder → project won't run → must reinstall.

10. Common Errors and Causes

  • 404 page not found – Missing page.js or wrong folder.
  • Cannot find module – Wrong import path.
  • Server-side code running on client – Forgot 'use server' directive or using server-only modules in client component.
  • API route not found – Placed route.js outside app/api.
  • Globals.css not applied – Not imported in layout.js.
  • Image not showing – Placed outside public or wrong src.
  • Prisma errors – schema not in prisma folder, .env missing DATABASE_URL, migration not run.
  • Next.js build errors – Misplaced layout.js, page.js, or client/server component mismatch.
  • Hydration errors – Using browser-only code in server component without 'use client'.

11. Client vs Server Components

  • Server component – default → can fetch data, access database, secure.
  • Client component – add 'use client' → can use state, effects, browser APIs.
  • Placing client code in server component → error.
  • Placing server code in client component → runtime error.

12. Summary & Best Practices

  • Keep page.js inside folder → Next.js routing depends on it.
  • Keep layout.js at top-level inside folder → persistent layout works.
  • Use components anywhere but import correctly.
  • Static assets → public folder only.
  • Database → prisma folder recommended.
  • Always check 'use client' for components using state/browser APIs.
  • Misplacing files can break routing, API, or styling.
  • Next.js is forgiving for components, but page.js/layout.js/api must follow rules.

13. Real-life Restaurant Analogy (Full)

  • app/page.js → Table menus (pages customer sees)
  • app/layout.js → Restaurant interior and furniture (layout across all pages)
  • app/components → Waiters (reusable staff)
  • app/api → Kitchen (backend logic, server code)
  • app/actions → Chef specials (server actions, form submissions)
  • public/ → Storefront window (images, videos)
  • lib/ → Tools in kitchen (helpers, database clients)
  • prisma/ → Kitchen blueprint (database models)

Misplacing kitchen blueprint or menus causes chaos → errors!

Next.js app/ Folder – Full Guide with Files, Uses & Errors

Next.js app/ Folder – Full Guide

1. Introduction

The app/ folder is the core of a Next.js App Router project. Everything related to pages, layout, server actions, API routes, and components is typically inside this folder. Understanding it is essential for avoiding errors and building scalable apps.

2. Official app/ Folder Structure

app/
│
├── page.js           # Required for every page, defines UI for a route
├── layout.js         # Optional, wraps pages, common UI
├── globals.css       # Optional, global styles imported in layout.js
│
├── about/            # Example subfolder for "about" page
│   └── page.js       # about page content
│
├── components/       # Optional, reusable UI components
│   └── Navbar.js
│
├── api/              # Optional, backend API routes
│   └── users/
│       └── route.js
│
├── actions/          # Optional, server actions for forms
│   └── userActions.js

3. page.js

- Represents a route/page. - Required in every folder to make a valid page. - Can fetch data on server (default).

Example: app/page.js

export default function Home() {
  return <h1>Welcome to Next.js App Folder</h1>
}

What Happens if Misplaced

  • Outside app/ → Next.js cannot route → 404 error.
  • Missing page.js in subfolder → route unavailable → 404 error.

Real-life Analogy

page.js is like the table menu in a restaurant; each table (folder) must have a menu (page) for customers to see.

4. layout.js

- Wraps child pages. - Provides persistent UI (navbar, footer, global layout). - Optional but recommended for consistency.

Example: app/layout.js

import './globals.css'
import Navbar from './components/Navbar'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <Navbar />
        <main>{children}</main>
      </body>
    </html>
  )
}

What Happens if Misplaced

  • Outside app/ → layout not applied → page renders without common layout.
  • Multiple layout.js in same folder → Next.js uses closest parent layout → allowed.

Real-life Analogy

Layout.js is like the interior design of a restaurant: tables, chairs, and lighting remain consistent across rooms (pages).

5. globals.css

- Global styles for your application. - Imported in layout.js. - Optional but recommended for styling consistency.

Example

What Happens if Misplaced

  • Not imported → global styles not applied.
  • Placed outside app/ → must import with relative path.

Real-life Analogy

Globals.css is like the paint color and wallpaper of your restaurant; without it, the rooms look default and plain.

6. Subfolders for Pages

- Each folder in app/ can represent a route. - Must contain page.js for route to work.

Example: app/about/page.js

export default function About() {
  return <h1>About Next.js App Folder</h1>
}

What Happens if Misplaced

  • page.js missing → route unavailable → 404.
  • Folder without page.js → cannot navigate directly.

Real-life Analogy

Each folder is a room in the restaurant; page.js is the menu for that room.

7. components/ Folder

- Stores reusable UI components. - Can be imported anywhere in app/. - Optional, but keeps code DRY (Don't Repeat Yourself).

Example

export default function Navbar() {
  return <nav>Home | About</nav>
}

What Happens if Misplaced

  • Can place anywhere → must import with correct path.
  • Incorrect import path → build error.

Real-life Analogy

Components are like waiters and staff; reusable for multiple tables (pages).

8. api/ Folder

- Backend API routes. - Default route.js inside folder → server-only code. - Optional.

Example

// app/api/users/route.js
export async function GET() {
  return Response.json({ users: ['Alice', 'Bob'] })
}

What Happens if Misplaced

  • route.js outside api/ → Next.js cannot recognize → 404 API error.
  • API folder nested wrongly → route unavailable.

Real-life Analogy

Kitchen in a restaurant; only chefs (server) can work here. Customers cannot directly access kitchen.

9. actions/ Folder

- Optional folder for server actions, like form handling. - Must use 'use server' directive.

Example

'use server'
import prisma from '@/lib/prisma'

export async function createUser(formData) {
  await prisma.user.create({
    data: {
      name: formData.get('name')
    }
  })
}

What Happens if Misplaced

  • Placed outside app/ → can still work if imported, but convention broken.
  • Forgot 'use server' → runtime error in browser.

Real-life Analogy

Special chef preparing specific dishes upon request (forms/actions).

10. Client vs Server Components

  • Server component → default → can access DB, server-only APIs.
  • Client component → add 'use client' → can use state, useEffect, browser APIs.
  • Placing client code in server → build-time error.
  • Placing server-only code in client → runtime error.

11. Common Errors in app/ Folder

  • Missing page.js → 404 route.
  • Layout.js outside folder → layout not applied.
  • route.js outside api/ → API route 404.
  • Server code in client → hydration error.
  • Component import wrong → cannot find module.
  • globals.css missing → styling not applied.

12. Summary Table (app/ Folder)

File/FolderPurposeOptional?Real-life Analogy
page.jsDefine page routeNoTable menu
layout.jsPersistent layout for pagesYesRestaurant interior
globals.cssGlobal stylesYesPaint/wallpaper
components/Reusable UIYesWaiters/staff
api/Server API routesYesKitchen
actions/Server actions (form handlers)YesSpecial chef
subfolders (e.g., about/)Page routesYesRoom with its own menu

13. Best Practices

  • Keep page.js in every folder that represents a route.
  • Keep layout.js at top-level folder for persistent UI.
  • Use components folder to keep reusable code organized.
  • Always import globals.css in layout.js for consistent styling.
  • Server code → api/ or actions/ only.
  • Use 'use client' for browser-dependent components.

Reference Book: N/A

Author name: MWALA_LEARN Work email: biasharabora12@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::