Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 72 ยท Practice and Interviews

Exercises with Solutions

Ten Next.js exercises with runnable solutions on routing, the server and client boundary, caching, Server Actions and forms, plus hints you can open when stuck.

Reading about the App Router builds vocabulary. Solving small problems builds judgment. This page has ten exercises that cover the ideas people get wrong most often: how a URL finds a file, which components belong on the server, how caches decide when to refetch, and how actions validate input. Each one is small enough to finish in about ten minutes.

Next.js itself cannot run on this site, so the exercises ask you to rebuild the logic behind the framework in plain JavaScript or React. That is a good way to learn: once you have written a route matcher or a tag-based cache yourself, the real thing stops being magic. Every solution is runnable, and the lines it prints are the expected output.

Try each exercise on paper or in your own editor first. Open the hint if you are stuck for five minutes, and only then open the solution. If you want a refresher before starting, the lessons are linked in every section.

How the exercises are organized

Four areas, ten problems

Routing Exercises 1 to 3.
Boundary Exercises 4 and 5.
Caching Exercises 6 to 8.
Actions Exercises 9 and 10.

Within each area the problems get harder.

1 / 2

Routing

These problems use file-based routing, dynamic routes, catch-all routes and the proxy matcher.

1. Map a URL to a file (Easy)

Write matchRoute(url, routes). Each route is a path such as /blog/[slug]. Return { route, params } for the first route that matches the URL, or null. A [name] segment matches exactly one URL segment and stores it in params.

Show hint

Split both the URL and the route on / and drop empty pieces. If the lengths differ, it cannot match. Then compare segment by segment: a segment wrapped in square brackets always matches and writes to params; any other segment must be equal.

Show solution
Node.js Exercise 1: matchRoute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first match wins here, which is why the next exercise matters: real routers need a notion of which match is best.

2. Which file wins? (Medium)

Extend the matcher so that several routes can match one URL and the most specific one is chosen. Support [name], [...rest] (one or more segments) and [[...rest]] (zero or more). A static segment beats a dynamic one, which beats a catch-all.

Show hint

Give each matched segment a score: static 3, dynamic 2, required catch-all 1, optional catch-all 0. A catch-all swallows the rest of the URL, so it ends the loop. Compare candidates by their score lists, position by position, and keep the higher one at the first position where they differ.

Show solution
Node.js Exercise 2: route priority

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare with the rules in Catch-All and Optional Catch-All Routes. The optional form is the only one that also matches the bare /files.

3. Write a proxy matcher (Medium)

Write runsFor(path, matcher). The matcher is a list of patterns: an exact path such as /login, or /admin/:path*, which matches /admin and everything below it. Return true when the proxy would run. Then add an exclude list for prefixes such as /api and /_next.

Show hint

For /admin/:path*, remove the suffix /:path* to get the base /admin. The path matches if it equals the base or starts with the base followed by a slash. Check the exclusions first.

Show solution
Node.js Exercise 3: matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that /administrator does not match: the base must be followed by a slash. The real config.matcher uses a richer syntax, but the idea is the same, and a narrow matcher keeps the proxy off the hot path for static files.

The server and client boundary

These problems practise Server Components, Client Components and composition.

4. Server, client, or both? (Easy)

Write verdict(component) that takes a description such as { name, uses: [...] } and returns server, client, or split (a server parent with a small client child). Hooks for state or effects, event handlers and browser APIs force the client. Database, secret keys and the file system need the server.

Show hint

Make two lists of features, one for each side, and use filter to find which a component uses. If both are non-empty, the answer is split; the fix is to keep the data work on the server and move only the interactive part into a child.

Show solution
Node.js Exercise 4: where does it run?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The default is the server. Choosing client should always have a reason you can point to, as explained in Client Components and "use client".

5. Keep the children out of the update (Medium)

Write a Collapsible component with a toggle button that shows or hides its children. The expensive Note is created by the parent and passed in. Open and close the panel several times and check the console: Note should log its render only once. This is the pattern behind "pass Server Components as children of a Client Component".

Show hint

State lives in Collapsible, but the <Note /> element is created in App, which does not re-render. When Collapsible's state changes, React reuses the same element object it received as children, so Note is not called again. Do not create <Note /> inside Collapsible.

Show solution
Exercise 5: children survive state changes

When the panel is hidden, Note unmounts, and showing it again renders it once more. That is normal: the point is that the toggle's own state change does not force the children to run. With real Server Components, the children are rendered on the server and arrive as ready-made output, so no component code is sent to the browser at all.

Caching

These problems rebuild the ideas from Caching in Next.js, The use cache Directive, Revalidating Data and Static vs Dynamic Rendering.

6. A cache with a lifetime (Easy)

Write cached(key, ttl, load). On a miss it calls load(), stores the value and an expiry time, and returns it. On a hit that has not expired, it returns the stored value without calling load(). Use a fake clock so you can move time forward.

Show hint

Store { value, expires: now + ttl }. A hit is valid while expires > now. After expiry, treat it exactly like a miss.

Show solution
Node.js Exercise 6: TTL cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

At t=60 the entry has just expired (expires > now is false), so the data is loaded again. This is the shape of cacheLife and revalidate: 60.

7. Revalidate by tag (Medium)

Add tags. cached(key, tags, load) stores the tags with each entry (no expiry this time). revalidateTag(tag) removes every entry that carries the tag and returns how many it removed. Show that updating one product only drops that product and the product list.

Show hint

Store { value, tags }. In revalidateTag, loop over the map and delete entries whose tags array includes the tag. Deleting from a Map while iterating over it is safe in JavaScript.

Show solution
Node.js Exercise 7: tag-based invalidation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The specific tag product-1 invalidates one entry. The shared products tag drops three entries at once but leaves about untouched. Note that in the real framework, since version 16 revalidateTag takes a cache profile as a second argument and serves stale data while refreshing in the background. The deletion here is the simplest model of "make the entry miss next time".

8. Static or dynamic? (Medium)

A route is rendered dynamically (per request) when it reads request data or opts in. Write renderMode(route) returning static or dynamic plus the reasons. Request data means cookies, headers, searchParams and connection. A route also becomes dynamic with dynamic = 'force-dynamic'.

Show hint

Collect reasons in an array. Map each request-data API that appears in route.uses to a short reason, and add one more when the dynamicConfig field is 'force-dynamic'. No reasons means static.

Show solution
Node.js Exercise 8: how Next decides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

/blog/[slug] stays static when its parameters are known at build time with generateStaticParams, as covered in Static Generation. With Cache Components enabled, the model changes: instead of a whole route being dynamic, only the part that reads request data becomes a dynamic hole in a static shell.

Server Actions and forms

These problems use Server Actions, forms with actions and validation.

9. Validate on the server (Easy)

Write the logic of a createPost(previousState, formData) action. Trim the fields, then require a title of 3 to 80 characters and a body of at least 10. Return { ok: false, errors, values } on failure (so the form can keep what the user typed) or { ok: true, id } with a slug on success.

Show hint

Never trust the form: read each field with String(formData.get('title') ?? '') so a missing field cannot crash you. Build an errors object field by field, and return early if it has any keys.

Show solution
Node.js Exercise 9: createPost validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same function is safe to call from a form, a script or a hand-made curl request, which is exactly why the checks belong on the server. A client-side check is only a courtesy to the user.

10. A form with pending state (Medium)

Build a newsletter form with React 19's useActionState. The action waits briefly, then returns either { error, email } for an invalid address or { message } on success. Show the error or message, keep the typed email after an error, and disable the button while the action is pending.

Show hint

useActionState(action, initialState) returns [state, formAction, pending]. Pass formAction to the form's action prop. React resets uncontrolled fields after an action, so restore the text with defaultValue={state.email ?? ''}.

Show solution
Exercise 10: useActionState

In a real Next.js app the subscribe function would carry 'use server' and live in its own file, and React would send the form data to the server instead of calling it in the browser. The form component stays the same. That is the idea behind progressive enhancement, covered in Server Actions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two routes match /docs/intro: /docs/intro and /docs/[topic]. Which does Next.js choose?

    More specific routes win: static segments beat dynamic segments, which beat catch-all segments.
  2. 2. A component needs both a database query and an onClick handler. What is the usual fix?

    Splitting keeps secrets and data access on the server and sends only the small interactive piece to the browser.
  3. 3. Why does Note render only once in exercise 5 when the toggle state changes?

    Collapsible re-renders, but the children prop still points to the same element object, so React skips it.
  4. 4. Which of these makes a route dynamic?

    Reading request data such as cookies, headers or search parameters ties the output to the request, so it cannot be prerendered once for everyone.
  5. 5. Why validate form input inside a Server Action even if the browser already validated it?

    Anyone can post to an action without your form. Client checks help users, server checks protect you.

Summary

  • A router picks the most specific matching route: static, then dynamic, then catch-all.
  • Everything is a Server Component by default. Add 'use client' only for state, effects, events and browser APIs, and keep the client part small.
  • Elements passed as children are created by the parent, so a Client Component's own state changes do not re-run them.
  • A cache needs a lifetime (cacheLife, revalidate) or tags (cacheTag, revalidateTag) so stale data can be replaced.
  • Reading cookies, headers or search parameters makes a route dynamic.
  • Validate and trim every input on the server, return field errors, and keep the user's values for the next render.

Next: Next.js Interview Questions