Next.js course Β· Module 1: Next.js Configuration
Directory and File Structure in Next.js (app/ vs pages/)
In this lesson9
In Quantum Metropolis, engineers design advanced transportation systems that can operate both on classic roads and on new quantum teleportation routes. Similarly, Next.js offers two parallel routing systems: the traditional Pages Router and the modern App Router. In this module, we will thoroughly analyze the differences between these two approaches and understand how to organize files and directories in our projects.
Two Routing Philosophies in Next.js
Next.js originally relied on file-based routing in the pages/ folder. In Next.js 13, a new routing system based on the app/ folder was introduced. This evolution resembles the transition from classic transportation systems to quantum teleportation in Quantum Metropolis - the new technology is more advanced, but both still coexist.
Pages Router: The Classic Approach
The Pages Router is the original routing system in Next.js. It is simple, well-documented, and still widely used. In this convention, every JavaScript or TypeScript file in the pages/ directory automatically becomes a route in the application.
pages/
βββ index.js # Route: /
βββ about.js # Route: /about
βββ contact.tsx # Route: /contact
βββ products/
β βββ index.js # Route: /products
β βββ [id].js # Route: /products/:id (dynamic)
βββ api/
βββ hello.js # API Endpoint: /api/helloIn this system:
- Files directly map to URL paths
- Dynamic path segments are marked with square brackets
[param] - A special
api/directory is used for handling API endpoints - Each file exports a React component or API handler function by default
App Router: The Modern Approach
The App Router, introduced in Next.js 13 and refined in version 15, represents a new approach based on React Server Components. It is like transitioning from traditional vehicles to quantum teleportation - a fundamental change in how we think about web applications.
app/
βββ layout.tsx # Main layout (required)
βββ page.tsx # Route: /
βββ about/
β βββ page.tsx # Route: /about
βββ blog/
β βββ page.tsx # Route: /blog
β βββ layout.tsx # Layout specific to /blog and its sub-routes
β βββ [slug]/
β βββ page.tsx # Route: /blog/:slug (dynamic)
βββ api/
βββ users/
βββ route.ts # API Endpoint: /api/usersIn the App Router:
- Only directories define routes, and special files within those directories serve specific functions
- The
page.tsxfile renders the page component for a given route - The
layout.tsxfile defines a shared layout for all pages in the directory and its subdirectories - Dynamic segments still use square brackets:
[param] - API endpoints are created using
route.tsfiles
File Naming and Conventions in App Router
The App Router introduces "convention over configuration" with a series of special files that have specific roles. This is like specialized modules in Quantum Metropolis systems - each with a defined function in the overall architecture.
Basic Special Files:
page.tsx: Renders the route's user interface and makes the path publicly accessible.
// app/dashboard/page.tsx export default function DashboardPage() { return ( <section> <h1>Quantum Metropolis Control Panel</h1> <p>Welcome to the command center!</p> </section> ); }layout.tsx: Defines a shared interface for a segment and its children.
// app/dashboard/layout.tsx export default function DashboardLayout({ children, }: { children: React.ReactNode; }) { return ( <div className="dashboard-layout"> <nav className="dashboard-sidebar"> {/* Sidebar navigation */} </nav> <main className="dashboard-main">{children}</main> </div> ); }route.ts: Creates an API endpoint using the new request handling API.
// app/api/status/route.ts import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json({ status: 'online', systemsOperational: 15, time: new Date().toISOString() }); } export async function POST(request: Request) { const data = await request.json(); // Processing data... return NextResponse.json({ success: true }); }loading.tsx: Creates a loading interface with React Suspense.
// app/dashboard/loading.tsx export default function DashboardLoading() { return ( <div className="dashboard-loading"> <div className="spinner"></div> <p>Loading Metropolis system data...</p> </div> ); }error.tsx: Creates an error handling interface with React Error Boundary.
'use client'; // Error handling components must be client components import { useEffect } from 'react'; export default function DashboardError({ error, reset, }: { error: Error; reset: () => void; }) { useEffect(() => { // Log error to monitoring system console.error(error); }, [error]); return ( <div className="error-container"> <h2>An error occurred in the Metropolis systems!</h2> <p>{error.message}</p> <button onClick={reset}>Try again</button> </div> ); }not-found.tsx: Creates an interface for a not-found resource (404).
// app/not-found.tsx export default function NotFound() { return ( <div className="not-found"> <h2>Unknown Zone</h2> <p>No Quantum Metropolis module was found with that identifier.</p> <a href="/">Return to command center</a> </div> ); }
Advanced App Router Features
The App Router introduces several advanced organizational features that resemble the advanced transportation systems in Quantum Metropolis - they allow for more complex and flexible routes.
1. Route Groups
Route groups allow organizing files without affecting the URL structure. They are marked by enclosing the directory name in parentheses: (group-name).
app/
βββ (marketing)/ # Route group (does not affect URL path)
β βββ about/
β β βββ page.tsx # Route: /about
β βββ contact/
β βββ page.tsx # Route: /contact
βββ (dashboard)/ # Another route group
βββ layout.tsx # Shared layout for dashboard routes
βββ page.tsx # Route: /
βββ stats/
βββ page.tsx # Route: /statsRoute groups are like districts in Quantum Metropolis - they help organize the city structure, but don't affect addresses.
2. Parallel Routes
Parallel routes allow simultaneous rendering of multiple pages in the same view, which is useful for complex layouts. They are marked by a slot name with the "@" sign: @slot-name.
app/
βββ layout.tsx # Main layout
βββ page.tsx # Main page
βββ dashboard/
βββ layout.tsx # Layout with multiple slots
β // layout.tsx defines slots {children, @stats, @notifications}
βββ page.tsx # Default content for the main slot
βββ @stats/
β βββ page.tsx # Content for the @stats slot
β βββ default.tsx # Required in Next.js 16 (e.g. returns null)
βββ @notifications/
βββ page.tsx # Content for the @notifications slot
βββ default.tsx # Required in Next.js 16 (e.g. returns null)In Next.js 16 every slot needs a default.tsx file (for example one that returns null or calls notFound()), otherwise next build fails.
// app/dashboard/layout.tsx
export default function DashboardLayout({
children,
stats,
notifications,
}: {
children: React.ReactNode;
stats: React.ReactNode;
notifications: React.ReactNode;
}) {
return (
<div className="dashboard-grid">
<main>{children}</main>
<aside className="stats-panel">{stats}</aside>
<section className="notifications-panel">{notifications}</section>
</div>
);
}Parallel routes are like parallel dimensions in Quantum Metropolis - different realities accessible simultaneously.
3. Intercepting Routes
These allow "intercepting" a route and displaying it differently, which is ideal for modals that preserve navigation context. They are marked by the segment name with the sign "(.)": (.)name, (..)name or (...)name.
app/
βββ layout.tsx
βββ page.tsx # Route: /
βββ dashboard/
βββ layout.tsx
βββ page.tsx # Route: /dashboard
βββ projects/
βββ layout.tsx # Renders {children} and {modal}
βββ page.tsx # Route: /dashboard/projects
βββ [id]/
β βββ page.tsx # Route: /dashboard/projects/:id
βββ create/
β βββ page.tsx # Route: /dashboard/projects/create (full page)
βββ @modal/
βββ default.tsx # Returns null when the modal is closed
βββ (.)create/
βββ page.tsx # Modal over the list when opened via a linkWhen you follow a link from the list, Next.js shows the intercepted page in the @modal slot over the list; after a refresh or when you open the address directly, it shows the full create/page.tsx page.
Intercepting routes are like quantum shortcuts in Quantum Metropolis - they allow quick access to resources without changing context.
Code Organization in Next.js 16
Besides the routing structure, Next.js 16 suggests specific ways of organizing code. This is like planning districts in Quantum Metropolis - proper organization increases efficiency and readability.
Shared Components and Resources
Components used in multiple places should be organized consistently. Here is the recommended structure:
src/
βββ app/ # Application with App Router
β βββ layout.tsx
β βββ page.tsx
βββ components/ # Shared components
β βββ ui/ # Basic UI components
β β βββ Button.tsx
β β βββ Card.tsx
β βββ features/ # Feature-specific components
β βββ dashboard/
β βββ auth/
βββ lib/ # Shared functions and classes
β βββ api/
β βββ utils/
βββ hooks/ # Custom React hooks
β βββ useAuth.ts
β βββ useLocalStorage.ts
βββ styles/ # Global styles
βββ globals.cssCo-location vs. Centralization
Next.js 16 and the App Router support a "co-location" approach, where files related to a specific route are placed close together. This is like micro-districts in Quantum Metropolis - everything you need is nearby.
app/
βββ dashboard/
βββ page.tsx
βββ loading.tsx # Loading for this route
βββ error.tsx # Error handling for this route
βββ layout.tsx # Layout for this route
βββ actions.ts # Server Actions for this route
βββ components/ # Components specific to this route
β βββ StatusCard.tsx
β βββ DashboardNav.tsx
βββ styles/ # Styles specific to this route
βββ dashboard.module.cssComparing App Router and Pages Router
Now that we've explored both routing systems, let's compare them - just as Quantum Metropolis engineers might compare classic transport with quantum teleportation.
Rendering
Pages Router:
- Every page is pre-rendered to HTML by default (automatic static optimization), then hydrated in the browser
- SSR and SSG available through getServerSideProps and getStaticProps
- Relatively simple data models
App Router:
- Server Components by default
- Choice between Server and Client Components
- More advanced data flow model
- Streaming rendering
In the Pages Router, a page gets its data from a function exported next to the component, e.g. getStaticProps, which Next.js calls once, during the build:
// pages/posts.js (Pages Router)
export async function getStaticProps() {
const posts = await getPosts();
return { props: { posts } };
}The getServerSideProps function has the same shape, but Next.js calls it on every request.
Loading State
Pages Router:
- Manual loading state management
- Often uses external libraries
App Router:
- Built-in loading.tsx components
- Integration with React Suspense
- Automatic loading indicators
Error Handling
Pages Router:
- Manual error management
- General component for 500 errors
App Router:
- error.tsx components with granular error handling
- Integration with React Error Boundary
- Ability to recover/retry after an error
Layouts
Pages Router:
- Manual layout creation with _app.js component
- One layout for the entire application
- Nested layouts require additional work
App Router:
- Built-in layout system through layout.tsx
- Ability to create nested layouts
- Layout sharing is simple and intuitive
When to Use Which Routing System?
Choosing between App Router and Pages Router resembles choosing between quantum teleportation and traditional transport in Quantum Metropolis - it depends on specific needs.
Use App Router when:
- You are creating a new project from scratch
- You want to use the latest React and Next.js features
- You need advanced layout and organization capabilities
- You care about better performance and streaming rendering
- You want to use React Server Components
Use Pages Router when:
- You have an existing project based on Pages Router
- You need a simpler mental model
- You use libraries that are not yet compatible with the App Router
- You want to use ready-made patterns and solutions
Migration from Pages Router to App Router
If you have an existing project using Pages Router, you can gradually migrate to App Router. This is like modernizing districts in Quantum Metropolis - you don't have to rebuild everything at once.
Next.js 16 allows both systems to coexist. You can start using app/ for new features while keeping existing pages in pages/.
.
βββ app/ # New features using App Router
β βββ new-feature/
β β βββ page.tsx # /new-feature
β βββ layout.tsx
βββ pages/ # Existing pages using Pages Router
βββ index.js # /
βββ about.js # /aboutImportant notes about migration:
- Routes in
app/take priority over routes inpages/, but the same URL cannot exist in both directories: Next.js reports an error during the build - Both structures use the same Next.js configuration
- You can gradually move pages from
pages/toapp/
Best Practices for File Organization
Regardless of the chosen routing system, it's worth following certain best practices:
Feature-oriented structure: Organize components and code around business features, not by technical types.
src/ βββ features/ β βββ auth/ β β βββ components/ β β βββ hooks/ β β βββ utils/ β βββ dashboard/ β βββ components/ β βββ hooks/ β βββ utils/Modular approach: Treat each feature as an isolated module with a clearly defined API.
Consistent naming conventions: Establish conventions and stick to them throughout the project.
- Component files: PascalCase (Button.tsx)
- Hooks: camelCase with "use" prefix (useAuth.ts)
- Helper functions: camelCase (formatDate.ts)
Relative vs. absolute imports: Use import aliases (
@/) for better readability and easier file moving.Test co-location: Place tests close to the tested components.
src/ βββ components/ β βββ Button.tsx β βββ Button.test.tsx
Summary
The directory and file structure in Next.js 16 is like the architecture of Quantum Metropolis - with proper planning, it can be both elegant and functional. The App Router introduces a more advanced but also more flexible application organization model, while the Pages Router offers a simpler and more direct approach.
The choice between them depends on the specific needs of the project, but for new projects, it is recommended to use the App Router to take advantage of the latest features and optimizations. Remember that good project organization is the key to easy maintenance and extensibility in the future.
In the next lesson, we will dive into the Next.js 16 component system, particularly the differences between Client Components and Server Components, which are a fundamental part of the App Router.
Code for this lesson: App.tsx
// Props and State - Metropolis Quantum
import React, { useState } from 'react';
console.log("Props and State in React");
console.log("Data management in Quantum City\n");
// ==========================================
// 1. PROPS - Passing Data
// ==========================================
console.log("=== 1. PROPS - Properties ===");
interface UserCardProps {
name: string;
role: string;
level: number;
avatar: string;
}
const UserCard: React.FC<UserCardProps> = ({ name, role, level, avatar }) => {
return (
<div style={{
background: 'rgba(255, 255, 255, 0.1)',
padding: '20px',
borderRadius: '12px',
border: '2px solid #64ffda',
display: 'flex',
alignItems: 'center',
gap: '15px',
marginBottom: '15px'
}}>
<div style={{ fontSize: '3rem' }}>{avatar}</div>
<div>
<h3 style={{ color: '#64ffda', margin: '0 0 5px 0' }}>{name}</h3>
<p style={{ margin: '5px 0', color: '#b0bec5' }}>Role: {role}</p>
<p style={{ margin: '5px 0', color: '#ff9800' }}>Level: {level}</p>
</div>
</div>
);
};
// ==========================================
// 2. STATE - Component State
// ==========================================
console.log("\n=== 2. STATE - useState Hook ===");
function QuantumCounter() {
// useState returns [value, function to change value]
const [energy, setEnergy] = useState<number>(50);
const [isCharging, setIsCharging] = useState<boolean>(false);
const charge = () => {
if (energy < 100) {
setEnergy(energy + 10);
setIsCharging(true);
setTimeout(() => setIsCharging(false), 300);
console.log(`Charging energy: ${energy + 10}%`);
}
};
const discharge = () => {
if (energy > 0) {
setEnergy(energy - 10);
console.log(`Discharging energy: ${energy - 10}%`);
}
};
const reset = () => {
setEnergy(50);
console.log("Energy reset to 50%");
};
const getEnergyColor = () => {
if (energy > 70) return '#4caf50';
if (energy > 30) return '#ff9800';
return '#f44336';
};
return (
<div style={{
background: 'rgba(124, 77, 255, 0.2)',
padding: '20px',
borderRadius: '12px',
border: '2px solid #7c4dff'
}}>
<h3 style={{ color: '#7c4dff' }}>Quantum Energy Generator</h3>
<div style={{
background: 'rgba(0, 0, 0, 0.5)',
padding: '15px',
borderRadius: '8px',
marginBottom: '15px'
}}>
<div style={{
fontSize: '2rem',
textAlign: 'center',
color: getEnergyColor(),
marginBottom: '10px'
}}>
{energy}%
</div>
<div style={{
width: '100%',
height: '20px',
background: 'rgba(255, 255, 255, 0.1)',
borderRadius: '10px',
overflow: 'hidden'
}}>
<div style={{
width: `${energy}%`,
height: '100%',
background: `linear-gradient(90deg, ${getEnergyColor()}, #64ffda)`,
transition: 'all 0.3s ease',
transform: isCharging ? 'scale(1.05)' : 'scale(1)'
}}></div>
</div>
</div>
<div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
<button
onClick={charge}
disabled={energy >= 100}
style={{
background: energy >= 100 ? '#555' : 'linear-gradient(45deg, #4caf50, #8bc34a)',
color: 'white',
border: 'none',
padding: '10px 20px',
borderRadius: '6px',
cursor: energy >= 100 ? 'not-allowed' : 'pointer',
fontWeight: 'bold'
}}
>
Charge
</button>
<button
onClick={discharge}
disabled={energy <= 0}
style={{
background: energy <= 0 ? '#555' : 'linear-gradient(45deg, #f44336, #e91e63)',
color: 'white',
border: 'none',
padding: '10px 20px',
borderRadius: '6px',
cursor: energy <= 0 ? 'not-allowed' : 'pointer',
fontWeight: 'bold'
}}
>
Discharge
</button>
<button
onClick={reset}
style={{
background: 'linear-gradient(45deg, #607d8b, #90a4ae)',
color: 'white',
border: 'none',
padding: '10px 20px',
borderRadius: '6px',
cursor: 'pointer',
fontWeight: 'bold'
}}
>
Reset
</button>
</div>
</div>
);
}
// ==========================================
// 3. Props + State Together
// ==========================================
console.log("\n=== 3. Props + State Combined ===");
interface SystemStatusProps {
systemName: string;
initialStatus: 'online' | 'offline' | 'maintenance';
}
const SystemStatus: React.FC<SystemStatusProps> = ({ systemName, initialStatus }) => {
const [status, setStatus] = useState(initialStatus);
const [uptime, setUptime] = useState(0);
const toggleStatus = () => {
const statuses: Array<'online' | 'offline' | 'maintenance'> = ['online', 'offline', 'maintenance'];
const currentIndex = statuses.indexOf(status);
const nextStatus = statuses[(currentIndex + 1) % statuses.length];
setStatus(nextStatus);
setUptime(0);
console.log(`${systemName} status changed to: ${nextStatus}`);
};
const getStatusColor = () => {
switch(status) {
case 'online': return '#4caf50';
case 'offline': return '#f44336';
case 'maintenance': return '#ff9800';
}
};
return (
<div style={{
background: 'rgba(255, 255, 255, 0.1)',
padding: '15px',
borderRadius: '10px',
border: `2px solid ${getStatusColor()}`,
marginBottom: '15px'
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<h4 style={{ margin: '0 0 10px 0', color: '#64ffda' }}>{systemName}</h4>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{
width: '12px',
height: '12px',
borderRadius: '50%',
background: getStatusColor(),
boxShadow: `0 0 10px ${getStatusColor()}`
}}></div>
<span style={{ color: getStatusColor(), textTransform: 'uppercase', fontWeight: 'bold' }}>
{status}
</span>
</div>
</div>
<button
onClick={toggleStatus}
style={{
background: 'linear-gradient(45deg, #2196f3, #21cbf3)',
color: 'white',
border: 'none',
padding: '8px 16px',
borderRadius: '6px',
cursor: 'pointer',
fontWeight: 'bold'
}}
>
Toggle Status
</button>
</div>
</div>
);
};
// ==========================================
// Main App
// ==========================================
function App() {
const citizens = [
{ name: 'Alex Quantum', role: 'Chief Architect', level: 42, avatar: '' },
{ name: 'Nova Star', role: 'Data Scientist', level: 38, avatar: '' },
{ name: 'Cypher Neo', role: 'Security Expert', level: 45, avatar: '' }
];
return (
<div style={{
padding: '20px',
background: 'linear-gradient(135deg, #0f0f23 0%, #1a1a2e 100%)',
minHeight: '100vh',
color: 'white'
}}>
<h1 style={{ textAlign: 'center', color: '#64ffda' }}>Metropolis Control Panel</h1>
<div style={{ marginTop: '30px' }}>
<h2 style={{ color: '#7c4dff' }}>Citizens (Props Demo)</h2>
{citizens.map((citizen, index) => (
<UserCard
key={index}
name={citizen.name}
role={citizen.role}
level={citizen.level}
avatar={citizen.avatar}
/>
))}
</div>
<div style={{ marginTop: '30px' }}>
<h2 style={{ color: '#7c4dff' }}>Energy System (State Demo)</h2>
<QuantumCounter />
</div>
<div style={{ marginTop: '30px' }}>
<h2 style={{ color: '#7c4dff' }}>Systems Status (Props + State)</h2>
<SystemStatus systemName="Quantum Core" initialStatus="online" />
<SystemStatus systemName="Neural Network" initialStatus="maintenance" />
<SystemStatus systemName="Transport Grid" initialStatus="offline" />
</div>
<div style={{
marginTop: '30px',
background: 'rgba(100, 255, 218, 0.1)',
padding: '20px',
borderRadius: '10px',
borderLeft: '4px solid #64ffda'
}}>
<h3>Props vs State:</h3>
<ul style={{ lineHeight: '1.8' }}>
<li><strong>Props</strong>: Passed from parent, read-only, like function parameters</li>
<li><strong>State</strong>: Internal component state, can be modified, re-renders component</li>
<li><strong>Props + State</strong>: Most commonly used together for dynamic UI</li>
</ul>
</div>
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does 'declarative programming' mean in the context of React?
2. React components can be:
Hands-on tasks in the game
- Horizontal ordering
Arrange the path to a dynamic post page in Next.js
- Code editor
Create the About page component for the file pages/about.js (export default function About). The page should display an <h1> or <h2> heading with the company name and a <p> paragraph with information about the company.