completefrontend
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

  1. 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.Easy
  2. 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.Easy
  3. An error screen that can retryapp/teas/error.tsx: a Client Component that shows a safe message and the error's digest, reports it once, and calls retry.Easy
  4. Tea list filtered, sorted, and paged by the URLapp/teas/page.tsx reads its awaited searchParams to filter, sort, and paginate, with safe defaults for bad values and links that keep the rest.Medium
  5. Tea pages under their categoryapp/shop/[category]/[slug]/page.tsx: two dynamic segments, both filled by generateStaticParams, with a 404 for unknown teas and a 308 to the right category.Medium
  6. A home page without a waterfallapp/page.tsx waits for three slow queries one after another. Start them together with Promise.all, so the page is ready when the slowest is.Medium
  7. 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.Hard
  8. 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.Hard

Links & client navigation

  1. Nav links that show where you areA Client Component header nav that marks the current page and section with usePathname, aria-current, and an active class.Easy
  2. Tea page tabs in the URLTabs made of links that keep the open tab in ?tab=, switching with replace and scroll={false} and keeping the other params.Easy
  3. 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.Easy
  4. Tea search in the URLA Client Component search box that keeps what you type in the URL's q, with useRouter, usePathname, and useSearchParams.Medium
  5. Tea type filters as repeated paramsCheckboxes kept in the URL as ?type=green&type=oolong: read with getAll, written in one order, and pushed so Back undoes each change.Medium
  6. Warn before leaving an unsaved noteBlock Link navigation with onNavigate while a tasting note is unsaved, never ask on a Ctrl-click, and cover reloads with beforeunload.Medium
  7. 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.Hard
  8. Sign in, then back to next, safelyA sign-in form that returns to ?next= with router.replace, behind a safeNextPath guard that refuses every way off the site.Hard

Server & Client Components

  1. 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.Easy
  2. 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.Easy
  3. 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.Easy
  4. 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.Medium
  5. 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.Medium
  6. 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.Medium
  7. 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.Hard
  8. 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.Hard

Route Handlers

  1. Tea search APIA GET Route Handler that filters and sorts the teas from the query string, and answers 400 for a query it can't use.Medium
  2. One order by its idA dynamic GET Route Handler that awaits its params, and answers 400 for an id that isn't a whole number and 404 for an order that isn't there.Easy
  3. Short links that redirectA GET Route Handler that looks up a short code and redirects with NextResponse.redirect, keeping the link's search params, or answers 404.Easy
  4. A price list to download as CSVA GET Route Handler at /price-list.csv that answers a CSV file with the right headers, quoting the fields that need it.Easy
  5. Create a review with POSTA POST Route Handler that checks the tea, the Content-Type, and the JSON body, then answers 201 with a Location, or 404, 415, or 400.Medium
  6. A tea API that answers 304 Not ModifiedA GET Route Handler that sends an ETag and answers 304 with no body when If-None-Match shows the app already has the latest tea.Medium
  7. Edit and delete your own reviewsGET, PATCH, and DELETE in one route.ts: a bearer token for changes, 401, 403, and 404 in the right order, and 204 for a delete.Medium
  8. 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.Hard
  9. Rate-limit the newsletter sign-upA fixed-window rate limit per client in a Route Handler: X-RateLimit-* headers, and 429 with Retry-After once a client has used up its window.Hard

Server Actions & forms

  1. 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.Easy
  2. 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.Easy
  3. 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.Easy
  4. Tea review Server ActionA Server Action that checks a review form's fields, saves it, revalidates the tea's page, and redirects there.Medium
  5. 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.Medium
  6. 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.Medium
  7. 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.Medium
  8. 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.Hard
  9. 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.Hard

proxy.ts

  1. Send signed-out visitors to sign inA proxy.ts that runs for /account and the pages under it, and redirects a visitor without a session cookie to /sign-in?next=….Easy
  2. Password-protect the staging siteHTTP Basic authentication in proxy.ts: decode the Authorization header, compare safely, and answer 401 with WWW-Authenticate straight from the proxy.Easy
  3. A request id for the page and the browserForward an x-request-id header to the app with NextResponse.next({ request: { headers } }), and send the same id to the browser on the response.Easy
  4. Send each visitor to their languageRedirect paths without a language to /en or /fr, picked from a NEXT_LOCALE cookie or the weights in Accept-Language.Medium
  5. 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-a or /home-b while the address stays /.Medium
  6. Run proxy.ts for pages onlyWrite the config.matcher that keeps proxy.ts away from the API, Next.js's files, metadata files, images, and prefetches, but not from /apiary.Medium
  7. A shop on every tea house's own addressRead the host header, rewrite tea houses' subdomains and custom domains to /sites/<tenant>, and answer 404 for unknown hosts and /sites.Hard
  8. Maintenance mode with a way in for staffRewrite pages to /maintenance, answer the API with 503 and Retry-After, keep an allow-list open, and let staff in with a preview link that becomes a cookie.Hard

Metadata & SEO files

  1. A robots.txt that keeps staging out of searchapp/robots.ts that lets crawlers into the shop but not /account or /checkout, names the sitemap, and shuts every other deploy.Easy
  2. A web app manifest to install the shopapp/manifest.ts with the shop's names and colors, a standalone window, a stable id, and its icons sized and marked any or maskable.Easy
  3. Titles, descriptions, and social cards for tea pagesgenerateMetadata for each tea: its title, a description cut at a word, a canonical URL, an Open Graph card, and noindex for retired teas.Medium
  4. A sitemap built from the teas and the journalapp/sitemap.ts from the database: full URLs, no retired teas or drafts, and each page's lastModified taken from when its content changed.Medium
  5. 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.Medium
  6. hreflang links between English and French tea pagesgenerateMetadata for a tea page in two languages: hreflang links both ways, a canonical of its own, Open Graph locales, and redirects for the wrong slug.Hard

Caching & revalidation

  1. 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.Easy
  2. 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.Easy
  3. 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.Medium
  4. 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.Medium
  5. 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.Medium
  6. 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.Hard

Auth & security

  1. 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.Easy
  2. 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.Easy
  3. 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.Easy
  4. An email change API that refuses other sitesA POST Route Handler that compares Origin with X-Forwarded-Host or Host, as Next.js does for Server Actions, and answers 403 before it reads the session.Medium
  5. 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.Medium
  6. A Content Security Policy with a fresh nonceA proxy.ts that 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.Medium
  7. Verify a signed session in the data access layergetSession and verifySession in a data access layer: check a signed cookie's HMAC, validate its payload and expiry, and never throw for a bad one.Hard
  8. 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.Hard

Small apps

  1. 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.Easy
  2. 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.Easy
  3. 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.Medium
  4. 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.Medium
  5. 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.Medium
  6. 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.Medium
  7. 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.Hard
  8. 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.Hard