Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Next.js Documentation

The React framework for full websites — file-based routing, server rendering, API routes and SEO built in.

Next.js is a React framework for building full websites and apps. It adds what React alone doesn't have: file-based routing, server rendering (good for SEO and speed), API routes, image and font optimisation, and an easy path to deployment. These docs use the App Router (app/ folder), the default since Next.js 13.

1. Introduction & Setup

Requirements: Node.js 18.18+ (20 or 22 recommended).

npx create-next-app@latest my-app
# ✔ TypeScript? … No / Yes   ✔ ESLint? Yes   ✔ Tailwind CSS? Yes
# ✔ src/ directory? No       ✔ App Router? Yes  ✔ Turbopack? Yes
cd my-app
npm run dev

Output:

  ▲ Next.js 15.x
  - Local:        http://localhost:3000
 ✓ Ready in 1.2s

Project layout:

my-app/
├── app/
│   ├── layout.js        ← root layout (html, body) shared by every page
│   ├── page.js          ← the "/" page
│   └── globals.css
├── public/              ← static files served at "/" (images, favicon)
├── next.config.mjs
└── package.json
Script What it does
npm run dev development server with fast refresh
npm run build production build (also type-checks and lints)
npm start run the production build

Why Next.js instead of plain React (Vite)?

Plain React SPA Next.js
the browser downloads JS, then renders → empty HTML for crawlers HTML is rendered on the server → fast first paint, great SEO
you add a router, data fetching, a backend routing, data fetching and API routes built in
one rendering mode static, dynamic and streaming per route

⚠️ Common error: You're importing a component that needs useState. It only works in a Client Component — add "use client" at the top of that file (see section 4).

2. Routing with the App Router

Folders inside app/ become URL segments; a page.js file makes the segment public.

app/page.js                        →  /
app/about/page.js                  →  /about
app/blog/page.js                   →  /blog
app/blog/[slug]/page.js            →  /blog/hello-world   (dynamic)
app/shop/[...parts]/page.js        →  /shop/a/b/c         (catch-all)
app/(marketing)/pricing/page.js    →  /pricing            (group: folder name not in the URL)
// app/about/page.js
export default function AboutPage() {
  return <h1>About Codify</h1>;
}

Dynamic segments arrive in params (a Promise in Next.js 15):

// app/blog/[slug]/page.js
export default async function Post({ params }) {
  const { slug } = await params;
  return <h1>Post: {slug}</h1>;
}

Linking and navigation:

import Link from 'next/link';

<Link href="/blog/hello-world">Read post</Link>   // client-side navigation + prefetching
'use client';
import { useRouter, usePathname, useSearchParams } from 'next/navigation';

const router = useRouter();
router.push('/dashboard');      // navigate in code

Special files in a route folder:

File Purpose
page.js the UI of the route
layout.js shared wrapper that stays mounted between pages
loading.js shown instantly while the page loads (Suspense)
error.js error boundary for the segment (must be a Client Component)
not-found.js UI for notFound() / unknown routes
route.js an API endpoint instead of a page

3. Layouts & Metadata

// app/layout.js
import './globals.css';

export const metadata = {
  title: { default: 'Codify', template: '%s · Codify' },
  description: 'Learn to code with notes, practice and contests.',
};

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <nav>…</nav>
        <main>{children}</main>
      </body>
    </html>
  );
}

Nested layout for one section:

// app/dashboard/layout.js
export default function DashboardLayout({ children }) {
  return (
    <div className="grid grid-cols-[220px_1fr]">
      <aside>Sidebar</aside>
      <section>{children}</section>
    </div>
  );
}

Per-page metadata, including dynamic pages:

// app/blog/[slug]/page.js
export async function generateMetadata({ params }) {
  const { slug } = await params;
  const post = await getPost(slug);
  return { title: post.title, description: post.summary, openGraph: { images: [post.cover] } };
}

4. Server and Client Components

In the App Router every component is a Server Component by default: it runs on the server, can be async, can read the database or secrets directly, and sends no JavaScript to the browser.

Add 'use client' to make a Client Component when you need interactivity.

Need Component type
fetch data, use secrets, access the DB Server
keep big libraries off the client Server
useState, useEffect, event handlers (onClick) Client
browser APIs (localStorage, window) Client
// app/counter.js
'use client';
import { useState } from 'react';

export default function Counter() {
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + 1)}>Clicked {n} times</button>;
}
// app/page.js (Server Component)
import Counter from './counter';

export default async function Home() {
  const stats = await fetch('https://api.example.com/stats').then((r) => r.json());
  return (
    <>
      <p>{stats.users} learners</p>
      <Counter />          {/* a client "island" inside server-rendered HTML */}
    </>
  );
}

Rules:

  • A Server Component can render a Client Component, and pass it serialisable props (no functions).
  • A Client Component can't import a Server Component, but can receive one as children.
  • Put 'use client' as low in the tree as possible to keep bundles small.

⚠️ Common error: Event handlers cannot be passed to Client Component props — you passed a function from a Server Component. Move the handler into the Client Component.

5. Data Fetching & Caching

Fetch data directly in async Server Components:

// app/notes/page.js
async function getNotes() {
  const res = await fetch('https://api.codify.example/notes', { next: { revalidate: 3600 } });
  if (!res.ok) throw new Error('Failed to load notes');
  return res.json();
}

export default async function NotesPage() {
  const notes = await getNotes();
  return <ul>{notes.map((n) => <li key={n.slug}>{n.title}</li>)}</ul>;
}
Option Behaviour
fetch(url) (Next.js 15 default) not cached — fetched on every request
fetch(url, { cache: 'force-cache' }) cached until revalidated
fetch(url, { next: { revalidate: 60 } }) ISR: cached, refreshed at most every 60 s
fetch(url, { next: { tags: ['notes'] } }) cached; refresh with revalidateTag('notes')
export const dynamic = 'force-dynamic' render the route on every request
export const revalidate = 300 route-level revalidation

Run independent requests in parallel:

const [user, posts] = await Promise.all([getUser(id), getPosts(id)]);

Static generation for dynamic routes:

// app/blog/[slug]/page.js
export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((p) => ({ slug: p.slug }));   // pre-render these at build time
}

6. Rendering Strategies

Strategy When HTML is made Use for
SSG (static) at build time marketing pages, docs, blogs
ISR (incremental static) at build, then regenerated in the background product pages, content that changes hourly
SSR (dynamic) on every request dashboards, personalised pages, search results
CSR (client-side) in the browser highly interactive widgets
Streaming server sends parts as they're ready slow data — show the shell first

Streaming with Suspense:

import { Suspense } from 'react';

export default function Page() {
  return (
    <>
      <h1>Dashboard</h1>
      <Suspense fallback={<p>Loading stats…</p>}>
        <SlowStats />        {/* async component; streamed in when ready */}
      </Suspense>
    </>
  );
}

npm run build prints a legend: ○ static, ● SSG with params, ƒ dynamic.

7. Route Handlers (API Routes)

// app/api/notes/route.js
import { NextResponse } from 'next/server';

export async function GET(request) {
  const q = request.nextUrl.searchParams.get('q') ?? '';
  const notes = await db.note.findMany({ where: { title: { contains: q } } });
  return NextResponse.json(notes);
}

export async function POST(request) {
  const body = await request.json();
  if (!body.title) return NextResponse.json({ error: 'Title required' }, { status: 400 });
  const note = await db.note.create({ data: body });
  return NextResponse.json(note, { status: 201 });
}
// app/api/notes/[id]/route.js
export async function DELETE(_req, { params }) {
  const { id } = await params;
  await db.note.delete({ where: { id } });
  return new Response(null, { status: 204 });
}

Use route handlers for webhooks, public APIs and mobile clients. For your own forms, Server Actions are usually simpler.

8. Server Actions & Forms

A Server Action is an async function marked 'use server' that runs on the server but can be called from a form or a client component — no API route needed.

// app/notes/new/page.js
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';

async function createNote(formData) {
  'use server';
  const title = String(formData.get('title') || '').trim();
  if (!title) return;
  await db.note.create({ data: { title } });
  revalidatePath('/notes');          // refresh the cached list
  redirect('/notes');
}

export default function NewNote() {
  return (
    <form action={createNote}>
      <input name="title" placeholder="Note title" required />
      <button type="submit">Save</button>
    </form>
  );
}

Pending state and validation errors in a client form:

'use client';
import { useActionState } from 'react';
import { saveNote } from './actions';     // 'use server' file

export default function NoteForm() {
  const [state, action, pending] = useActionState(saveNote, { error: '' });
  return (
    <form action={action}>
      <input name="title" />
      {state.error && <p role="alert">{state.error}</p>}
      <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
    </form>
  );
}

⚠️ Server Actions are public endpoints — always check authentication and validate input inside them.

9. Images, Fonts, Styling & Environment Variables

import Image from 'next/image';

<Image src="/hero.png" alt="Students coding" width={1200} height={630} priority />

next/image resizes, lazy-loads and serves modern formats (WebP/AVIF) and prevents layout shift. Remote images need their host listed in next.config.mjs:

// next.config.mjs
export default {
  images: { remotePatterns: [{ protocol: 'https', hostname: 'res.cloudinary.com' }] },
};

Fonts are self-hosted automatically (no layout shift, no request to Google at runtime):

import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });

<body className={inter.className}>…</body>

Styling options: global CSS, CSS Modules (page.module.css), Tailwind CSS, Sass.

Environment variables (.env.local, never committed):

DATABASE_URL=postgres://…          # server only
NEXT_PUBLIC_SITE_URL=https://…     # exposed to the browser (prefix NEXT_PUBLIC_)

10. Middleware, Auth & Advanced Concepts

Middleware runs before a request reaches a route — redirects, auth checks, rewrites, headers.

// middleware.js (project root)
import { NextResponse } from 'next/server';

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

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

Read cookies and headers in Server Components:

import { cookies, headers } from 'next/headers';
const theme = (await cookies()).get('theme')?.value ?? 'dark';
  • Auth: Auth.js (NextAuth), Clerk, or your own JWT in an httpOnly cookie. Check the session in the page/action, not only in middleware.
  • Databases: Prisma or Drizzle (SQL), Mongoose (MongoDB) — create one client and reuse it.
  • SEO extras: app/sitemap.js, app/robots.js, opengraph-image.js generate files from code.
  • Parallel & intercepting routes (@modal, (.)photo) for modals with their own URL.
  • Deployment: Vercel (zero config), or output: 'standalone' in next.config.mjs for Docker/Node hosts; output: 'export' for a fully static site.

11. Examples with Output

Example 1 — Dynamic route

// app/hello/[name]/page.js
export default async function Hello({ params }) {
  const { name } = await params;
  return <h1>Hello, {decodeURIComponent(name)}!</h1>;
}

Visiting /hello/Asha renders:

Hello, Asha!

Example 2 — JSON API route

// app/api/time/route.js
export function GET() {
  return Response.json({ ok: true, year: new Date().getFullYear() });
}
curl http://localhost:3000/api/time
{"ok":true,"year":2026}

Example 3 — Build output

npm run build
Route (app)                Size     First Load JS
┌ ○ /                      1.2 kB   102 kB
├ ○ /about                 160 B    101 kB
├ ƒ /api/time              0 B      0 B
└ ● /blog/[slug]           420 B    103 kB
○ (Static)  ● (SSG)  ƒ (Dynamic)

12. Practice Problems

  1. Build a blog with app/blog/page.js (list) and app/blog/[slug]/page.js (post) from markdown files; pre-render all posts with generateStaticParams.
  2. Add loading.js and error.js to the blog and test them with a slow and a failing fetch.
  3. Create a notes app with Server Actions: add, delete and revalidatePath after each change.
  4. Add a /api/notes route handler with GET (search with ?q=) and POST (validation, 201/400 responses).
  5. Protect /dashboard with middleware that redirects to /login without a cookie.
  6. Make a theme toggle as a Client Component inside a Server Component layout.
  7. Add generateMetadata and an Open Graph image to each blog post; check the page source.
  8. Deploy to Vercel with an environment variable and a custom domain.

13. Interview Questions

1. What is Next.js and why use it over plain React? A React framework that adds file-based routing, server rendering (SSR/SSG/ISR), API routes and optimisations — better SEO, faster first load and a full-stack setup.

2. SSR vs SSG vs ISR? SSR renders on every request; SSG renders at build time; ISR serves static pages but regenerates them in the background after a revalidate interval.

3. What are Server Components? Components that run only on the server, can be async and access data directly, and ship no JavaScript to the browser. Client Components ('use client') handle interactivity.

4. App Router vs Pages Router? The App Router (app/) uses Server Components, nested layouts, streaming and Server Actions. The older Pages Router (pages/) uses getServerSideProps / getStaticProps.

5. What is hydration? React attaching event handlers to server-rendered HTML in the browser. A hydration mismatch happens when server and client render different output (e.g. using Date.now() or window during render).

6. What are Server Actions? Async server functions ('use server') callable from forms or client components to mutate data without writing API routes.

7. How does next/image help performance? Automatic resizing, modern formats, lazy loading and fixed dimensions that prevent layout shift.

8. What does middleware do? Runs before matched requests to redirect, rewrite, set headers or check auth.

9. How do you expose an environment variable to the browser? Prefix it with NEXT_PUBLIC_; others stay server-only.

10. How do you revalidate cached data? Time-based with revalidate, or on demand with revalidatePath() / revalidateTag() after a mutation.

14. Cheat Sheet & References

Create and run

npx create-next-app@latest my-app
npm run dev          # http://localhost:3000
npm run build        # production build
npm start            # serve the build

Routing files

app/page.js                 # /
app/about/page.js           # /about
app/blog/[slug]/page.js     # dynamic segment
app/(group)/x/page.js       # route group, not in URL
app/api/x/route.js          # API endpoint
layout.js loading.js error.js not-found.js

Components

'use client'                                  // make a Client Component
import Link from 'next/link'                  // <Link href="/x">
import Image from 'next/image'                // <Image src alt width height />
import { useRouter } from 'next/navigation'   // router.push('/x')
import { notFound, redirect } from 'next/navigation'

Data

await fetch(url, { cache: 'force-cache' })        // cache
await fetch(url, { next: { revalidate: 60 } })    // ISR
export const dynamic = 'force-dynamic'            // always SSR
export async function generateStaticParams() {}   // pre-render params
revalidatePath('/notes'); revalidateTag('notes')  // on-demand refresh

Server Actions and route handlers

async function save(formData) { 'use server' }    // <form action={save}>
export async function GET(req) { return Response.json({}) }
export async function POST(req) { const b = await req.json() }

Config and env

export const metadata = { title: 'Page' }          // SEO
NEXT_PUBLIC_API_URL=https://...                    // browser-visible env
images: { remotePatterns: [{ hostname: 'x.com' }] } // next.config.mjs

Official documentation