What is role of each file and names in Nextjs App Router?

When you first create a Next.js 14 project with the App Router, you might feel overwhelmed by the different files and directories. But don’t worry! This guide will walk you through each part of the structure so you can understand the purpose of every file and how to use it effectively. For this explanation, we’ll use the example of a Recipe Sharing App to make it relatable.

.
β”œβ”€β”€ .eslintrc.json                # ESLint configuration
β”œβ”€β”€ .gitignore                    # Git ignore rules
β”œβ”€β”€ next.config.js                # Next.js configuration
β”œβ”€β”€ package.json                  # Dependencies and scripts
β”œβ”€β”€ .prettierrc                   # Prettier configuration
β”œβ”€β”€ tsconfig.json                 # TypeScript configuration
β”œβ”€β”€ .env                          # Environment variables
β”œβ”€β”€ .env.local                    # Local environment variables
β”œβ”€β”€ public                        # Public assets (favicon, images, etc.)
β”‚   β”œβ”€β”€ favicon.ico               # Favicon file
β”‚   └── images                    # Images folder
β”œβ”€β”€ src                           # Main source directory
β”‚   β”œβ”€β”€ app                       # Next.js 14 App Router directory
β”‚   β”‚   β”œβ”€β”€ layout.tsx            # Global layout
β”‚   β”‚   β”œβ”€β”€ page.tsx              # Home page
β”‚   β”‚   β”œβ”€β”€ recipes               # Folder for recipes-related pages
β”‚   β”‚   β”‚   β”œβ”€β”€ page.tsx          # Recipes listing page (for /recipes route)
β”‚   β”‚   β”‚   β”œβ”€β”€ new               # Subfolder for creating a new recipe
β”‚   β”‚   β”‚   β”‚   └── page.tsx      # New recipe form (for /recipes/new route)
β”‚   β”‚   β”‚   └── [id]              # Dynamic route for individual recipe pages
β”‚   β”‚   β”‚       └── page.tsx      # Recipe details page (for /recipes/[id] route)
β”‚   β”‚   β”œβ”€β”€ dashboard             # Dashboard for managing recipes
β”‚   β”‚   β”‚   β”œβ”€β”€ layout.tsx        # Dashboard layout
β”‚   β”‚   β”‚   └── page.tsx          # Dashboard page (for /dashboard route)
β”‚   β”‚   β”œβ”€β”€ globals.css           # Global CSS file
β”‚   β”‚   β”œβ”€β”€ loading.tsx           # Loading state
β”‚   β”‚   β”œβ”€β”€ error.tsx             # Error page
β”‚   β”‚   β”œβ”€β”€ not-found.tsx         # 404 page
β”‚   β”‚   β”œβ”€β”€ global-error.tsx      # Global error handler
β”‚   β”‚   β”œβ”€β”€ sitemap.xml           # Sitemap for SEO
β”‚   β”‚   └── robots.txt            # Robots.txt for SEO
β”‚   β”œβ”€β”€ api                       # API routes
β”‚   β”‚   └── recipes.ts            # API route for handling recipe submissions
β”‚   β”œβ”€β”€ components                # Reusable components
β”‚   β”‚   └── RecipeCard.tsx        # RecipeCard component
β”‚   β”œβ”€β”€ fonts                     # Custom fonts
β”‚   β”‚   β”œβ”€β”€ GeistVF.woff          # Font file
β”‚   β”‚   └── GeistMonoVF.woff      # Font file
β”‚   └── styles                    # Component/module-specific styles
β”‚       β”œβ”€β”€ RecipeCard.module.css # Styles for RecipeCard component
β”‚       └── dashboard.scss        # SCSS file for dashboard
β”œβ”€β”€ middleware.ts                 # Middleware for handling requests
β”œβ”€β”€ README.md                     # Project README
└── tests                         # Tests folder
    └── RecipeCard.test.tsx       # Test for RecipeCard component

Root Configuration Files

At the root of your project, you’ll find some essential configuration files:

  1. package.json: This file keeps track of all the dependencies and scripts for your project. Think of it as the heart of your project, where all the tools and libraries your app needs are listed.
  2. .eslintrc.json: This file configures ESLint, which helps you write cleaner, error-free code. It's like having a smart code editor that points out mistakes and suggests improvements.
  3. .gitignore: This file tells Git which files or directories shouldn’t be tracked in version control, such as node_modules or .env.
  4. next.config.js: This is where you can tweak settings specific to your Next.js app. You might use this to enable image optimization or configure build options.
  5. .prettierrc: If you're using Prettier for code formatting, this file will help you maintain consistent code style across your project.

'src/' Directory

When you choose to organize your code in the src/ folder, it helps to keep your codebase neat. Everything related to your app lives in this folder, which makes scaling and navigating your project easier.

'app/' Directory

The app/ directory is where the magic of Next.js 14’s App Router happens. Here, you manage routing, layouts, pages, and error handling:

  • Global Layout (layout.tsx): This file defines the layout for your entire app. For our recipe app, you can use this to include a header with navigation links (like "Home", "Recipes", "About"), which will appear on every page.
  • Page Components (page.tsx): The main content of your pages goes here. If you're building a recipe app, your homepage (/) could be a list of featured recipes. Each page gets its own file, making routing simple.
  • Dynamic Routes ([slug].tsx): When you want to display a recipe based on its name (or ID), you can use dynamic routes. For example, the file [slug].tsx would map to a URL like /recipes/chocolate-cake.
  • Metadata Configuration (head.tsx, metadata.js): Use these files to manage the metadata for each page, such as setting the title and description. For instance, when users visit a recipe page, the title in their browser could read "Chocolate Cake Recipe - RecipeMaster".
  • Nested Layouts (dashboard/layout.tsx): If you need different layouts for different sections of your app (like a user dashboard), nested layouts come in handy.
  • Loading States (loading.tsx): This file allows you to show a loading indicator while a page is fetching data. Imagine showing a β€œLoading your recipe…” message while your app fetches details from the database.
  • Global Error Handling (global-error.tsx): If something goes wrong, like the server not responding, this file shows a global error message to the user, such as β€œOops, something went wrong.”
  • Error Pages (error.tsx, not-found.tsx): These handle errors or 404 pages. If someone tries to access a recipe that doesn't exist, you can use not-found.tsx to show a user-friendly message like "Recipe Not Found".

Middleware Configuration

The middleware.ts file allows you to control server-side actions such as authentication or request handling. For example, if you want to ensure only registered users can submit recipes, you can implement authentication middleware.

API Routes

The api/ directory is where you create API routes. If your recipe app has a backend that allows users to submit recipes, the API logic for saving the recipe can go in api/recipes.ts.

Styling and Asset Management

In Next.js, you have multiple ways to manage styles and assets:

  • Global CSS (globals.css): This file contains styles that apply to the whole app. You might set fonts, colors, and base styles for your recipe app here.
  • Module CSS (component.module.css): For component-specific styling, you can use CSS Modules. For example, if your "RecipeCard" component needs its own styles, you could create RecipeCard.module.css.
  • SASS/SCSS Files (.scss): If you're using SCSS for more advanced styling, you can easily include these files for managing variables and mixins.
  • Favicon Setup (favicon.ico): The small icon shown in the browser tab. You can customize this for your recipe app by adding your own logo.
  • Static Files (Images, Fonts): Add your static assets like images (for recipe photos) or fonts in the public/ directory for easy access.

SEO and Site Optimization

To improve your recipe app’s discoverability, Next.js provides built-in tools for SEO:

  • Sitemap (sitemap.xml): You can generate a sitemap to list all available routes in your app, helping search engines index your recipes better.
  • Robots.txt: Use this file to manage which parts of your app should be accessible by search engines. You might not want search engines to index your user dashboard, for example.

Server Components and Client Components

In Next.js 14, you can mix Server Components and Client Components. Server components fetch data on the server, improving performance. For example, if you fetch the list of recipes from a database, you can use a server component to render it. For interactive elements, like adding a recipe to favorites, you can use client components.

TypeScript Support

If you're using TypeScript, tsconfig.json is where you'll configure TypeScript options. Using TypeScript helps catch errors early and makes your code more predictable.

Environment Variables

The .env and .env.local files store sensitive information like API keys and database connection strings. For example, you could store your database URL in .env to keep it hidden from the public.

Testing with Jest/React Testing Library

If you're writing tests for your recipe app, you can use Jest and React Testing Library to ensure everything works as expected. This ensures your users can search, view, and submit recipes without any bugs.

Summary

In this guide, we've covered the entire project structure for a Next.js 14 App Router project, using the example of a recipe-sharing app. From the root configuration files to the app/ directory and beyond, each part of the project has a specific purpose that makes your app more scalable and maintainable. By understanding these files and how to use them, you’re now better equipped to build a functional, dynamic Next.js app!

Next.js
Clap here if you liked the blog