Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 32 ยท Practice and review

Nuxt Cheat Sheet

A one-page Nuxt 4 cheat sheet: folder-to-feature map, key composables, nuxt.config keys, routeRules, CLI commands and server helpers, with runnable stand-ins for routes and rules.

This is the page to keep open in a tab. It does not replace the lessons; every section links to the one that explains the idea in full. Think of it as a map: you will already know most of what is on it, and when you do not, you will know where to read.

It targets Nuxt 4, where application code lives in app/ and server/ stays at the project root. In a Nuxt 3 project without an app/ folder, the same folders sit at the root. The real framework cannot run on this site, so the code blocks are read-only. Two small stand-ins in plain JavaScript model how routes and routeRules behave; they are not Nuxt itself.

Four places your code lives

app/ Pages, components, layouts, composables.
server/ API routes, middleware, utils.
public/ Files served exactly as they are.
nuxt.config.ts Modules, routeRules, runtime config.

Everything else is generated or optional.

1 / 2

Folder to feature map

Folder or file What it gives you Lesson
app/pages/ File-based routes (index.vue, [id].vue, [...slug].vue) Routing
app/layouts/ Page frames, chosen with definePageMeta({ layout }) Layouts
app/components/ Auto-imported components (Lazy prefix, .client and .server suffixes) Components
app/composables/ Auto-imported useXxx functions Auto-imports
app/utils/ Auto-imported helpers Auto-imports
app/middleware/ Route middleware (name.vue, name.global.ts) Middleware
app/plugins/ Code that runs once at app start (defineNuxtPlugin) Plugins
app/assets/ Files processed by the bundler (CSS, images) Head, SEO and assets
app/app.vue, app/error.vue Root component, global error page Layouts
app/app.config.ts Build-time, public, reactive settings (useAppConfig) Runtime config
server/api/ Endpoints under /api (name.get.ts, [id].put.ts) Server routes
server/routes/ Endpoints at exact paths (/sitemap.xml) Server routes
server/middleware/ Code that runs on every request Server middleware
server/utils/ Auto-imported server helpers Server middleware
server/plugins/ Nitro plugins and hooks Server middleware
public/ Static files at the site root (/favicon.ico) Head, SEO and assets
layers/ Local layers you extend Layers
nuxt.config.ts Project configuration Project structure
.nuxt/, .output/ Generated dev files and the production build (do not edit) Deployment

Routes from file names

File Route
pages/index.vue /
pages/about.vue /about
pages/blog/index.vue /blog
pages/blog/[slug].vue /blog/:slug
pages/users/[[id]].vue /users/:id? (optional)
pages/docs/[...path].vue /docs/* (catch-all)
pages/account.vue plus pages/account/ folder Parent route, children render in <NuxtPage />
JS Stand-in: from file path to route

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

No output.

The patterns on the right use the Vue Router syntax that Nuxt generates. See file-based routing and dynamic routes.

Composables you reach for daily

Composable Use it to Note
useFetch(url, opts) Fetch data in a page or component SSR-safe, reuses the payload
useAsyncData(key, fn) Wrap any async function Key identifies the data
$fetch(url) Call an API from an event handler or server code Not for top-level setup
useState(key, init) Shared, request-scoped, serializable state Never a module-level ref
useCookie(name) Read and write a cookie on both sides Reactive
useRoute() / useRouter() Params, query, programmatic navigation
navigateTo(path) Redirect or navigate Return it from middleware
abortNavigation() Cancel a navigation Return it from middleware
useHead() / useSeoMeta() Title, meta and link tags See Head and SEO
useRuntimeConfig() Read runtime config Public keys only in the browser
useRequestHeaders() Forward incoming headers Server-side use
refreshNuxtData(key) Refetch data by key
clearError() / showError() Control the error page
definePageMeta() Layout, middleware, validate, name Compiler macro, top of <script setup>
defineNuxtComponent, defineNuxtPlugin, defineNuxtRouteMiddleware Typed helpers for each file kind

Options of useFetch and useAsyncData worth remembering: lazy, server, default, transform, pick, watch, immediate. The result holds data, status, pending, error, refresh, execute and clear. See data fetching.

VUE
<script setup lang="ts">
const route = useRoute()
const { data: post, status, error } = await useFetch(() => `/api/posts/${route.params.slug}`)
useSeoMeta({ title: () => post.value?.title ?? 'Loading' })
</script>

Server helpers (h3 and Nitro)

Helper Purpose
defineEventHandler(fn) An endpoint or middleware
getQuery(event) Parsed query string
readBody(event) Parsed request body
getRouterParam(event, 'id') A path parameter
getHeader, setHeader, getCookie, setCookie Headers and cookies
setResponseStatus(event, 201) Response status
createError({ statusCode, statusMessage }) Throw an HTTP error
sendRedirect(event, '/x') Redirect from the server
defineCachedEventHandler(fn, { maxAge }) A cached endpoint
useStorage() Nitro storage layer
useRuntimeConfig(event) Config inside handlers
TypeScript
// server/api/posts/[id].get.ts
export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id')
  const post = await findPost(id)
  if (!post) {
    throw createError({ statusCode: 404, statusMessage: 'Not found' })
  }
  return post
})

File suffixes choose the method: .get.ts, .post.ts, .put.ts, .patch.ts, .delete.ts. A file with no suffix answers every method. See server routes.

Common nuxt.config.ts keys

Key Purpose
modules Nuxt modules to load
css Global stylesheets
ssr Server rendering on (default) or off
routeRules Per-route rendering and caching
runtimeConfig Server secrets; public is sent to the browser
app.head Defaults for title and meta tags
nitro Engine options: preset, prerender, storage
extends Layers to build on
devtools Toggle the Nuxt DevTools
compatibilityDate Pins platform defaults to a date
imports, components Tune auto-import scanning
vite Pass options to the bundler
TypeScript
export default defineNuxtConfig({
  compatibilityDate: '2025-07-15',
  modules: ['@pinia/nuxt'],
  runtimeConfig: {
    apiSecret: '',            // server only, NUXT_API_SECRET
    public: { apiBase: '/api' }, // also in the browser, NUXT_PUBLIC_API_BASE
  },
})

Environment variables override runtimeConfig keys at runtime using the NUXT_ prefix (and NUXT_PUBLIC_ for public keys). See runtime config and environment variables.

routeRules

Rule Effect
prerender: true Build the page to a static file at build time
ssr: false Skip server rendering, serve an SPA shell
swr: 600 Cache the render, revalidate in the background after 600 s
isr: 600 Like SWR, using the host's cache (Vercel, Netlify)
cache: { maxAge: 60 } Cache the response in Nitro storage
redirect: '/new' Redirect (a string, or an object with to and statusCode)
headers: { ... } Add response headers
cors: true Add permissive CORS headers

Patterns use * for one segment and ** for any depth. When several patterns match a path, their rules are combined and the more specific pattern wins on conflicts. The stand-in below models that merge with a simplified matcher, ordering patterns by length. Nuxt's real matcher is more capable, so treat this as an illustration.

Node.js Stand-in: which rules apply to which path

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 /blog/drafts/idea: it inherits swr from /blog/** and adds ssr: false from the more specific pattern. See rendering modes.

CLI commands

Command Purpose
npm create nuxt@latest my-app Create a project
npx nuxt dev Start the dev server with hot reload
npx nuxt build Build for production into .output/
npx nuxt generate Prerender the whole site for static hosting
npx nuxt preview Serve the production build locally
npx nuxt prepare Generate types in .nuxt/ (run after install)
npx nuxt typecheck Run the type checker (needs vue-tsc and typescript)
npx nuxt analyze Inspect bundle size
npx nuxt module add <name> Install and register a module
npx nuxt upgrade Upgrade Nuxt
npx nuxt cleanup Remove generated folders
npx nuxt info Print versions for bug reports

The same commands also exist under the older nuxi name. The production server starts with node .output/server/index.mjs for the default Node preset. See deployment.

Quick rules of thumb

  • Fetch in components with useFetch; use $fetch for clicks and submits.
  • Put shared state in useState; never in a module-level ref.
  • Make the first client render match the server HTML; browser-only values go in onMounted or <ClientOnly>.
  • Secrets live in private runtimeConfig only, and every API route checks authorization itself.
  • Choose rendering per route with routeRules instead of one mode for the whole site.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file creates the endpoint PUT /api/users/:id?

    Files in server/api are served under /api, brackets make a parameter and the .put suffix limits the handler to the PUT method.
  2. 2. Where do you declare a secret that must never reach the browser?

    Top-level runtimeConfig keys are server-only; only keys under public are sent to the browser, and app.config.ts is public too.
  3. 3. A path matches both /blog/** with swr and /blog/drafts/** with ssr false. What happens?

    Matching rules are merged. The more specific pattern wins where they disagree, so this path gets swr from the first and ssr false from the second.
  4. 4. Which command produces static files for every route?

    nuxt generate prerenders the site so it can be hosted on any static host. Preview only serves a finished build, and prepare only generates types.

Summary

  • app/ is the front end, server/ is the API and Nitro code, public/ is served as-is, nuxt.config.ts ties it together.
  • File names decide routes ([id], [[id]], [...path]) and server endpoints (name.get.ts).
  • useFetch, useAsyncData, useState and useCookie are the SSR-safe building blocks; $fetch belongs in handlers.
  • runtimeConfig keeps secrets private; NUXT_ environment variables override it at runtime.
  • routeRules picks prerender, SWR, SPA, cache or redirect behavior per path pattern.
  • The CLI covers dev, build, generate, preview, prepare, analyze and module add.

Test your knowledge with the Nuxt interview questions, or revisit the introduction.