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
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, runnpm run build, thengit switch main. Examples reuse paths likeapp/accounts/page.tsx, so they must not share a tree. - Build, do not just run dev.
npm run devshows Cache Components problems as an overlay you can ignore.npm run buildfails 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
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
U is a usage example (worked), a number is an exercise (solution hidden).
| # | Item | Level | Drills |
|---|---|---|---|
| U | Dynamic data and Cache Components | must read | the build error and its three fixes |
| 1 | "use cache" did not fix it | easy | runtime APIs vs cached data |
| 2 | The clock that breaks the build | easy | new Date(), connection() |
| U | Route groups, nested layouts, active link | easy | (group), usePathname |
| U | loading, error, not-found | easy | notFound(), retry |
| 3 | Account tabs layout | medium | LayoutProps, params in a layout |
| U | Server content inside a client wrapper | medium | children across the boundary |
| 4 | Which prop breaks the build? | medium | serializable props |
| 5 | Why is this running on the client? | medium | "use client" boundaries, server-only |
| U | Streaming with skeletons | easy | several Suspense boundaries |
| U | Cache, tag, update | medium | use cache, cacheTag, updateTag |
| U | Search and pagination in the URL | medium | searchParams |
| 6 | The waterfall | easy | Promise.all |
| U | Deposit form with errors and pending state | medium | useActionState, useFormStatus |
| 7 | Open an account, then redirect | medium | field errors, redirect |
| U | A small JSON API | medium | GET, POST, status codes, RouteContext |
| 8 | Deposit endpoint | medium | validation, 400 / 404 / 201 |
| U | Session cookie, protected layout, proxy | hard | cookies(), proxy.ts |
| 9 | Spot the security bug | hard | re-checking inside actions |
| U | Dynamic metadata and images | easy | generateMetadata, React cache |
| 10 | The missing environment variable | easy | NEXT_PUBLIC_ |
| 11 | Mini project: accounts browser | project | static params, streaming, 404 |
| 12 | Mini project: transfer form | project | action, useOptimistic, tags |
| 13 | Mini project: API consumed by a client page | project | handler, useSearchParams, router.replace |
| U | Reading the build's route table | must read | static, 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.
| Fix | User sees first | Data freshness | Use when |
|---|---|---|---|
<Suspense> | Shell and fallback at once, data streams in | Fresh on every request | Per-user or fast-changing data. The default choice. |
"use cache" (+ generateStaticParams for params) | The whole page, from the prerender | As old as cacheLife allows, or until updateTag | Same data for everyone: catalogues, public profiles |
instant = false | Nothing until all data is ready | Fresh | Migrating an old app route by route |
What to notice
- The trigger list in the message is the whole rule:
params,searchParams,cookies(),headers(),connection(), uncachedfetchor database calls. Each must sit under a Suspense boundary or inside"use cache". - A
loading.tsxnext 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,revalidateandfetchCacheare build errors. Useuse cache+cacheLifeinstead. - 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:
toSortedreturns 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/serverpackage 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()andcrypto.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.
| File | URL | Layouts that wrap it |
|---|---|---|
app/(bank)/accounts/page.tsx | /accounts | root, (bank) |
app/(marketing)/about/page.tsx | /about | root only |
What to notice
- Only
NavLinkis 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)/aboutand(marketing)/aboutwould 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.
| File | Shown when | Runs on | Note |
|---|---|---|---|
loading.tsx | The page is awaiting | server | Is a Suspense boundary around the page, not around the layout |
not-found.tsx | notFound() is called | server | Adds noindex; see the status trap below |
error.tsx | Rendering threw | client | Props are error: unknown and retry |
What to notice
notFound()returnsnever, so TypeScript knowsaccountis defined after it.- Trap, checked with
curl:/accounts/99answers 200, not 404. The loading shell was already sent with a 200 whennotFound()ran; Next adds<meta name="robots" content="noindex">instead. If the status code matters (APIs, analytics), check before streaming starts, for example inproxy.ts. - In production a server error reaches
error.tsxwith a generic message and adigestto 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 olderreset()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]">. Itsparamsis 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 insideOwner, 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. OwnerandBalanceboth callgetAccount. The metadata example shows how Reactcache()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 value | Crosses? | Note |
|---|---|---|
| string, number, boolean, null, plain object, array | yes | Serialized into the RSC payload, so visible in the page source |
Date, Map, Set | yes | Arrive as real Date / Map / Set objects |
JSX, including server components (children) | yes | Rendered on the server first |
| A Promise | yes | Read it with React use() inside Suspense |
A Server Action ("use server" function) | yes | Sent as a reference; calling it makes a POST |
| Any other function, event handler | no | Build error, see exercise 4 |
| Class instance | no | "Only plain objects, and a few built-ins, can be passed to Client Components" |
What to notice
RecentTxnsis 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
paramspromise. 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.
| Call | Where | Effect | Use for |
|---|---|---|---|
updateTag("accounts") | Server Actions only | Expires now; next read waits for fresh data | The user must see their own change |
revalidateTag("accounts", "max") | Actions and route handlers | Stale-while-revalidate: old data once, fresh in the background | Webhooks, CMS updates |
revalidatePath("/accounts") | Actions and route handlers | Everything cached for that path | When you do not know the tags |
refresh() | Server Actions | Re-renders the current page; touches no cache | Uncached data on screen |
cacheLife("hours") | Inside "use cache" | Time-based: 5 min stale in the browser, revalidate after 1 h, expire after 1 day | Data 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 {"}"} {"}"})andcache: "force-cache"belong to the previous model. With Cache Components, put the fetch inside a"use cache"function and usecacheLife/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.
| URL | sp.q | sp.page |
|---|---|---|
/accounts | undefined | undefined |
/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
qandpageinto 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
errorsand the submittedvalues. redirect()throws a special error to stop the action. Never call it inside atryblock that catches everything.
Solution
- Validation lives on the server. You may add
requiredorpatternto the inputs for quick feedback, but never instead of it. - Call
updateTagbeforeredirect, 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.
| Need | Route handler | Server Action |
|---|---|---|
| Called by your own forms and buttons | works, more code | yes, the default |
Called by a mobile app, a partner, a webhook, curl | yes | no (POST with a private action id) |
| GET, caching, a stable public URL | yes | no, actions are POST only |
| Status codes and headers you control | yes | no |
Progressive enhancement, pending state, updateTag | no (revalidateTag only) | yes |
| Needs auth and input validation | yes | yes, 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 bodynarrowsunknownwithout 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
| Request | Status | Body |
|---|---|---|
/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 oops | 400 | {"{"}"error":"body must be JSON"{"}"} |
/api/accounts/99/deposits, valid body | 404 | {"{"}"error":"account not found"{"}"} |
GET /api/accounts/2/deposits | 405 | (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.
| Layer | Checks | Enough on its own? |
|---|---|---|
proxy.ts | Cookie exists | No: a forged cookie passes, and matchers are easy to get wrong |
| Layout | Signature valid | No: layouts do not re-render on every navigation, and actions and route handlers skip them |
| Page, action, route handler | Signature valid and the user may touch this data | Yes, 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_SECRETfrom 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
accountIdin 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/.
| Need | Use | Note |
|---|---|---|
| Fixed title | export const metadata | Layouts and pages; merged top-down, page wins |
| Title from data | generateMetadata | Same Cache Components rules as the page |
| Image above the fold | <Image preload /> | priority is deprecated since Next 16 |
| Remote images | images.remotePatterns in next.config.ts | Otherwise the build or the request fails |
| Fonts | next/font/google or next/font/local | The generated app/layout.tsx already uses Geist this way |
| De-duplicate a DB call per request | React 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". fetchcalls with the same URL and options are de-duplicated per request automatically; database calls needcache().
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_NAMEalso works, and is fine for a name. Never do it forBANK_API_KEY: anythingNEXT_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
generateStaticParamsand cached data, the page may awaitparamsat the top. Only the fresh part needs Suspense.
Solution
- The build output shows
○ /accountsand, 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/99shows the not-found UI with a 200 and anoindextag, 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
accountstag 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 theuseOptimisticsetter, 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 containsq, case-insensitive;/explorer?q=sanopens 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
AbortControllerper 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 beforerouter.replacefor 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:
| Symbol | Means | Here | Why |
|---|---|---|---|
○ Static | Complete HTML at build time, served as a file | /, /accounts, /explorer | No 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 Prerender | Static shell at build time, holes streamed per request | /accounts/1 to /5, /transfer | A server-side Suspense boundary around uncached data |
ƒ Dynamic | Nothing prerendered, runs on every request | /api/v1/accounts | A route handler that reads the request |
What to notice
- The indented lines under
/accounts/[id]are the ids fromgenerateStaticParams. 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./explorerhas 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-prerendergives better stack traces, andnext devshows 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
- 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.