Learnings

Tutorial 4 of 6

Next.js Practice: Usage Examples and Exercises

Worked usage examples and exercises with hidden solutions for the App Router on Next 16.4 with Cache Components on: routing, server and client components, data and caching, Server Actions, route handlers, auth, metadata and three mini projects. Every file on this page was built with next build in a fresh create-next-app project.

How to use this page

Part 1 of 11 · the project, the shared data module and the list

One project for the whole page, one shared data file, and the production build as the test.

The project and the routine

How to use this page

Node 20 or newer. These are the exact flags the examples were checked with (Next 16.4.6, React 19.3, Tailwind 4, TypeScript 5):

The generated next.config.ts already has cacheComponents: true and partialPrefetching: true. That one setting changes what builds, so read the first usage example before anything else.

  • One branch per exercise: git switch -c ex-05, write the files, run npm run build, then git switch main. Examples reuse paths like app/accounts/page.tsx, so they must not share a tree.
  • Build, do not just run dev. npm run dev shows Cache Components problems as an overlay you can ignore. npm run build fails on them, and so will your CI.
  • Try for 10 to 15 minutes before opening a solution. For puzzles, write your answer down first.
  • Usage examples are worked and visible: read them, type them, build them. Exercises hide the solution in a <details>.

Types: PageProps<"/accounts/[id]">, LayoutProps and RouteContext are global helpers that next build, next dev or npx next typegen generate from your folders. If the editor says they do not exist, run npx next typegen once.

The shared bank module

How to use this page

Every example reads from this file instead of a real database. Each function waits a little with setTimeout, which is what a database call looks like to Next: async work it cannot finish while prerendering. Put it in every branch. Amounts are whole rupees.

Why it matters: with Cache Components, a page that awaits this module outside <Suspense> and outside "use cache" fails the build. That is the point of the delay: it behaves like Postgres would.

Everything on this page

How to use this page

U is a usage example (worked), a number is an exercise (solution hidden).

#ItemLevelDrills
UDynamic data and Cache Componentsmust readthe build error and its three fixes
1"use cache" did not fix iteasyruntime APIs vs cached data
2The clock that breaks the buildeasynew Date(), connection()
URoute groups, nested layouts, active linkeasy(group), usePathname
Uloading, error, not-foundeasynotFound(), retry
3Account tabs layoutmediumLayoutProps, params in a layout
UServer content inside a client wrappermediumchildren across the boundary
4Which prop breaks the build?mediumserializable props
5Why is this running on the client?medium"use client" boundaries, server-only
UStreaming with skeletonseasyseveral Suspense boundaries
UCache, tag, updatemediumuse cache, cacheTag, updateTag
USearch and pagination in the URLmediumsearchParams
6The waterfalleasyPromise.all
UDeposit form with errors and pending statemediumuseActionState, useFormStatus
7Open an account, then redirectmediumfield errors, redirect
UA small JSON APImediumGET, POST, status codes, RouteContext
8Deposit endpointmediumvalidation, 400 / 404 / 201
USession cookie, protected layout, proxyhardcookies(), proxy.ts
9Spot the security bughardre-checking inside actions
UDynamic metadata and imageseasygenerateMetadata, React cache
10The missing environment variableeasyNEXT_PUBLIC_
11Mini project: accounts browserprojectstatic params, streaming, 404
12Mini project: transfer formprojectaction, useOptimistic, tags
13Mini project: API consumed by a client pageprojecthandler, useSearchParams, router.replace
UReading the build's route tablemust readstatic, partial, dynamic

Cache Components first

Part 2 of 11 · the rule that decides whether your app builds

If you learned Next before 16, this is where your old code stops building. Learn the error message once and the rest of the page is easy.

Dynamic data and Cache Components: why the build complains and the three ways to fix it

Cache Components first · usage

With cacheComponents: true, next build prerenders every route into a static shell. Anything it cannot finish at build time must be either cached, or put behind a <Suspense> fallback so it can stream in at request time. Code that is neither is an error, not a silent switch to dynamic rendering as in Next 13 to 15. This page looks harmless:

Fix 1, stream: move the await under Suspense

The page itself stops being async. It passes the params promise down to a child that awaits it inside the boundary. The heading and the fallback go into the static shell.

Fix 2, cache: list the params and cache the data

"use cache" alone is not enough here, because params is still request data. generateStaticParams tells the build which ids exist, so it can render those pages fully. Other ids get the shell first and are filled in on the first visit.

Fix 3, block: opt the route out of the check

One line tells Next that this route is allowed to block until its data is ready, like a classic server-rendered page. It is the migration escape hatch, not the target.

FixUser sees firstData freshnessUse when
<Suspense>Shell and fallback at once, data streams inFresh on every requestPer-user or fast-changing data. The default choice.
"use cache" (+ generateStaticParams for params)The whole page, from the prerenderAs old as cacheLife allows, or until updateTagSame data for everyone: catalogues, public profiles
instant = falseNothing until all data is readyFreshMigrating an old app route by route

What to notice

  • The trigger list in the message is the whole rule: params, searchParams, cookies(), headers(), connection(), uncached fetch or database calls. Each must sit under a Suspense boundary or inside "use cache".
  • A loading.tsx next to the page is also a Suspense boundary around it, so it fixes a page (not its layout). See the special files example.
  • Old route segment config is gone with Cache Components: export const dynamic, revalidate and fetchCache are build errors. Use use cache + cacheLife instead.
  • Interview line: "Cache Components make dynamic the default and caching explicit, and the build forces every slow part to declare a fallback or a cache."

1. "use cache" did not fix it

Cache Components first · easy · puzzle

The list page below caches its data, yet npm run build still fails with the same "uncached or runtime data" error. Find the line that causes it, then fix the page so the list of accounts stays cached and only the part that depends on the URL streams.

The finished page must

  • build without instant = false;
  • show the heading "Accounts" in the static shell;
  • sort by balance, highest first, for /accounts?sort=balance, and keep the original order otherwise.

Hints

  • Reread the trigger list in the error. Which item is on the first line of the component?
  • Caching the data does not make the URL known at build time.
Solution

The culprit is await searchParams. Query strings exist only at request time, so it is runtime data, and no amount of caching the accounts changes that. Read it inside a Suspense boundary and keep the cached call as is:

  • toSorted returns a new array, so the cached value is never mutated.
  • "use cache" fixes uncached data. It never fixes runtime APIs (searchParams, cookies(), headers()); those need Suspense.

2. The clock that breaks the build

Cache Components first · easy · puzzle

This statement page has no data at all. Predict whether it builds. Then make it show the time of each request, with the heading still in the static shell.

Hints

  • What would the prerendered HTML say, and for how long would it be true?
  • The next/server package exports a function whose only job is to say "from here on, this is request time".
Solution

It does not build. A prerender would freeze the build time into the HTML, so Next refuses:

  • The same rule covers Date.now(), Math.random() and crypto.randomUUID().
  • The server's time zone is used. If you want the reader's local time, render it in a client component instead (the [client] option).

Routing and layouts

Part 3 of 11 · folders, layouts, special files, navigation

Route groups, nested layouts and an active link

Routing and layouts · usage

The bank pages share a nav, the marketing page does not. Folders in parentheses group routes under their own layout without adding a URL segment. The nav highlights the current section with a small client component.

FileURLLayouts that wrap it
app/(bank)/accounts/page.tsx/accountsroot, (bank)
app/(marketing)/about/page.tsx/aboutroot only

What to notice

  • Only NavLink is a client component. The layout stays on the server and passes plain props to it.
  • A layout inside a route group has no route of its own, so type its props directly. For real segments use LayoutProps<"/accounts/[id]"> (see exercise 3).
  • Two groups must not both define the same URL: (bank)/about and (marketing)/about would be a build error.

loading, error and not-found for one account

Routing and layouts · usage

Four files in one folder: the page, a skeleton while it loads, a 404 for unknown ids, and an error boundary for anything unexpected. Because loading.tsx wraps the page in Suspense, the page may await params directly.

FileShown whenRuns onNote
loading.tsxThe page is awaitingserverIs a Suspense boundary around the page, not around the layout
not-found.tsxnotFound() is calledserverAdds noindex; see the status trap below
error.tsxRendering threwclientProps are error: unknown and retry

What to notice

  • notFound() returns never, so TypeScript knows account is defined after it.
  • Trap, checked with curl: /accounts/99 answers 200, not 404. The loading shell was already sent with a 200 when notFound() ran; Next adds <meta name="robots" content="noindex"> instead. If the status code matters (APIs, analytics), check before streaming starts, for example in proxy.ts.
  • In production a server error reaches error.tsx with a generic message and a digest to find in the server logs. Never show raw server messages to users.
  • In Next 16.3+ the recovery prop is retry(), which re-fetches the segment. The older reset() only re-renders without new data.

3. Account tabs layout

Routing and layouts · medium

Give every account two tabs, Overview at /accounts/[id] and Transactions at /accounts/[id]/transactions, under a shared layout that shows the owner's name. The layout must not block the static shell while it looks up the owner.

The finished thing must

  • show the owner as the heading on both tabs, with the fallback heading "Account" while it loads;
  • mark the current tab with aria-current="page";
  • show the balance on Overview and the last transactions on Transactions;
  • build with Cache Components on and without instant = false.

Hints

  • Type the layout with LayoutProps<"/accounts/[id]">. Its params is a promise: do not await it in the layout body.
  • A client component can read the id itself with useParams(), so the tabs need no props.
Solution
  • The layout is not async. The await happens inside Owner, under its own boundary, so the page shell still prerenders.
  • Trap: useParams() in a client component is URL data too. Without the Suspense around <Tabs /> the build fails with "Next.js encountered URL data `useParams()` in a Client Component outside of `<Suspense>`". useSearchParams() behaves the same way.
  • Owner and Balance both call getAccount. The metadata example shows how React cache() makes that one call per request.

Server and client components

Part 4 of 11 · what runs where, and what can cross

Server content inside a client wrapper

Server and client components · usage

A collapsible panel needs state, so it is a client component. What goes inside it can still be a server component that reads the database: the server renders it and hands the result to the client as children.

The rule for props from a server component to a client component, checked against this version:

Prop valueCrosses?Note
string, number, boolean, null, plain object, arrayyesSerialized into the RSC payload, so visible in the page source
Date, Map, SetyesArrive as real Date / Map / Set objects
JSX, including server components (children)yesRendered on the server first
A PromiseyesRead it with React use() inside Suspense
A Server Action ("use server" function)yesSent as a reference; calling it makes a POST
Any other function, event handlernoBuild error, see exercise 4
Class instanceno"Only plain objects, and a few built-ins, can be passed to Client Components"

What to notice

  • RecentTxns is not imported by the client file, it is passed in. That is what keeps it on the server.
  • The server renders the children even while the panel is closed (they are part of the cached page). Fine for small content; for heavy content load it on demand instead.

4. Which prop breaks the build?

Server and client components · medium · puzzle

A server page renders a client row and passes three props. Predict: does npx tsc --noEmit pass? Does npm run build pass? If not, which prop and why? Then fix it so a click still runs code on the server.

Hints

  • TypeScript checks types, not where code runs.
  • Look at the table in the previous example. One of these props is fine although many people expect it to fail.
Solution

tsc passes. The build fails on onSelect: a plain function cannot be serialized to the browser. The Date is fine.

If the click should run server code, pass a Server Action instead. It crosses as a reference, and AccountRow stays as it is:

  • If the click only changes the UI, the fix is simpler: drop the prop and keep the handler inside the client component.
  • A Server Action is a public POST endpoint: anyone can call it with any argument. Hence the check, and see exercise 9.

5. Why is this running on the client?

Server and client components · medium · puzzle

FeeNote has no "use client", and the fee rule is marked server-only. Yet the build fails. Explain why FeeNote is a client component here, then restructure so the fee rule never reaches the browser and the card still opens and closes.

Hints

  • "use client" marks a boundary in the import graph, not a single component.
  • You already saw the fix in the Collapsible example.
Solution

Every module imported from a client module is bundled for the client too, whatever its own directives. AccountCard imports FeeNote, which imports lib/fees.ts, so the build stops:

Let the card take children and let the server page render FeeNote (lib/fees.ts and FeeNote.tsx stay as they are):

  • Without import "server-only" the first version builds and silently ships the pricing rule in the browser bundle. Put that import in every module that holds secrets or business rules.
  • A component file without a directive is "shared": it becomes whatever its importer is. Only the importer decides.

Data: fetching, streaming, caching

Part 5 of 11 · reading data on the server with the current APIs

Streaming with skeletons

Data: fetching, streaming, caching · usage

The account header takes about 100 ms, the transactions about 300 ms. Give each its own boundary and the header appears as soon as it is ready instead of waiting for the slower list. The skeletons are part of the static shell, so the first byte is instant.

What to notice

  • Boundaries are independent: each one swaps its fallback for content when its own data arrives.
  • Both children await the same params promise. Awaiting a promise twice is free.

Cache, tag, update

Data: fetching, streaming, caching · usage

Cache the accounts list for hours, tag it, and expire the tag from the Server Action that changes balances. The page needs no Suspense at all: all its data is cached, so the build prerenders it completely.

CallWhereEffectUse for
updateTag("accounts")Server Actions onlyExpires now; next read waits for fresh dataThe user must see their own change
revalidateTag("accounts", "max")Actions and route handlersStale-while-revalidate: old data once, fresh in the backgroundWebhooks, CMS updates
revalidatePath("/accounts")Actions and route handlersEverything cached for that pathWhen you do not know the tags
refresh()Server ActionsRe-renders the current page; touches no cacheUncached data on screen
cacheLife("hours")Inside "use cache"Time-based: 5 min stale in the browser, revalidate after 1 h, expire after 1 dayData that may lag a little

What to notice

  • The one-argument revalidateTag(tag) is deprecated and a TypeScript error. Pass a profile, usually "max".
  • cacheLife("seconds") or anything that expires within 5 minutes is "short-lived" and is left out of the prerender: the page then needs a Suspense boundary again.
  • The old fetch(url, {"{"} next: {"{"} revalidate: 60 {"}"} {"}"}) and cache: "force-cache" belong to the previous model. With Cache Components, put the fetch inside a "use cache" function and use cacheLife / cacheTag.

Search and pagination in the URL

Data: fetching, streaming, caching · usage

Keep filter state in the query string: it survives reloads, can be shared, and needs no client state. A plain GET form writes ?q=, the page reads it under Suspense, and the data itself comes from cache.

URLsp.qsp.page
/accountsundefinedundefined
/accounts?q=san&page=2"san""2"
/accounts?q=a&q=b["a", "b"]undefined

What to notice

  • Values are string | string[] | undefined. Never trust them: narrow, parse and clamp, as with query params in any backend.
  • Filtering a cached list is cheap. For big tables, pass q and page into a cached function so they become part of the cache key.

6. The waterfall

Data: fetching, streaming, caching · easy · puzzle

From the delays in lib/bank.ts, predict roughly how long Summary takes to render (100 ms for an account or the list, 300 ms for transactions). Then make it take only as long as the slowest call.

Hints

  • Does any call need the result of another?
  • A promise starts running when the function is called, not when it is awaited.
Solution

About 500 ms: 100 + 300 + 100, one after the other, although none depends on another. Start all three, then await them together, and it takes about 300 ms:

  • When a call does depend on another (load the account, then its branch), keep it sequential but move the dependent part into its own Suspense child so the first part can show.

Mutations with Server Actions

Part 6 of 11 · forms, validation, pending state, redirect

Deposit form with errors and pending state

Mutations with Server Actions · usage

The action validates on the server and returns expected errors as values, not exceptions. useActionState shows them, useFormStatus disables the button while the request runs, and updateTag makes the new balance appear.

What to notice

  • .bind(null, id) pre-fills the first argument. It is convenient, not secure: a caller can send any id, so the action must check ownership (exercise 9).
  • Return expected errors as state. Throwing would hit error.tsx, which is for bugs.
  • After a successful action React resets the form's uncontrolled inputs. If you want to keep what the user typed after an error, return it in the state and use it as defaultValue (next exercise).

7. Open an account, then redirect

Mutations with Server Actions · medium

Build /accounts/new: a form with the owner's name and an optional opening deposit. On success, open the account, deposit, expire the accounts tag and redirect to the new account's page.

The finished thing must

  • show an error under each invalid field: name must be 2 to 60 letters (spaces, dot, apostrophe and hyphen allowed); deposit must be empty or a whole number of rupees, 0 or more;
  • keep what the user typed when it shows errors;
  • disable the button and say "Opening..." while the action runs;
  • end at /accounts/<new id> on success.

Hints

  • Let the state carry both errors and the submitted values.
  • redirect() throws a special error to stop the action. Never call it inside a try block that catches everything.
Solution
  • Validation lives on the server. You may add required or pattern to the inputs for quick feedback, but never instead of it.
  • Call updateTag before redirect, so the page you land on already reads fresh data.

Route handlers

Part 7 of 11 · HTTP endpoints in route.ts

A small JSON API

Route handlers · usage

List with filters, create with validation, and read one by id. Handlers use the standard Request and Response; NextRequest adds nextUrl for easy query parsing. RouteContext types the dynamic segment.

NeedRoute handlerServer Action
Called by your own forms and buttonsworks, more codeyes, the default
Called by a mobile app, a partner, a webhook, curlyesno (POST with a private action id)
GET, caching, a stable public URLyesno, actions are POST only
Status codes and headers you controlyesno
Progressive enhancement, pending state, updateTagno (revalidateTag only)yes
Needs auth and input validationyesyes, both are public endpoints

What to notice

  • request.json() throws on invalid JSON; .catch(() => null) turns that into a 400 instead of a 500.
  • "owner" in body narrows unknown without a cast. In a real app use a schema library such as Zod.
  • With Cache Components a GET handler that touches no request data and no uncached I/O is prerendered at build time, like a page. These two read the request or the bank, so they run per request.

8. Deposit endpoint

Route handlers · medium

Add POST /api/accounts/[id]/deposits with a JSON body {"{"} "amount": 500 {"}"}. Respond with the updated account, and with the right status code for each kind of failure.

Expected results

RequestStatusBody
/api/accounts/2/deposits, {"{"}"amount":500{"}"}201{"{"}"id":"2","owner":"Sandhya Agrawani","balance":12500{"}"}
same, body {"{"}"amount":"500"{"}"}400{"{"}"error":"amount must be a whole number above 0"{"}"}
same, body oops400{"{"}"error":"body must be JSON"{"}"}
/api/accounts/99/deposits, valid body404{"{"}"error":"account not found"{"}"}
GET /api/accounts/2/deposits405(empty)

Hints

  • Type the second argument as RouteContext<"/api/accounts/[id]/deposits">.
  • You do not write the 405: Next answers it for every method you do not export.
  • typeof amount === "number" is the line that rejects "500".
Solution
  • 400 means "your request is malformed", 404 "that resource does not exist", 422 "well formed but the business rule says no". Pick one convention and keep it.
  • This endpoint has no auth yet. Before shipping, read the session (or an API token) exactly as in the next part.

Auth

Part 8 of 11 · cookies, protected routes, never trusting the client

Session cookie, protected layout and proxy

Auth · usage

A signed, httpOnly cookie holds the account id. proxy.ts (the Next 16 name for middleware.ts) bounces visitors without a cookie early, the layout checks the signature, and the page checks again where it reads data. The PIN check is a demo stand-in for a real password or an auth library.

LayerChecksEnough on its own?
proxy.tsCookie existsNo: a forged cookie passes, and matchers are easy to get wrong
LayoutSignature validNo: layouts do not re-render on every navigation, and actions and route handlers skip them
Page, action, route handlerSignature valid and the user may touch this dataYes, this is the real check

What to notice

  • The layout reads cookies() inside Suspense, as Cache Components require; the fallback is part of the static shell.
  • A real app needs a stable SESSION_SECRET from the environment, session expiry and rotation, and a password hash or an auth library (Auth.js, Better Auth, Clerk).

9. Spot the security bug

Auth · hard · puzzle

This page lives under the protected layout from the previous example, so only signed-in users can see it. The hidden field holds the signed-in user's own account. Find how a signed-in user can send money out of someone else's account, then fix the action.

Hints

  • Who can send a POST to a Server Action, and what can they put in the body?
  • The layout's check ran when the page was rendered. Does it run when the action is called?
Solution

A Server Action is a public POST endpoint. Any signed-in user can open the browser dev tools, change the hidden from to 2, and move Sandhya's money; a script can do the same without the page at all. The layout never runs for an action call. The fix: take the account from the session inside the action and ignore anything the client says about identity.

  • Rule: identity and permissions come from the server (session, database), never from form fields, bound arguments, URL params or hidden inputs.
  • The same applies to the bound accountId in the deposit example: check that the session owns that account before changing it.

Metadata, assets and environment

Part 9 of 11 · titles, images, fonts, configuration

Dynamic metadata and images

Metadata, assets and environment · usage

The account page sets its title from the database. The layout provides a title template, React cache() makes generateMetadata and the page share one database call per request, and next/image renders a logo from public/.

NeedUseNote
Fixed titleexport const metadataLayouts and pages; merged top-down, page wins
Title from datagenerateMetadataSame Cache Components rules as the page
Image above the fold<Image preload />priority is deprecated since Next 16
Remote imagesimages.remotePatterns in next.config.tsOtherwise the build or the request fails
Fontsnext/font/google or next/font/localThe generated app/layout.tsx already uses Geist this way
De-duplicate a DB call per requestReact cache(fn)Request scoped. "use cache" is the cross-request cache

What to notice

  • Because the page itself streams, the build lets the metadata stream too. If the rest of the page were fully static, Next would ask you to cache the metadata data with "use cache".
  • fetch calls with the same URL and options are de-duplicated per request automatically; database calls need cache().

10. The missing environment variable

Metadata, assets and environment · easy · puzzle

.env.local contains BANK_NAME=Practice Bank and BANK_API_KEY=secret. What does the browser end up showing for the bank name, and why? Fix it two ways: once with a prop from a server component, and say which other rename would also work and why you would not do that for the key.

Hints

  • Which variables does Next copy into the browser bundle at build time?
  • A server component can read any variable and pass the value down.
Solution

Only names starting with NEXT_PUBLIC_ are inlined into client code at build time. In the browser bundle process.env.BANK_NAME is undefined, so the name is missing after hydration (and React may warn about a mismatch with the server-rendered HTML, which did see it). The safe fix keeps the variable on the server:

  • Renaming to NEXT_PUBLIC_BANK_NAME also works, and is fine for a name. Never do it for BANK_API_KEY: anything NEXT_PUBLIC_ is readable by every visitor.

Mini projects and the route table

Part 10 of 11 · three small apps that combine the parts, and how to read what the build made of them

Each project is one branch. Their URLs do not collide, so you can also build all three in one tree, which is what the route table chapter does.

11. Mini project: accounts browser

Mini projects and the route table · project

A list of accounts and a detail page per account. Account data may be up to an hour old; transactions must always be fresh.

The finished thing must

  • /accounts: every owner with balance and a link, plus the total of all balances; fully static in the build output;
  • /accounts/[id]: prerendered at build time for every existing account; owner and balance from cache, transactions streamed per request behind a skeleton;
  • an unknown id shows "No account with that number" with a link back to the list;
  • account reads are tagged accounts, so a later Server Action can expire them.

Hints

  • Put both cached reads in one small module next to the routes.
  • With generateStaticParams and cached data, the page may await params at the top. Only the fresh part needs Suspense.
Solution
  • The build output shows ○ /accounts and, under /accounts/[id], one ◐ line per account: the header is in the static HTML, the transactions are the dynamic hole. See the route table.
  • An id the build did not list (an account opened later) is rendered on its first visit and then cached like the others.
  • Same status trap as before, checked with curl: /accounts/99 shows the not-found UI with a 200 and a noindex tag, because the shell for unknown ids is streamed first.

12. Mini project: transfer form

Mini projects and the route table · project

Rishikesh Agrawani sends money to another family account at /transfer. Show his balance, a form, and his last five transactions. The new transaction must appear in the list the moment he submits, before the server answers.

The finished thing must

  • offer every other account as a payee and validate the amount on the server (whole rupees above 0, not more than the balance);
  • show the pending row as "... (sending)" immediately, and remove it again if the server says no;
  • show server errors under the form, and the fresh balance and list after success;
  • expire the accounts tag after a transfer;
  • take the sender from one place (a stand-in for the session of exercise 9), never from the form.

Hints

  • Wrap the Server Action in a client function passed to useActionState. Inside it, call the useOptimistic setter, then await the real action.
  • A "use server" file may export only async functions (and types). Keep constants elsewhere.
Solution
  • The optimistic row lives only while the action's transition is running. On success the server's re-rendered list replaces it; on failure it simply disappears, with no rollback code.
  • Only {"{"} id, owner {"}"} is sent for payees: everything you pass to a client component is visible in the page source, so do not send other people's balances.

13. Mini project: API consumed by a client page

Mini projects and the route table · project

A JSON endpoint under /api/v1 and an /explorer page that consumes it from the browser, as a separate frontend or a mobile app would. The search box is kept in the URL.

The finished thing must

  • GET /api/v1/accounts?q= returns the accounts whose owner contains q, case-insensitive;
  • /explorer?q=san opens with "san" in the box and only matching accounts listed; typing updates the URL without adding history entries;
  • a stale response never overwrites a newer one while the user types.

Hints

  • useSearchParams() is URL data: wrap the client component in Suspense or the build fails.
  • An AbortController per effect run cancels the previous request.
  • router.replace(`${"{"}pathname{"}"}?${"{"}params{"}"}`) changes the URL without a history entry.
Solution
  • This is the one place on the page where the browser fetches data in useEffect. Inside a Next app you would read on the server instead; the pattern is for consuming your API from a client the server does not render.
  • The input is uncontrolled with defaultValue, so typing stays smooth while the URL catches up. Add a 300 ms debounce before router.replace for real traffic.

Reading the build's route table

Mini projects and the route table · usage

The last thing next build prints is a table of every route and what it became. This is the real output for the three mini projects built together in one fresh project:

SymbolMeansHereWhy
○ StaticComplete HTML at build time, served as a file/, /accounts, /explorerNo server-side runtime data. /accounts only reads "use cache" data; /explorer reads the URL in a client component, so the server prerenders its fallback and the browser does the rest
◐ Partial PrerenderStatic shell at build time, holes streamed per request/accounts/1 to /5, /transferA server-side Suspense boundary around uncached data
ƒ DynamicNothing prerendered, runs on every request/api/v1/accountsA route handler that reads the request

What to notice

  • The indented lines under /accounts/[id] are the ids from generateStaticParams. The ◐ /accounts/[id] line itself is the App Shell served for ids the build did not know.
  • Revalidate and Expire come from cacheLife("hours"): the static HTML is regenerated in the background after an hour and thrown away after a day. /explorer has no cached data, so no timer.
  • With Cache Components a page is almost never ƒ: reading cookies or params no longer makes the whole route dynamic, it only makes a hole in the shell. If a page you expected to be ○ shows ◐, look for a Suspense boundary around uncached data.
  • When a build fails on prerendering, next build --debug-prerender gives better stack traces, and next dev shows the same problem as an overlay on the page.

Where to go next

Part 11 of 11 · the other pages of this path

Next steps

Where to go next

  • React vs Next: what each Next feature on this page replaces in a plain React app, side by side.
  • Design to code: turning a Figma frame into these server and client components.
  • React practice: the same kind of exercises for hooks, state and components, without the server.
  • Back to Next.js Essentials for the concepts, or start the exercises again from the list.