Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment Β· evaluation Β· observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification Β· coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
πŸ€– AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
πŸ“± Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
βš™οΈ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
πŸ’Ύ Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
πŸ§ͺ Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

Β 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
Β© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Frontend
  4. Next.js
Guide to the React framework

β–² Next.js Complete Guide

Visitors

The full-stack framework built on React. App Router, server/client components, data caching, server actions, Route Handlers, middleware, metadata and SEO, streaming, and deployment β€” learn the standard of modern web development from end to end.

  • Intermediate
  • Updated Oct 1, 2026
  • ~7 min read
  • 15 sections
  • 14 code examples
  • Web IDE lab included
β–²

Next.js Web IDE

Run code in the browser with nothing to install and learn through step-by-step examples.

Open the Web IDE β†’
SSR/SSG full-stack appsApp RouterServer ActionsVercel/Cloudflare deployment

Related frameworks & environments

βš›οΈReactβ†’πŸ”·TypeScriptβ†’πŸŸ’Node.jsβ†’πŸ’‘Nuxtβ†’

Contents

0 / 18
  1. How to use this guide
  2. Architecture diagrams
  3. What is Next.js?
  4. App Router & file-based routing
  5. Server vs client components
  6. Data fetching & caching
  7. Server actions & forms
  8. Route Handlers (API)
  9. Middleware
  10. Metadata & SEO
  11. Loading/Error UI & streaming
  12. Image & font optimization
  13. Deployment (Vercel / Cloudflare)
  14. Next.js design
  15. Operating standards
  16. Verification strategy
  17. Frequently asked questions
  18. Next steps
Contents 18 sections
  1. How to use this guide
  2. Architecture diagrams
  3. What is Next.js?
  4. App Router & file-based routing
  5. Server vs client components
  6. Data fetching & caching
  7. Server actions & forms
  8. Route Handlers (API)
  9. Middleware
  10. Metadata & SEO
  11. Loading/Error UI & streaming
  12. Image & font optimization
  13. Deployment (Vercel / Cloudflare)
  14. Next.js design
  15. Operating standards
  16. Verification strategy
  17. Frequently asked questions
  18. Next steps

How to use this guide

How to read it

Understanding Next.js as a real-world workflow

The full-stack framework built on React. App Router, server/client components, data caching, server actions, Route Handlers, middleware, metadata and SEO, streaming, and deployment β€” learn the standard of modern web development from end to end. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.

Key perspective

Frontend / app development

Do not stop at drawing the screen: look at state, data requests, routing, accessibility, and the unit of deployment together.

SSR/SSG full-stack appsApp RouterServer ActionsVercel/Cloudflare deployment

Architecture diagrams

To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Next.js.

Learning flow

Rendering diagram…

Architecture view

Rendering diagram…

What is Next.js?

When you first open Next.js, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.

Next.js is a full-stack framework that bundles routing, rendering strategies, data fetching, and deployment on top of React. The key is that the rendering mode can be chosen differently per page and per component rather than for the whole app.
RenderingDescriptionWhen to use it
SSGStatic HTML generated at build timeContent that rarely changes
ISRStatic + periodic revalidationBlogs, product lists
SSRServer rendering on every requestPages personalized per user
CSRClient renderingInteractive dashboards

App Router & file-based routing

Here you look at App Router & file-based routing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

The folder structure of the app/ directory is the URL. Inside a folder, only page.tsx is exposed as an actual route, and the other files (layout, loading, error, and so on) are wired up automatically by convention.
TEXT
app/
β”œβ”€β”€ layout.tsx        # root layout
β”œβ”€β”€ page.tsx          # /
β”œβ”€β”€ blog/
β”‚   β”œβ”€β”€ page.tsx      # /blog
β”‚   └── [slug]/
β”‚       └── page.tsx  # /blog/:slug (dynamic segment)
β”œβ”€β”€ docs/
β”‚   └── [...slug]/
β”‚       └── page.tsx  # /docs/a/b/c (catch-all)
β”œβ”€β”€ (marketing)/      # route group β€” groups folders without affecting the URL
β”‚   └── about/page.tsx  # /about
└── api/
    └── users/
        └── route.ts  # /api/users
PatternMeaning
[id]Dynamic segment β€” accessed as params.id
[...slug]catch-all β€” matches several segments as an array
[[...slug]]optional catch-all β€” also matches the parent path itself
(marketing)route group β€” a folder group that does not appear in the URL path
@modalparallel route β€” renders several pages in the same layout at once
(.)photointercepting route β€” intercepts another route, for modals and the like

Server vs client components

Here you look at Server vs client components alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Server components are the default. Declare "use client" with the smallest possible scope, only on leaf components that need state, events, or browser APIs.
TSX
// Server component (default) β€” can access the DB directly
async function ProductList() {
    const products = await db.product.findMany({ take: 20 });
    return <ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>;
}

// Client component β€” when interaction is needed
'use client';
import { useState } from 'react';
export function Counter() {
    const [n, setN] = useState(0);
    return <button onClick={() => setN(n+1)}>{n}</button>;
}

Tip

  • The "use client" boundary propagates down the tree β€” declare it as close to the leaf nodes as possible
  • A server component is an async function that can await directly; a client component handles state only through hooks
  • When a server component is passed as children of a client component, that part is still rendered on the server

Data fetching & caching

Here you look at Data fetching & caching alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Next.js extends fetch to control caching declaratively. The default is static (cached indefinitely), and options select periodic revalidation or fully dynamic rendering.
TSX
// Default β€” cached indefinitely (behaves like SSG)
const res = await fetch('https://api.example.com/products');

// ISR β€” revalidated in the background every N seconds
const res2 = await fetch(url, { next: { revalidate: 60 } });

// Tag-based revalidation β€” selectively invalidate specific data only
const res3 = await fetch(url, { next: { tags: ['products'] } });
// later, in a server action and so on: revalidateTag('products');

// Fetch fresh on every request (SSR)
const res4 = await fetch(url, { cache: 'no-store' });

// Force dynamic rendering for the whole route
export const dynamic = 'force-dynamic';
OptionBehavior
(default, no option)Cached at build time, reused until revalidated
next: { revalidate: N }Revalidated in the background after N seconds (ISR)
next: { tags: [...] }Selectively invalidate specific caches with revalidateTag()
cache: 'no-store'Fetch fresh on every request (same as SSR)
export const dynamic = 'force-dynamic'Server-render the whole page on every request

Server actions & forms

Here you look at Server actions & forms alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

A server action is a server function that can be called directly from the client. It handles form submissions and mutations with no separate API route. Just add the `use server` directive and the function body runs on the server, and in a client component useActionState hands you the loading and error state of that function to reflect in the form UI, so no separate fetch or state management code is needed.
app/users/actions.tsTSX
'use server';
import { revalidatePath } from 'next/cache';
import { z } from 'zod';

const schema = z.object({ name: z.string().min(1, 'Enter a name') });

export async function createUser(prevState: { error?: string }, formData: FormData) {
  const parsed = schema.safeParse({ name: formData.get('name') });
  if (!parsed.success) {
    return { error: parsed.error.issues[0].message };
  }
  await db.user.create({ data: parsed.data });
  revalidatePath('/users');
  return { error: undefined };
}
app/users/UserForm.tsxTSX
'use client';
import { useActionState } from 'react';
import { createUser } from './actions';

export function UserForm() {
  const [state, formAction, isPending] = useActionState(createUser, {});
  return (
    <form action={formAction}>
      <input name="name" />
      {state.error && <p>{state.error}</p>}
      <button disabled={isPending}>Add</button>
    </form>
  );
}

Tip

  • Always validate again on the server inside a server action β€” client validation is for UX only and is not to be trusted
  • After a mutation, refresh the cache with revalidatePath/revalidateTag for it to show on screen

Route Handlers (API)

Here you look at Route Handlers (API) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Where server actions are for forms and mutations, a Route Handler is for REST APIs exposed externally and for receiving webhooks. Export a function per HTTP method in app/api/**/route.ts.
app/api/users/[id]/route.tsTYPESCRIPT
import { NextRequest, NextResponse } from 'next/server';

export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const user = await db.user.findUnique({ where: { id } });
  if (!user) return NextResponse.json({ error: 'not found' }, { status: 404 });
  return NextResponse.json(user);
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  await db.user.delete({ where: { id } });
  return new NextResponse(null, { status: 204 });
}
SituationChoice
Form submission/mutation within the same appServer Action
A REST API called by external clients (mobile apps and so on)Route Handler
Receiving webhooks (payments, GitHub, and so on)Route Handler
When a streaming response is needed outside server componentsRoute Handler

Middleware

Here you look at Middleware alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Middleware runs before a request reaches a route. Use it for authentication checks, redirects, rewrites, and header manipulation, and narrow its scope with a matcher.
middleware.tsTYPESCRIPT
import { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  const token = req.cookies.get('session')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/settings/:path*'],
};

Tip

  • Without a matcher it runs on every request, static assets included, which affects performance
  • Middleware runs on the Edge runtime, so Node.js-only APIs (fs and so on) cannot be used

Metadata & SEO

Here you look at Metadata & SEO alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Generate the title/description/OG tags per page dynamically with generateMetadata, and control search engine crawling with sitemap.ts and robots.ts.
app/blog/[slug]/page.tsxTSX
import type { Metadata } from 'next';

export async function generateMetadata(
  { params }: { params: Promise<{ slug: string }> }
): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPost(slug);
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: { title: post.title, images: [post.coverImage] },
  };
}
app/sitemap.tsTYPESCRIPT
export default async function sitemap() {
  const posts = await getAllPosts();
  return posts.map((p) => ({
    url: 'https://example.com/blog/' + p.slug,
    lastModified: p.updatedAt,
  }));
}

Loading/Error UI & streaming

Here you look at Loading/Error UI & streaming alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

loading.tsx, error.tsx, and not-found.tsx each replace a Suspense fallback, an Error Boundary, and 404 handling with a single file. Wrap only the data that is ready late in and the rest of the screen is streamed first.
TEXT
app/dashboard/
β”œβ”€β”€ layout.tsx
β”œβ”€β”€ page.tsx
β”œβ”€β”€ loading.tsx     # shown automatically while page.tsx gets ready
β”œβ”€β”€ error.tsx       # catches errors thrown below it (needs use client)
└── not-found.tsx   # shown when notFound() is called
app/dashboard/error.tsxTSX
'use client';

export default function Error({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div>
      <p>Something went wrong: {error.message}</p>
      <button onClick={() => reset()}>Try again</button>
    </div>
  );
}
app/dashboard/page.tsxTSX
import { Suspense } from 'react';

export default function Dashboard() {
  return (
    <>
      <Header />
      <Suspense fallback={<p>Loading stats...</p>}>
        <SlowStats />
      </Suspense>
    </>
  );
}

Image & font optimization

Here you look at Image & font optimization alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

next/image handles resizing, format conversion (WebP/AVIF), and lazy loading automatically, and next/font self-hosts fonts at build time to eliminate layout shift (CLS).
TSX
import Image from 'next/image';
import { Inter } from 'next/font/google';

const inter = Inter({ subsets: ['latin'], display: 'swap' });

export default function Hero() {
  return (
    <main className={inter.className}>
      <Image
        src="/hero.png"
        alt="Product introduction image"
        width={1200}
        height={600}
        priority // only for the LCP image
      />
    </main>
  );
}

Tip

  • Put priority only on the one image visible on the first screen (LCP) β€” overusing it actually slows things down
  • Images from external domains must be registered in images.remotePatterns in next.config.ts for optimization to apply

Deployment (Vercel / Cloudflare)

Here you look at Deployment (Vercel / Cloudflare) alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Vercel supports 100% of the App Router features with no extra configuration. On Cloudflare, deploy to Workers/Pages with the OpenNext adapter.
BASH
# Vercel
npm i -g vercel && vercel --prod

# Cloudflare Workers
npm install -D @opennextjs/cloudflare
npx opennextjs-cloudflare build
npx wrangler deploy
Deployment targetCharacteristics
VercelThe maker of Next.js; full support for every feature, including ISR, Edge, and image optimization
Cloudflare Workers/PagesDeployed with @opennextjs/cloudflare; low latency and low cost
Docker (self-hosted)Set output: 'standalone' in next.config.ts, then build a lightweight image

Next.js practical design

Next.js practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

The key in Next.js is designing the server/client boundary in the App Router. State where data is fetched and the cache policy explicitly per page.
Decision pointQuestion to askPractical guideline
BoundariesWhich parts of the Next.js code are most likely to change?Separate input/output, configuration, external integrations, and the core rules.
StateWhere is state created and where does it go away?Make the owner and lifecycle of state visible in the code.
FailureWhat does the caller receive on failure?Decide the timeout, fallback, and error contract first.

Next.js operating standards

This section covers Next.js operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.

Make ISR/revalidate, dynamic routes, edge/runtime differences, bundle splitting, and image optimization your operating standards.

Tip

  • server/client boundary
  • cache policy
  • metadata/canonical
  • hydration check

Next.js verification strategy

Next.js verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

Test route handlers, metadata, the sitemap, canonical URLs, and hydration mismatches.
Quality axisHow to verifyDefinition of done
CorrectnessAutomate the normal/failure cases.The core scenarios pass reproducibly.
Regression preventionWhen fixing a bug, leave the same case behind as a test.The same failure is not deployed again.
OperabilityCheck the logs, metrics, and alerts.There is a path for tracing the cause when a problem occurs.

Next.js: frequently asked questions

What is the difference between Next.js and React?

React is a library for building screens from components, and Next.js is a framework that adds routing, server rendering, build optimization, and API handling on top. What you would have to assemble yourself with React alone, Next.js provides in a defined way.

Should I use the App Router or the Pages Router?

For a new project, the App Router is recommended. Server components, nested layouts, and streaming are provided through the App Router. Existing projects on the Pages Router remain supported, so there is no rush to move, and the two can coexist in one project while you migrate gradually.

How do I decide between server components and client components?

A server component runs only on the server, can access databases and secrets directly, and sends no JavaScript to the browser. Parts that need state, event handlers, or browser APIs become client components by putting "use client" at the top of the file. Default to server components and split out only the small interactive parts as client components.

Next steps

This section covers Next steps from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.

πŸš€
Finished the Next.js fundamentals?

Hooks inside components, state management, form validation, and performance optimization are covered in more depth in the React guide. For a large codebase, add type safety with the TypeScript guide, and for automating the deployment pipeline see the CI/CD guide.

Related guides: React guide Β· TypeScript guide Β· CI/CD guide Β· Nuxt.js guide
← Previous guideReactNext guide β†’Vue