v1.0 ยท MIT ยท Single HTML ยท Offline

Inside Next.js: From Source Code to Browser

A friendly, click-along story: how your code becomes a website kids (and grown-ups) can use.

๐Ÿ‘‹ Start here: Next.js is like a helper robot that reads your folders, builds your pages, sends them to the computer in the cloud, and makes buttons work in the browser. Tap each section โ€” we explain the hard words with simple pictures.

The 60-second version

Short on time? Here is the whole guide as a tweet-sized thread. Copy one, or copy all.

Post first tweet on X

The Big Picture

Ten steps from โ€œI wrote codeโ€ to โ€œThe page works when I click.โ€ Tap each step on the left.

๐Ÿ—บ๏ธLike a factory line: Your code rides on a conveyor belt. Each station does one job โ€” find pages, connect pieces, translate for computers, pack suitcases (bundles), and deliver to the browser.

Remember from this chapter

  • Next.js is a pipeline, not one magic box โ€” each step has a clear job.
  • Most data work stays on the server; the browser gets HTML first, JS only where needed.
  • Production output lives in .next after next build.

Route Discovery

Folder names on your computer become website addresses (URLs).

๐Ÿ“Like room labels: If you put a page in folder about, the website gets an /about door. Next.js walks your app/ folder like a librarian with a map.

File tree โ€” click a file

Generated route manifest


      

Route mapping

Folder names become URL segments. page.tsx marks a routable page. Dynamic segments use [param].

page.tsx

The actual screen for a URL

layout.tsx

Wrapper shared by pages in that folder

loading.tsx

Spinner while the page prepares

route groups (folder)

Organize files without changing the URL

Remember from this chapter

  • No central routes file โ€” the folder tree is the map.
  • Special filenames (layout, loading, error) add behavior around page.

Dependency Graph

Pages use pieces (components). Pieces can use smaller pieces. Thatโ€™s a โ€œwho needs whoโ€ map.

๐ŸงฉLike LEGO instructions: The big page is built from Header, Hero, and Dashboard blocks. Dashboard needs Chart and Table. Click a circle to light up everything it needs.
Selected Uses another piece

Dependencies

Click a module in the graph.

Remember from this chapter

  • Every import is an edge in the graph โ€” the bundler walks it from each page.
  • Shared imports become shared chunks; duplicate heavy deps inflate download size.

SWC Compiler

Browsers donโ€™t speak JSX. SWC translates your code super fast.

๐Ÿ—ฃ๏ธLike a translator: You write in JSX (mix of HTML-ish tags and JavaScript). SWC turns it into plain JavaScript the browser understands โ€” and shrinks it for the trip.

Compiler pipeline โ€” click to animate

Remember from this chapter

  • SWC replaces slower JS-based compilers for most Next.js transforms.
  • Dev = readable code; production = minified output in .next.

React Server Components

Some work happens on a big computer far away โ€” not in your pocket phone browser.

๐ŸซLike homework at school: The server (school) asks the database (library) for facts, builds the page, and sends you the finished poster. Your browser just hangs it on the wall.
๐Ÿ–ฅ๏ธ Browser
Gets the finished poster (HTML)
sends โ†’
๐Ÿซ Server
Cooks the page
๐Ÿ“š Database (library) sits behind the server โ€” only the server may visit
async function Page() {
  const posts = await db.posts.findMany()
  return <PostList posts={posts} />
}

๐Ÿซ Server Component

  • Cooks in the kitchen (server)
  • Can ask the library (database)
  • Doesnโ€™t add weight to your backpack (no extra JS)

๐ŸŽฎ Client Component

  • Runs on your device
  • Clicks, typing, animations
  • Ships JavaScript in the download

Remember from this chapter

  • Default in App Router: components are Server Components unless you say otherwise.
  • Server code can use secrets and databases; it never ships as source to the client.

Client Components

Interactive bits (clicks, typing) need JavaScript downloaded to the browser.

๐ŸŽฎLike a remote control: "use client" means โ€œthis part needs buttons that work on your device.โ€ More client parts = bigger download (heavier backpack).

Estimated bundle

0 KB

Toggle client components below

Remember from this chapter

  • Put "use client" only on components that need browser APIs, state, or effects.
  • Client boundaries pull in JavaScript cost โ€” keep them small and low in the tree when possible.

React Flight

The server sends recipe cards, not the whole kitchen.

โœˆ๏ธLike airplane snacks: Flight sends small numbered messages (โ€œput a Hero here, pass these propsโ€). The browser follows the recipe. Your secret server code never flies over.

Component tree

Page
โ”œ Hero
โ”œ Sidebar
โ”” Dashboard

Payload inspector

M1:{"id":"./Hero","chunks":["M2"]}
M2:["$","section",null,{"children":"..."}]

Remember from this chapter

  • Flight is Reactโ€™s wire format for Server Components โ€” a stream of instructions, not TSX source.
  • The client reconciler builds UI from Flight + existing client component modules.

Bundling

Pack JavaScript into suitcases (chunks) so visitors download only what they need.

๐ŸงณLike packing for trips: Shared clothes go in one bag (shared.js). Dashboard toys go in another. Turn pieces on/off and watch the suitcases change size.

Remember from this chapter

  • Code splitting = many small files instead of one giant download.
  • Shared UI (header/footer) should land in a shared chunk cached across routes.

Webpack vs Turbopack

When you change one file, how much does the tool rebuild?

๐Ÿ”„Like cleaning your room: Webpack sometimes cleans the whole room. Turbopack mostly tidies the one corner you touched โ€” so you wait less while coding.

Webpack

Often rebuilds the whole neighborhood

โ€” ms

Turbopack

Mostly rebuilds the one house you touched

โ€” ms

Simulated dev rebuild after editing one file. Real times vary by project size.

Remember from this chapter

  • Turbopack (dev) targets incremental rebuilds; Webpack remains common in production tooling history.
  • Fast feedback loops matter as much as production bundle size.

Build Output

After next build, Next.js leaves a .next folder โ€” the packed lunch for production.

๐Ÿ“ฆLike a lunchbox: Server food, static snacks, and a map (manifest) so the app knows where everything lives.
Select a folder or file

Remember from this chapter

  • Never edit .next by hand โ€” it is regenerated by next dev / next build.
  • Manifests tell the runtime where routes and assets live in production.

Request Lifecycle

What happens when someone visits your site โ€” step by step.

๐Ÿ“ฌLike sending a letter: Browser asks โ†’ maybe CDN helps โ†’ Next server thinks โ†’ database answers โ†’ HTML comes back โ†’ browser wakes up React (hydration).

Request flow

Click a node to see details.

Remember from this chapter

  • One page view can touch CDN, server, database, and client โ€” know which step you are debugging.
  • Streaming lets users see HTML before all data finishes loading.

Hydration Simulator

The page looks ready before buttons truly work.

๐Ÿ–ผ๏ธLike a picture of a button: First you see the button (HTML). Hydration is React plugging in the wires so clicks actually do something.

The button is only a picture right now โ€” try clicking it!

Status: SSR HTML only

Remember from this chapter

  • Hydration mismatch errors mean server HTML and client render disagree โ€” fix the diff, donโ€™t ignore warnings.
  • Only Client Components need hydration for interactivity.

Cache System

Remember answers so you donโ€™t ask the library the same question every second.

๐Ÿ˜Like an elephantโ€™s memory: First visit = slow (cache miss, go to database). Second visit = fast (cache hit, use saved answer).
Route Cache

Remembers whole pages that donโ€™t change often

Fetch Cache

Donโ€™t ask the same API twice in one cook session

Image Cache

Keeps resized photos ready nearby

ISR Cache

Old page stays fast while a fresh one bakes behind the scenes

Request 1 ยท MISS โ†’ database Request 2 ยท HIT โ†’ memory

Remember from this chapter

  • Caching is a tradeoff: speed vs freshness โ€” configure revalidate and fetch options on purpose.
  • โ€œStale dataโ€ bugs often mean cache rules, not React bugs.

Build Your Own Next.js

Next.js is really six jobs. Match each job to its slot.

๐Ÿ—๏ธLike building with blocks: Routing = signs, Compiler = translator, Bundler = suitcases, Runtime = worker, Renderer = artist, Cache = memory.

Suggested stack
HonoReactSWCRspackRedis

Remember from this chapter

  • Frameworks combine routing, compile, bundle, run, render, and cache โ€” Next.js packages opinions for React apps.
  • You could swap pieces (e.g. different bundler) but you inherit integration cost.

Final Summary

You made it! Hereโ€™s the whole story in one breath.

โญRemember: Folders โ†’ map โ†’ connect pieces โ†’ translate โ†’ server builds โ†’ send recipes โ†’ pack JS โ†’ browser shows โ†’ hydrate clicks โ†’ cache for speed.

๐Ÿ“ Folders = URLs

Put pages in the right folder and the address appears by magic (convention).

๐Ÿซ Server does heavy lifting

Fetch data on the server; send HTML first, JavaScript only for interactive toys.

โœˆ๏ธ Flight = recipe cards

Instructions cross the wire โ€” not your whole secret codebase.

๐Ÿ˜ Cache = memory

Save answers so the next visitor gets a speedy reply.

You can explain Next.js to anyone now

  • Start with folders โ†’ end with hydration and cache.
  • When stuck, ask: is this build time, request time, or browser time?

Middleware

Code that runs before a page, for matching URLs only.

๐ŸšชLike a bouncer: Before anyone enters a room, the bouncer checks a list. Wrong door? Send them elsewhere (redirect). Old sign? Quietly show the new room (rewrite). All good? Let them in (next).
export function middleware(req) {
  if (!req.cookies.has('session') && req.nextUrl.pathname.startsWith('/dashboard'))
    return NextResponse.redirect(new URL('/login', req.url))
  if (req.nextUrl.pathname === '/old-blog')
    return NextResponse.rewrite(new URL('/blog', req.url))
  return NextResponse.next()
}
export const config = { matcher: ['/((?!api|_next).*)'] }
Pick a URL.

Remember from this chapter

  • Middleware runs before routing finishes โ€” keep it fast and small.
  • Use config.matcher so it skips assets and API paths.
  • Redirect changes the URL; rewrite keeps the URL but serves another page. Newer Next.js versions rename this file convention to proxy โ€” check your version.

Server Actions

Submit a form and run a function on the server โ€” no hand-written API route.

๐Ÿ“ฎLike a mail slot: You drop a note in the slot (form). A worker inside reads it, updates the library, then hands back a fresh page.
async function addTodo(formData) {
  'use server'
  await db.todos.create({ title: formData.get('title') })
  revalidatePath('/todos')
}
Press submit to follow the request.

Remember from this chapter

  • A Server Action is a public POST endpoint โ€” always validate input and check auth inside it.
  • revalidatePath / revalidateTag tell Next.js which cached data is now stale.
  • Forms can work before hydration โ€” progressive enhancement.

Streaming & Suspense

Send the page in pieces so slow parts never block fast parts.

๐ŸšฐLike a restaurant: Bring bread right away; the main dish arrives when it is ready. Each <Suspense> is a covered plate.
<Header />
<Suspense fallback={<Skeleton />}><Reviews /></Suspense>
<Suspense fallback={<Skeleton />}><Recommendations /></Suspense>
Shell + Header (streaming)โ€”
Reviewsโ€”
Recommendationsโ€”

Without streaming the user would see nothing until the slowest part finishes.

Remember from this chapter

  • Streaming improves perceived speed: users see the shell immediately.
  • loading.tsx is automatic Suspense around a whole route segment.
  • Put Suspense close to the slow data, not around the whole page.

Rendering Strategies

SSG, SSR, ISR, PPR โ€” pick by who sees the page and how often it changes.

๐ŸณLike a bakery: Pre-baked bread (SSG), baked on order (SSR), pre-baked but refreshed every hour (ISR), or fresh toppings on a ready base (PPR).
SSG

HTML built at next build. Fastest, CDN friendly.

SSR

HTML built per request. Fresh and personal, costs server time.

ISR

Static page re-generated after revalidate time or on demand.

PPR

Static shell plus streamed dynamic holes. Availability depends on version.

Remember from this chapter

  • Using cookies, headers or uncached data makes a route dynamic automatically.
  • Static is cheaper and faster; dynamic is fresher and personal.
  • You choose per route, not per app.

Node vs Edge Runtime

Where your server code runs decides which tools it can use.

๐ŸŒLike two kitchens: A big kitchen (Node) has every appliance but is far away. A tiny food truck (Edge) is close to you and starts instantly, but carries fewer tools.
export const runtime = 'edge' // or 'nodejs'

Remember from this chapter

  • Edge = fast cold start, low latency, limited Node APIs.
  • Native modules, fs and many DB drivers need the Node runtime.
  • Choose per route with export const runtime; default to Node unless you have a reason.

Glossary

Search terms you hear in Next.js docs โ€” each with a simple line and a precise line.

Do I need Node to read this page?

No. Double-click the HTML file. Everything runs in your browser.

Is this official Next.js documentation?

No. It is a community education artifact. Always confirm behavior with the docs for your Next.js version.

Why one HTML file?

So you can fork, ship, and teach without npm, CI, or hosting lock-in. Perfect for README demos and workshops.

What license?

MIT โ€” use commercially, modify, redistribute. Keep the license notice in the file header when you redistribute.

Keyboard shortcuts