Next.js Introduction
Next.js is a React framework that supplies the pieces every production site eventually rebuilds: routing, server-side rendering, data fetching, bundling, and deployment conventions. Using plain React with a bundler gets you a single-page application that ships all its JavaScript to the browser and shows a blank screen until it arrives. Next.js renders HTML on the server, streams it to the client, and hydrates only what needs interactivity.
The largest shift in recent versions is the App Router and server components. Components run on the server by default; opting into the client is a deliberate, visible decision. This lesson walks the mental model, the file-based routing conventions, layouts, dynamic data, and how it all deploys.
What the Framework Adds
A Create-React-App-style project ends where the hard parts begin. Next.js provides file-based routing so the directory tree is the route tree, multiple rendering strategies per page (static, server-rendered, streamed, client-side), automatic code splitting by route, image and font optimization, and an API layer for routes that need a backend. None of this requires configuration on day one ā conventions cover the defaults, and escape hatches cover the rest.
The App Router Mental Model
With the App Router, every route lives in the app directory. A page.js file makes a URL publicly routable; sibling files such as layout.js, loading.js, and error.js attach behaviors to that segment and everything beneath it.
app/
layout.js
page.js
products/
layout.js
page.js
[id]/
page.js
api/
health/
route.js
The root layout.js wraps every page and persists across navigation ā perfect for the html and body tags, global providers, and site chrome:
// app/layout.js
import Link from "next/link";
import "./globals.css";
export const metadata = {
title: "Northwind Catalog",
description: "Small-batch goods, shipped weekly.",
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<header className="site-header">
<Link href="/">Northwind</Link>
<nav>
<Link href="/products">Products</Link>
<Link href="/about">About</Link>
</nav>
</header>
<main>{children}</main>
<footer className="site-footer">
<p>Ā© 2026 Northwind Goods</p>
</footer>
</body>
</html>
);
}
Each segment's layout nests inside its parent automatically, so product pages render inside the root layout without any wrapping code.
Server Components by Default
In the App Router, components are server components unless they declare otherwise. They execute during the request (or at build time for static routes), can talk to your database and file system directly, and send zero JavaScript for themselves to the browser. A client component is one that needs the browser: event handlers, state, effects, hooks.
// app/products/page.js ā Server Component
import Link from "next/link";
const catalog = [
{ id: "linen-tote", name: "Linen Tote", price: 28 },
{ id: "enamel-mug", name: "Enamel Mug", price: 14 },
{ id: "wool-throw", name: "Wool Throw", price: 96 },
];
async function loadProducts() {
// In a real app: await db.product.findMany()
await new Promise((resolve) => setTimeout(resolve, 150));
return catalog;
}
export default async function ProductsPage() {
const products = await loadProducts();
return (
<section>
<h1>All products</h1>
<ul className="product-list">
{products.map((product) => (
<li key={product.id}>
<Link href={`/products/${product.id}`}>
{product.name} ā ā¬{product.price}
</Link>
</li>
))}
</ul>
</section>
);
}
Fetching data is just await ā no useEffect, no loading-state gymnastics, and Next.js streams the HTML as data resolves. When a component genuinely needs interactivity, add "use client" at the top of that file, and everything it imports becomes part of the client bundle too. Place the directive as deep in the tree as possible: a whole-page "use client" throws away the server-rendering benefit for every child.
| Concern | Server component | Client component |
|---|---|---|
| Runs where | Server (Node) | Browser, after hydration |
| Can use useState, useEffect | No | Yes |
| Can read the database directly | Yes | No ā call APIs |
| Ships JS to the browser | No | Yes |
| Typical role | Pages, data display, layouts | Buttons, forms, widgets |
Dynamic Segments and Params
Folders wrapped in square brackets capture URL parts. The page function receives them as a params promise ā awaiting it is part of the contract:
// app/products/[id]/page.js
export async function generateStaticParams() {
return [{ id: "linen-tote" }, { id: "enamel-mug" }, { id: "wool-throw" }];
}
export default async function ProductPage({ params }) {
const { id } = await params;
const product = await loadProduct(id);
if (!product) {
return <p>Product not found.</p>;
}
return (
<article>
<h1>{product.name}</h1>
<p>SKU: {id}</p>
<p>Price: ā¬{product.price}</p>
</article>
);
}
generateStaticParams tells the build which dynamic routes to pre-render; routes without it are rendered on demand. Nested dynamic segments compose freely (products/[id]/reviews/[reviewId]), and route groups in parentheses organize files without affecting URLs.
Loading and Error States Are Files
Two sibling conventions remove entire categories of boilerplate. loading.js wraps the segment in a Suspense boundary, showing a fallback while async pages resolve. error.js becomes the error boundary for the segment, catching render failures and offering a retry. Because they live next to page.js, they apply to exactly the right scope ā the segment and its children ā with no wrapper JSX anywhere.
Deployment and Environments
Next.js deploys anywhere Node runs: a managed platform such as Vercel, a container on any cloud, or a static export (output: "export") for fully static sites ā with the caveat that server components and dynamic routes need a server. Environment variables follow a simple rule: names without a prefix are server-only secrets; NEXT_PUBLIC_ exposes a value to the browser, so never prefix secrets with it. next build produces the production bundle; next start serves it.
Metadata and Static Assets
Alongside the file-based routes, every page can export a metadata object ā or generate one dynamically ā that fills the title, description, open-graph tags, and canonical URLs: the raw material search engines and social scrapers read. Because it is a plain export from a server component, the values can be assembled from data, so product pages derive their titles from the database without a third-party head library.
Static files belong in the public directory and are served verbatim at the site root ā favicons, robots.txt, and downloadable documents live there. Images passed through the framework's Image component instead gain automatic resizing, modern format negotiation, and lazy loading; the plain image element still works but opts out of all of that.
Route Handlers: The API Layer
Not every request should render a page. Files named route.js inside the app tree export handler functions ā GET, POST, PUT, DELETE ā and respond with standard Response objects. They share the same routing conventions as pages, so an endpoint under api/orders/[id]/route.js receives the same dynamic parameters a page would.
// app/api/orders/[id]/route.js
export async function GET(request, { params }) {
const { id } = await params;
const order = await findOrder(id);
if (!order) {
return Response.json({ error: "Order not found" }, { status: 404 });
}
return Response.json(order);
}
export async function POST(request) {
const body = await request.json();
const order = await createOrder(body);
return Response.json(order, { status: 201 });
}
Route handlers run in the Node runtime by default and can be switched to the edge runtime per file. Validation belongs at this boundary: parse the body, check authorization, then call into the same domain functions the server components use, keeping one source of truth for business logic no matter which layer received the request.
ā¹ļøWhen a plain React app is still the right call
The framework earns its weight on content-heavy sites, e-commerce, documentation, and dashboards that need fast first paint and search-engine visibility. A purely internal tool behind a login, with a handful of screens and no SEO stakes, may not need server rendering at all ā a bundled client-side React app deploys in minutes and avoids a server operations surface entirely. The decision hinge is simple: if strangers need to find your pages in search or open them on slow connections, the framework's server rendering pays for itself; if every user is authenticated and already on fast corporate wifi, weigh the complexity honestly before adopting it.
Common Mistakes
Adding 'use client' at the top of a whole page
Fix: Push the directive down to the leaf component that actually needs state or handlers.
Recreating fetch-in-useEffect patterns from client-side React
Fix: In server components, await data directly in the async component body.
Exposing secrets with NEXT_PUBLIC_
Fix: Only public configuration gets the prefix; API keys stay unprefixed on the server.
Reading params synchronously in App Router pages
Fix: Await the params promise ā it is async by design in the App Router.
Key Takeaways
- Next.js adds routing, rendering strategies, splitting, and deployment conventions on top of React.
- The app directory maps files to routes; page, layout, loading, and error files attach behaviors per segment.
- Components are server components by default ā 'use client' is a deliberate opt-in for interactivity.
- Server components await data directly; streaming replaces useEffect loading states.
- Dynamic folders in square brackets receive params as a promise to await.
- Layouts nest and persist across navigations; keep secrets unprefixed and public values NEXT_PUBLIC_.