NEXT.JS CODING
Next.js problems
78 problems for the Next.js coding round: write pages, Route Handlers, Server Actions, and Client Components in the editor, and run tests that call them the way Next.js does. 27 easy, 33 medium, and 18 hard.
The tests run Next.js's own code for requests, responses, redirects, and 404s, with React Testing Library, on this page. Your code is saved as you go, and hints are free. Sign in with Google to see the solutions.
78 of 78 problems
Pages & dynamic routes
- A page for every teaA dynamic route,
app/teas/[slug]/page.tsx: an async Server Component that loads its tea and calls notFound() for the rest. - Brewing guides at any depthA catch-all route,
app/guides/[...slug]/page.tsx: one page for guides nested at any depth, with a breadcrumb built from the URL. - An error screen that can retry
app/teas/error.tsx: a Client Component that shows a safe message and the error's digest, reports it once, and callsretry. - Tea list filtered, sorted, and paged by the URL
app/teas/page.tsxreads its awaitedsearchParamsto filter, sort, and paginate, with safe defaults for bad values and links that keep the rest. - Tea pages under their category
app/shop/[category]/[slug]/page.tsx: two dynamic segments, both filled bygenerateStaticParams, with a 404 for unknown teas and a 308 to the right category. - A home page without a waterfall
app/page.tsxwaits for three slow queries one after another. Start them together withPromise.all, so the page is ready when the slowest is. - Filters in the path, one URL for each listAn optional catch-all,
app/collections/[[...filters]]/page.tsx: read filter segments, answer 404 for bad ones, and 308 to a single canonical order. - Start each query as early as it canA tea page whose queries depend on each other: start the reviews with the tea, the teas of its type once the tea is in, and survive a reviews outage.
Links & client navigation
- Nav links that show where you areA Client Component header nav that marks the current page and section with
usePathname,aria-current, and anactiveclass. - Tea page tabs in the URLTabs made of links that keep the open tab in
?tab=, switching withreplaceandscroll={false}and keeping the other params. - A modal that closes by going backThe Client Component modal for an intercepted tea route: close it with
router.back()on Close, Escape, or a click on the backdrop. - Tea search in the URLA Client Component search box that keeps what you type in the URL's
q, with useRouter, usePathname, and useSearchParams. - Tea type filters as repeated paramsCheckboxes kept in the URL as
?type=green&type=oolong: read withgetAll, written in one order, and pushed so Back undoes each change. - Warn before leaving an unsaved noteBlock
Linknavigation withonNavigatewhile a tasting note is unsaved, never ask on a Ctrl-click, and cover reloads withbeforeunload. - Page links with gaps that keep the filtersA Client Component pager,
1 … 5 6 7 … 12, whose<Link href={{ pathname, query }}>links keep every other param, repeated ones too. - Sign in, then back to next, safelyA sign-in form that returns to
?next=withrouter.replace, behind asafeNextPathguard that refuses every way off the site.
Server & Client Components
- A steep timer on a server-rendered tea pageAdd a countdown to a tea's page as a small Client Component, so the page itself stays a Server Component.
- Move the tea list back to the serverTurn an all-client tea list that fetches in an effect into an async Server Component, keeping only the Add to cart buttons on the client.
- A cart context around server-rendered pagesA context provider as a Client Component that wraps the shop's Server Component pages, passed in as children, with a useCart hook.
- Send the buy box only what it needsA tea page that passes its Client Component a plain object with four safe fields, not the database row with its class instances and secrets.
- An Add to cart form that shows it's workingA Client Component form that imports a Server Action, runs it with useActionState, and shows a pending button and the action's answer.
- Stream the slow reviewsShow a tea's page as soon as the tea loads, and stream its slow reviews in from an async Server Component inside Suspense.
- Helpful votes that answer at once and roll backA Client Component that shows a vote straight away with useOptimistic, settles on the Server Action's count, and rolls back when saving fails.
- A currency picker that saves through a Server ActionA page that reads a cookie, and passes an inline Server Action, not a plain function, to a Client Component that sets the cookie.
Route Handlers
- Tea search APIA
GETRoute Handler that filters and sorts the teas from the query string, and answers 400 for a query it can't use. - One order by its idA dynamic
GETRoute Handler that awaits itsparams, and answers 400 for an id that isn't a whole number and 404 for an order that isn't there. - Short links that redirectA
GETRoute Handler that looks up a short code and redirects withNextResponse.redirect, keeping the link's search params, or answers 404. - A price list to download as CSVA
GETRoute Handler at/price-list.csvthat answers a CSV file with the right headers, quoting the fields that need it. - Create a review with POSTA
POSTRoute Handler that checks the tea, theContent-Type, and the JSON body, then answers 201 with aLocation, or 404, 415, or 400. - A tea API that answers 304 Not ModifiedA
GETRoute Handler that sends anETagand answers 304 with no body whenIf-None-Matchshows the app already has the latest tea. - Edit and delete your own reviews
GET,PATCH, andDELETEin oneroute.ts: a bearer token for changes, 401, 403, and 404 in the right order, and 204 for a delete. - A signed stock webhook that revalidatesA webhook Route Handler that verifies an HMAC signature on the raw body, refuses replays and repeats, updates stock, and calls
revalidateTag. - Rate-limit the newsletter sign-upA fixed-window rate limit per client in a Route Handler:
X-RateLimit-*headers, and 429 withRetry-Afteronce a client has used up its window.
Server Actions & forms
- Remove buttons bound to each teaA wishlist page with an inline Server Action, bound to each tea's slug with bind, that removes the tea and revalidates the page.
- A submit button that knows its form is sendingA shared Client Component submit button that reads useFormStatus to disable itself and show pending text while its own form's action runs.
- A to-try list that shows your change at onceServer Actions for a personal to-try list that call updateTag for the customer's own list, and revalidateTag with max for a shared one.
- Tea review Server ActionA Server Action that checks a review form's fields, saves it, revalidates the tea's page, and redirects there.
- Sign in and sign out with a session cookieServer Actions that check a password, set a safe session cookie and redirect, give one error for any bad sign-in, and end the session on sign-out.
- A newsletter form that keeps what was typedA useActionState form that marks each wrong field, keeps the typed values through React's form reset, and works before JavaScript loads.
- Cancel an order, checked again on the serverA bound Server Action that checks the session, the order's owner, and its status itself, though the page already hides the button.
- Checkout steps that remember progress in a cookieServer Actions for a three-step checkout that keep progress in a JSON cookie, check it again at every step, and total the order on the server.
- A brew photo upload that checks the fileA Server Action that checks an uploaded File's size, type, and first bytes, names it on the server, and saves it to the gallery.
proxy.ts
- Send signed-out visitors to sign inA
proxy.tsthat runs for/accountand the pages under it, and redirects a visitor without a session cookie to/sign-in?next=…. - Password-protect the staging siteHTTP Basic authentication in
proxy.ts: decode theAuthorizationheader, compare safely, and answer 401 withWWW-Authenticatestraight from the proxy. - A request id for the page and the browserForward an
x-request-idheader to the app withNextResponse.next({ request: { headers } }), and send the same id to the browser on the response. - Send each visitor to their languageRedirect paths without a language to
/enor/fr, picked from aNEXT_LOCALEcookie or the weights inAccept-Language. - A/B test the home page with a cookiePut each visitor of
/in group a or b once, remember it in a cookie, and rewrite to/home-aor/home-bwhile the address stays/. - Run proxy.ts for pages onlyWrite the
config.matcherthat keepsproxy.tsaway from the API, Next.js's files, metadata files, images, and prefetches, but not from/apiary. - A shop on every tea house's own addressRead the
hostheader, rewrite tea houses' subdomains and custom domains to/sites/<tenant>, and answer 404 for unknown hosts and/sites. - Maintenance mode with a way in for staffRewrite pages to
/maintenance, answer the API with 503 andRetry-After, keep an allow-list open, and let staff in with a preview link that becomes a cookie.
Metadata & SEO files
- A robots.txt that keeps staging out of search
app/robots.tsthat lets crawlers into the shop but not /account or /checkout, names the sitemap, and shuts every other deploy. - A web app manifest to install the shop
app/manifest.tswith the shop's names and colors, a standalone window, a stable id, and its icons sized and marked any or maskable. - Titles, descriptions, and social cards for tea pages
generateMetadatafor each tea: its title, a description cut at a word, a canonical URL, an Open Graph card, and noindex for retired teas. - A sitemap built from the teas and the journal
app/sitemap.tsfrom the database: full URLs, no retired teas or drafts, and each page's lastModified taken from when its content changed. - Product structured data on the tea pageA JSON-LD
<script>with a schema.org Product: full URLs, the offer's price and stock, a rating only with reviews, and every<escaped. - hreflang links between English and French tea pages
generateMetadatafor a tea page in two languages: hreflang links both ways, a canonical of its own, Open Graph locales, and redirects for the wrong slug.
Caching & revalidation
- Tag and time the cached tea catalogA
"use cache"data layer for the teas: a list tag and a tag per tea on each entry, and a cacheLife profile that fits each read. - Member prices without caching the memberSplit a tea page so its cached part takes the member's tier as a prop, and the greeting that reads the session cookie stays outside the cache.
- A price change staff see at onceA staff-only Server Action that saves a price, calls updateTag for the tea being edited, and revalidateTag with max for every list that shows it.
- A CMS webhook that revalidates the journalA Route Handler the CMS calls with a shared secret, mapping each event to the journal's cache tags, with max or an immediate expiry for each.
- Tag a big collection without losing tagsA cached collection read that tags every tea it lists, retired ones included, each once, in cacheTag calls of at most 128 tags.
- A flash sale price never a minute oldA cached price read that picks its own cacheLife from the sale's end time, so no shopper sees a sale price over a minute old and no copy outlives the sale.
Auth & security
- An order page only its customer can openStop an insecure direct object reference: check the session first, then answer 404 for any order that isn't the visitor's, in the page and in generateMetadata.
- A profile that shows each viewer what they may seeA data transfer object built field by field: public fields for all, the email for the member and staff, the staff note for staff only, never the hash.
- A profile form that can't make you staffA Server Action that reads only the two fields its form has, changes only the signed-in customer, and returns only what the form shows.
- An email change API that refuses other sitesA POST Route Handler that compares
OriginwithX-Forwarded-HostorHost, as Next.js does for Server Actions, and answers 403 before it reads the session. - Sort and search teas without SQL injectionA tea list page that sends the search to the database as a parameter and picks the ORDER BY from its own allow list, so nothing in the URL becomes SQL.
- A Content Security Policy with a fresh nonceA
proxy.tsthat makes a random nonce per request, sends a strict policy to the browser, and hands the nonce and policy to the app as request headers. - Verify a signed session in the data access layer
getSessionandverifySessionin a data access layer: check a signed cookie's HMAC, validate its payload and expiry, and never throw for a bad one. - Lock an account after five wrong passwordsA sign-in Server Action that counts failures per email in a shared store with expiry, locks for 15 minutes after five, and reveals no accounts.
Small apps
- A task list for the shop floorA to-do page in one Server Component: add, finish, and delete tasks through inline Server Actions, with a count and an empty state.
- A poll you can vote in onceA poll page that reads a cookie to choose between the vote form and the results, and a Server Action that counts a vote once and sets it.
- A journal that loads more as you scrollInfinite scroll in a Client Component: an IntersectionObserver at the end of the list calls a Server Action for the next page by cursor.
- A dashboard whose panels load and fail on their ownThree panels, each an async Server Component in its own Suspense and error boundary, so each streams in when ready and one failure stays in its panel.
- An order status that keeps itself up to dateA Client Component that calls router.refresh() every 15 seconds so the server sends the order's new status, pausing while the tab is hidden.
- Comments that appear before the server answersA comments section that adds a comment at once with useOptimistic, settles on the server's fresh list, and gives the text back when posting fails.
- Search suggestions as you typeA combobox that fetches suggestions from a Route Handler after a pause in typing, aborts stale requests, and moves with the arrow keys.
- A cart kept in a cookieServer Actions that add, change, and remove cart lines in a JSON cookie: read it as untrusted input, enforce stock limits, and delete it when empty.