Next.js App Router: Your First Full-Stack App
When you create a Next.js project with the App Router, you are not just adding server-side rendering to React. You get a framework that decides, file by file, where your code runs: on the server during the request, at build time, or in the browser. That decision is the single most important idea in modern Next.js, because it determines how you fetch data, how much JavaScript ships to the client, and how your pages stay fast as the product grows.
By the end of this lesson you will understand the role of the app directory, why components are server-rendered by default, where 'use client' actually belongs, how nested layouts compose a page, and how the major file conventions map onto URLs.
Prerequisites
- !Basic React components and JSX
- !Understanding of HTTP requests and responses
- !Node.js installed locally with npm or pnpm
What You'll Learn
- 1Explain what the app directory provides over the old pages directory
- 2Decide correctly whether a component should be a Server or Client Component
- 3Compose nested layouts and pages into a complete route
- 4Map file names like page.js, layout.js, and route.js to URLs
What the app directory actually changes
Before the App Router, Next.js used a pages directory where every file automatically became a route, and every component rendered in the browser after hydration unless you reached for getServerSideProps. The App Router replaces that model with the Route Tree. Each folder under app represents a URL segment, and the files inside that folder have named roles: page.js renders the route's UI, layout.js wraps every child route, loading.js and error.js provide fallbacks, and route.js turns the segment into an API endpoint instead of a page.
The practical payoff is that data fetching and rendering happen inside Server Components by default. A page component can be an async function that awaits a database call directly. No API route, no client-side useEffect waterfall, no loading spinners wired by hand. The HTML is produced on the server with the data already in it, and the browser downloads markup instead of a bundle that has to re-fetch everything.
| File convention | Role in the Route Tree | Runs on |
|---|---|---|
page.js | UI for the segment's URL | Server (default) |
layout.js | Shared shell wrapping nested children | Server (default) |
loading.js | Suspense fallback for the segment | Server |
error.js | Error boundary for the segment | Client (must) |
route.js | API handler replacing a page | Server |
template.js | Like layout, but re-mounts on navigation | Server |
Server components are the default for a reason
A Server Component executes during the request on the server. Its import graph stays on the server, so database drivers, API secrets, and heavy dependencies never enter the client bundle. This is why a component like the following needs no special directive and no data-fetching library:
// app/products/page.js ā a Server Component by default
import { db } from '@/lib/db';
export default async function ProductsPage({ searchParams }) {
const category = searchParams.category ?? 'all';
const products = await db.product.findMany({
where: category === 'all' ? {} : { category },
take: 24,
});
return (
<main>
<h1>Products ({products.length})</h1>
<ul>
{products.map((p) => (
<li key={p.id}>
{p.name} ā {p.price}
</li>
))}
</ul>
</main>
);
}
The await inside the component body looks unusual if you come from classic React, but it is fully supported: Next.js streams the resolved UI to the browser. Two constraints matter. Server Components cannot use hooks such as useState or onClick handlers, because event handlers only exist in the browser. And they re-render on every request unless caching tells Next.js otherwise, which is a separate topic covered in the caching lesson.
Where 'use client' belongs
The 'use client' directive marks a boundary. Everything a client component imports, directly or transitively, is compiled for the browser; everything above the boundary stays on the server. The important habit is to push the boundary as low as possible. Do not mark a whole page interactive because one button needs state. Mark the button.
// app/counter/add-to-cart-button.js
'use client';
import { useState } from 'react';
export default function AddToCartButton({ productId }) {
const [quantity, setQuantity] = useState(1);
const [status, setStatus] = useState('idle');
async function addToCart() {
setStatus('pending');
await fetch('/api/cart', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, quantity }),
});
setStatus('added');
}
return (
<div>
<button onClick={() => setQuantity((q) => Math.max(1, q - 1))}>ā</button>
<span>{quantity}</span>
<button onClick={() => setQuantity((q) => q + 1)}>+</button>
<button onClick={addToCart} disabled={status === 'pending'}>
{status === 'added' ? 'Added' : 'Add to cart'}
</button>
</div>
);
}
Server Components can render Client Components and pass serializable props through them, so a page can stay mostly on the server while a leaf component handles clicks. What never works the other way around: a Client Component cannot import and render a Server Component as a child through a direct import. You pass them as children or fetch their data on the server side of the boundary.
Layouts compose the page shell
A layout.js receives children and renders the shared chrome ā navigation, sidebars, providers ā once for the whole segment. Child routes replace only the children slot during navigation, so navigation between sibling pages does not tear down the layout, refetch its data, or reset scroll. Nested folders nest layouts, and each level can be a Server Component wrapping Client Components for interactivity.
// app/(shop)/layout.js ā a route group layout
import Link from 'next/link';
import CartButton from './cart-button';
export default function ShopLayout({ children }) {
return (
<div className="shop-shell">
<header>
<Link href="/products">Catalog</Link>
<Link href="/orders">Orders</Link>
<CartButton />
</header>
<main>{children}</main>
<footer>Free shipping over 50 dollars</footer>
</div>
);
}
The (shop) folder name is a route group: it organizes files and applies a layout without adding a URL segment, so the layout above serves /products and /orders even though neither path contains "shop".
Rendering modes you get for free
Because rendering happens per route, you can mix strategies in one app. Static routes are rendered at build time and served from the edge cache. Dynamic routes read searchParams or cookies and render per request. Streaming works out of the box: when one part of a page awaits slowly, Next.js flushes the fast parts first and fills the rest in as promises resolve, using loading.js or explicit Suspense boundaries. Choosing a strategy per route ā rather than per application ā is one of the App Router's biggest operational advantages.
A realistic starting tree
A small but honest project structure looks like this, and almost every production app grows from these same primitives:
app/
layout.js # root layout, must render <html> and <body>
page.js # home route: /
globals.css
products/
layout.js # catalog sidebar shared by product routes
page.js # /products
[id]/page.js # /products/42
cart/
page.js # /cart
api/
cart/route.js # POST /api/cart
components/
add-to-cart-button.js
lib/
db.js
Two rules keep this tree healthy. The root layout must exist and render the document tags. And any folder that should not be routable ā shared code, helpers, tests ā lives outside app, typically in lib or components, because every folder inside app is part of the public URL surface.
Production pitfalls
Teams migrating from the pages directory make a predictable set of mistakes: marking entire pages 'use client' out of habit, fetching data in client components with useEffect when the page could await directly, and recreating API endpoints just to feed their own front end when a Server Component could call the database in-process. The mental reset is short: server-first by default, client only for state and events, and layouts for anything shared across sibling routes.
How a request flows through the framework
It is worth tracing one navigation end to end so the pieces stop feeling abstract. A user requests /products/42. Middleware, if you have any, runs first and may rewrite or redirect. Next.js then walks the route tree: the root layout wraps the products layout, which wraps the dynamic page for id forty-two. Because the page is a Server Component, Next.js renders it on the server ā awaiting any data calls, rendering child Server Components, and collecting the client components it encounters as separate references in the serialized payload. The response arrives as HTML plus the data needed to hydrate interactive parts. The browser paints quickly, downloads the JavaScript for the client boundary in the background, and from then on clicks inside interactive islands run locally while navigation between routes is handled by the client-side router, which asks the server only for the new segments it does not already hold.
That split ā HTML for structure and content, JavaScript only for interactivity ā is the performance story of the App Router in one paragraph. It also explains the debugging mindset: when content is wrong, look at what the server rendered; when a click does nothing, look at the client boundary.
Common Mistakes
Adding 'use client' to a page because it needs one interactive widget
Fix: Keep the page as a Server Component and move 'use client' down to the smallest interactive component, passing data as props.
Fetching page data in a client component with useEffect
Fix: Await the fetch directly in the Server Component page; the data arrives in the HTML with no client round-trip.
Expecting a layout to remount on every navigation
Fix: Layouts persist across navigations by design; use template.js when you genuinely need a fresh mount each time.
Putting helper files inside the app folder
Fix: Any folder inside app is routable; keep utilities in lib or components at the project root.
Best Practices
- Start every interactive island as the smallest possible component with its own 'use client' file
- Use route groups such as (marketing) and (shop) to apply different layouts without polluting URLs
- Keep secrets and database clients in server-only modules and never import them from client components
- Let loading.js provide skeletons for slow segments instead of hand-rolling spinners
Interview Questions
Q1: What does 'use client' actually do at build time?
It marks a module boundary: the directive file and everything it imports are assigned to the browser bundle and must be serializable across the server-client boundary, while modules imported only by Server Components remain server-only.
Q2: Can a Client Component directly import a Server Component?
No. Server Components can be children of Client Components only when passed through props such as children or a slot prop. A direct import would try to ship server-only code to the browser.
Q3: Why does the root layout have to render html and body?
Next.js owns the document shell at the root of the tree; nested layouts only fill the children slot, so exactly one file must produce the full HTML document.
Key Takeaways
- The app directory turns folders into a Route Tree where each file name has a fixed role: page, layout, loading, error, or route.
- Server Components are the default; they can await data directly and keep heavy dependencies out of the client bundle.
- 'use client' opens a boundary for state and event handlers ā place it as deep in the tree as possible.
- Layouts nest and persist across navigation, so shared chrome is fetched and rendered once per segment.
- Route groups, dynamic segments, and API route files give you structure without extra tooling.