Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 32 ยท Practice and review

Practice exercises with solutions

Ten hands-on Nuxt exercises on routing, data fetching, server routes, route rules and middleware, each with a runnable solution you can edit and test.

Reading about Nuxt only takes you so far. The ideas stick when you build something, get it wrong, and fix it. This lesson gives you ten exercises in five groups: file-based routing, server routes, data fetching, route rules and middleware. Each exercise states a small task, and a solution follows in a runnable editor.

Nuxt itself cannot run on this site, so each exercise is about the logic inside the framework: the part you can write as plain JavaScript and test with a few lines of output. If you can rebuild how Nuxt turns file names into routes, how it merges route rules or how a middleware chain stops, you understand it well enough to use it with confidence.

How to use this lesson. Read the exercise, close the solution, and try it in your own editor first. Run the solution, change an input, and break it on purpose. All solutions here are runnable stand-ins written in plain JavaScript, not Nuxt's real code, and they use simplified rules that match the behavior described in the earlier lessons.

Five groups, ten exercises

Routing File names to routes, and which route wins.
Server routes File names to methods, and safe handlers.
Fetching Keys, caching and request states.
Route rules Merging rules and stale-while-revalidate.

Middleware closes the set with chains and safe redirects.

1 / 2

Routing

Exercise 1: from file to route path

Nuxt builds routes from the files in pages/. Write fileToRoute(file) that turns a file path into the route path used by the router:

  • pages/index.vue is /
  • pages/about.vue is /about
  • pages/users/index.vue is /users
  • pages/users/[id].vue is /users/:id
  • pages/docs/[[section]].vue is /docs/:section? (optional parameter)
  • pages/blog/[...slug].vue is /blog/:slug(.*)* (catch-all)

Hint: remove the pages/ prefix and the .vue suffix, drop a trailing index, then convert each segment.

Exercise 2: which route wins?

Given a list of route paths and a URL, return the route that matches. When several routes match, the more specific one must win: a fixed segment beats a dynamic one, a dynamic one beats an optional one, and a catch-all comes last. Use the idea from Dynamic routes and params.

JS Solutions 1 and 2: file to route, and route matching

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

No output.

Check the interesting cases in the output. /users/new matches both /users/new and /users/:id, and the fixed route wins. /docs matches the optional parameter with no value. /blog/2026/hello is swallowed by the catch-all. And /nothing matches nothing, which is where Nuxt would show its 404 page.

Server routes

Exercise 3: from file name to method and path

In server/, the file name decides the HTTP method and the URL (Server routes and the Nitro engine). Write serverFile(file) returning { method, path }:

  • server/api/users/index.get.ts is GET /api/users
  • server/api/users/[id].put.ts is PUT /api/users/:id
  • server/api/ping.ts has no suffix, so it answers every method (ALL)
  • server/routes/health.get.ts is GET /health (the routes folder has no /api prefix)

Exercise 4: a safe list handler

Write a handler for GET /api/users?page=2&limit=3 over a fixed array of users. Rules: page defaults to 1 and is at least 1; limit defaults to 10 and is clamped between 1 and 50; bad numbers fall back to the defaults. Return { items, page, limit, total }. A second handler for /api/users/:id returns the user or throws a 404 error. Query values are always untrusted text.

JS Solutions 3 and 4: server files and a safe handler

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

No output.

The hostile query page=-5&limit=9999 ends up as page 1 with a limit of 50, so no one can ask your server for a million rows by editing the URL. That is the habit to take away: parse, clamp, and fall back, for every value that arrives from outside.

Data fetching

Exercise 5: keys and de-duplication

useAsyncData and useFetch use a key. Two calls with the same key share one request and one result, and refresh fetches again (Data fetching with useFetch and useAsyncData). Write createDataCache() with a function asyncData(key, fetcher) that returns the same promise for the same key, and a refresh(key, fetcher) that replaces it. Count how many real requests happen.

Exercise 6: pending, success and error

Write useRequest(fetcher) that returns an object with a status that is idle before it starts, pending while running, then success or error, plus data and error. Add an execute() method that can be called again to retry after an error.

JS Solutions 5 and 6: keys and request states

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

No output.

Notice the await pending line: the status is pending right after execute() starts and before it finishes, which is the moment your template shows a spinner. In real Nuxt, status also has the value idle for requests you start by hand with execute, and an error object you can show to the visitor. The retry works because execute resets the error and runs the fetcher again.

Route rules

Exercise 7: merge matching rules

routeRules map path patterns to settings. A request can match several patterns, and more specific patterns override general ones (Rendering modes: SSR, SPA, SSG, hybrid). Write rulesFor(path, routeRules) that supports /** wildcards and exact paths, merges all matching rules, and lets the pattern with the longer fixed prefix win each conflict.

Exercise 8: stale-while-revalidate

A rule such as { swr: 60 } means: serve the cached page, and when it is older than 60 seconds serve the stale copy once while refreshing it in the background. Write a small cache with a fake clock that returns MISS, HIT or STALE for each request, so you can see the timeline.

JS Solutions 7 and 8: merged rules and SWR

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

No output.

In the first output, /blog/draft/idea gets swr: false from the more specific rule, even though /blog/** says 3600, and it also inherits the security header from /**. That "specific wins, general fills the gaps" idea is exactly how you read real routeRules. In the second output, the visitor at 61 seconds is not made to wait for a render: they get the old page at once, and the visitor after them gets the new one.

Middleware

Exercise 9: a middleware chain

Route middleware runs in a fixed order: global middleware first, in alphabetical order of file name, then the middleware named in the page. Each middleware may return nothing (continue), a path (redirect there), or false (abort the navigation). Write runMiddleware(chain, to, from) that stops at the first middleware that returns something (Navigation and route middleware).

Exercise 10: an auth guard with a safe redirect

Write an auth middleware that sends signed-out visitors to /login?redirect=<where they wanted to go>, and a safeRedirect(value) function for the login page that accepts only local paths. //evil.example and https://evil.example must fall back to /dashboard.

JS Solutions 9 and 10: the chain and the safe guard

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

No output.

Notice the order in the output: the log middleware always runs first because its file name sorts first, and the chain stops at the first redirect or abort, so later middleware never runs. Without the // check in safeRedirect, a link such as /login?redirect=//evil.example would send a freshly signed-in visitor to another site: always treat a redirect target as untrusted input.

Where to go next

If an exercise felt hard, go back to the matching lesson, read it again, and then redo the exercise from scratch. Good follow-ups: add a unit test for each solution (Testing Nuxt apps), extend the route matcher with validate, or build one of the projects (Project: a blog with Nuxt Content style Markdown).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A URL matches both /users/new and /users/:id. Which route should win?

    Routers rank static segments above dynamic ones, so the fixed route /users/new wins.
  2. 2. Why does the list handler clamp limit between 1 and 50 instead of using the value from the URL?

    Anything in the URL can be edited. Clamping keeps cost and response size under your control.
  3. 3. What does { swr: 60 } do for a request that arrives 70 seconds after the page was cached?

    Stale-while-revalidate trades a little freshness for speed: the old page is sent at once and the next visitor gets the new one.
  4. 4. In a middleware chain, what happens after one middleware returns a redirect path?

    The first middleware that returns a redirect or abort result ends the chain, so later middleware never runs.
  5. 5. Why must safeRedirect reject values that start with //?

    //evil.example is read by browsers as a link to another host. Only a single leading slash is a local path.

Summary

  • File names are configuration: you practiced turning pages/ files into route paths and server/ files into methods and URLs.
  • Specific routes beat dynamic ones, and dynamic ones beat catch-alls.
  • Parse, clamp and default every query value, because it comes from outside.
  • Keys make useAsyncData share and cache requests, and refresh runs them again. A request has the states idle, pending, success and error.
  • Route rules merge, and the most specific pattern wins each conflict. swr serves stale pages while refreshing.
  • Middleware runs in order and stops at the first redirect or abort. Treat redirect targets as untrusted.

Next: Nuxt interview questions