# The app directory vs. the pages directory
The key differences between the app directory (which uses the App Router) and the pages directory
(which uses the Pages Router) in Next.js. are:
Key differences
# Routing
- In the pagesdirectory, routing is based on file names (e.g.,pages/about.jscreates a/aboutroute) .
- The appdirectory uses folder-based routing. Each folder represents a route segment, and you create apage.jsfile inside the folder to make it publicly accessible .
# File Structure
- The appdirectory introduces new special files likelayout.js,loading.js, anderror.jsthat apply to specific route segments .
- For example, app/blog/layout.js (opens new window)
would apply to all routes under /blog.
# Layouts
- In the pagesdirectory, you'd use a custom_app.jsfile for global layouts.
- The appdirectory useslayout.jsfiles, which can be nested and composed, providing more flexible layouts per route segment .
# Data Fetching
- The pagesdirectory usesgetStaticProps,getServerSideProps, andgetStaticPathsfor data fetching.
- In the appdirectory, these are replaced with a new model where you can useasync/awaitdirectly in your components and a newgenerateStaticParamsfunction for static path generation.
# Server Components
- By default, components in the appdirectory are React Server Components, which render on the server, reducing the amount of JavaScript sent to the client .
- You can opt into client-side rendering by adding 'use client'at the top of a file.
# Metadata and SEO
- In the pagesdirectory, you'd typically usenext/headfor metadata.
- The appdirectory introduces a new Metadata API, allowing you to define metadata directly in your components or in alayout.jsfile .
# Loading UI:
The app directory introduces a new loading.js file for creating loading UI
with Suspense (opens new window) .
# Error Handling:
Instead of a global _error.js page, the app directory allows you to create error.js f
iles for more granular error handling.
# Route Handlers:
API routes in the pages directory (pages/api/*) are replaced with route.js
files in the app directory, offering more flexibility .
# Colocating Files
The app directory allows you to colocate your components, styles, tests, and other related files next to your routes.
This means we can organize related files together within the same directory structure, close to where they are used.
# Parallel Routes and Intercepting Routes:
These are new advanced routing features available only in the app directory .
# Incremental Adoption
The app directory and App Router represent a significant evolution in Next.js,
offering more powerful and flexible ways to build your application.
They're designed to work alongside the pages directory, allowing for incremental adoption .