โฑ๏ธ Estimated read: 4 min
|
|
Project & Scripts
| Command | Purpose |
|---|
npx nuxi init my-app | Scaffold a project |
npm run dev | Dev server with HMR |
npm run build | Client + Nitro build into .output/ |
npm run generate | Build + full prerender (static) |
npm run preview | Serve the built .output/ locally |
npx nuxi prepare | Regenerate .nuxt/ types |
npx nuxi module add <name> | Install + register a module |
Directory Map
| Path | Role |
|---|
app.vue | Root component, holds <NuxtLayout> / <NuxtPage> |
pages/ | File-based routes |
components/ | Auto-imported components |
composables/ | Auto-imported composables |
server/api/ | Nitro API handlers |
server/middleware/ | Server-side request middleware |
middleware/ | Client/SSR route middleware |
layouts/ | Named layouts |
plugins/ | Vue plugins, .client / .server suffixes |
assets/ | Bundled, processed files |
public/ | Served as-is at / |
error.vue | Global error page (root, not pages/) |
app.config.ts | Reactive non-secret app config |
nuxt.config Essentials
export default defineNuxtConfig({
compatibilityDate: '2025-01-01',
devtools: { enabled: true },
modules: ['@nuxtjs/tailwindcss', '@nuxt/content'],
extends: ['../shared-layer'],
runtimeConfig: {
apiSecret: '', // server only, set via NUXT_API_SECRET
public: { apiBase: '/api' } // shipped to the browser
},
app: { head: { title: 'App' } },
routeRules: { '/blog/**': { isr: 3600 } },
nitro: { preset: 'node-server' }
})
Core Composables
| API | Returns / Use |
|---|
useNuxtApp() | Nuxt instance, hooks, payload |
useRouter() / useRoute() | Router instance / matched route |
useFetch(url, opts) | SSR-aware fetch, reactive |
useAsyncData(key, handler) | Custom async data with dedupe |
$fetch(url, opts) | Raw $ofetch instance |
useRuntimeConfig() | Resolved runtime config |
useRequestHeaders(['cookie']) | Forward headers on SSR |
useRequestEvent() | Current H3 event |
useState(key, init) | SSR-safe shared state |
useCookie(name, opts) | Universal cookie ref |
useHead() / useSeoMeta() | Head tags / meta |
navigateTo(path, opts) | Redirect + external, replace |
definePageMeta({}) | Per-page layout, middleware, SSR |
Data Fetching Pattern
const { data, pending, error, refresh } = await useFetch('/api/posts', {
key: 'posts', // dedupe + cache key
transform: (r) => r.slice(0, 10), // runs on both server and client
server: true, lazy: false, immediate: true
})
if (error.value) throw createError({ statusCode: 500, fatal: true })
Pages & Routing
| File | Route |
|---|
pages/index.vue | / |
pages/blog/[slug].vue | /blog/:slug |
pages/blog/[...slug].vue | Catch-all |
pages/[[...slug]].vue | Optional catch-all / 404 |
pages/about/index.vue | /about |
definePageMeta({
layout: 'admin', middleware: ['auth'], ssr: false,
validate: (route) => /^\d+$/.test(route.params.id as string)
})
Components
<NuxtLayout name="default">
<NuxtPage />
<NuxtErrorBoundary>
<Sidebar />
<template #error="{ error, clearError }">{{ error.message }}</template>
</NuxtErrorBoundary>
</NuxtLayout>
| Built-in | Purpose |
|---|
NuxtLink | Prefetching router link |
NuxtPage | Renders matched page |
NuxtLayout | Wraps a named layout |
NuxtErrorBoundary | Local error fallback |
NuxtLoadingIndicator | Route progress bar |
<ClientOnly> | Client-only render slot |
Server (H3)
// server/api/users/[id].ts
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id') // path param
const q = getQuery(event) // ?query
const body = await readBody(event) // POST body
const cookie = getCookie(event, 'session')
if (!id) throw createError({ statusCode: 400, statusMessage: 'Bad id' })
return { id }
})
| Helper | Use |
|---|
defineEventHandler | Register a handler |
createError({ statusCode }) | HTTP error, sets response code |
sendRedirect(event, to, 302) | Redirect |
setHeader(event, k, v) | Response header |
event.context | Per-request state |
setResponseStatus(event, 401) | Set status code |
Middleware
// middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
if (!useCookie('session').value) return navigateTo('/login')
})
Global: middleware.ts at root. Named: file name. Per-page: definePageMeta({ middleware: 'auth' }).
Quick How-To Guides & Fast FixesNeed a quick fix or step-by-step solution? Browse our fast answers on HowTo.KandZ.me:
Plugins
// plugins/chart.client.ts (client only)
export default defineNuxtPlugin((nuxtApp) => {
return { provide: { chart: () => import('chart.js') } }
})
| Suffix | Runs on |
|---|
.client.ts | Browser only |
.server.ts | Server only |
| none | Both |
Access with useNuxtApp().$chart after provide.
Errors
| API | Context | Effect |
|---|
throw createError({ statusCode, fatal }) | Both | SSR status code / client page |
showError({ statusCode }) | Client | Jump to error.vue |
clearError({ redirect: '/' }) | Client | Reset + navigate |
useError() | Client | Read current error |
error.vue | Root | Global fallback, receives error prop |
Modules & Layers
// nuxt.config.ts
extends: ['../base-layer', 'github:org/theme#v1']
modules: ['@nuxt/content', './modules/analytics']
| Concept | Scope |
|---|
Layer (extends) | File-system merge: pages, components, css |
| Module | Build-time logic via @nuxt/kit |
defineNuxtModule | Module wrapper with meta + setup |
createResolver | Path resolution relative to module file |
addPlugin / addComponent | Inject runtime pieces |
nuxt.hook('build:done') | Lifecycle integration |
Build & Deploy
| Preset | Runtime | Notes |
|---|
node-server | Node process | Default, containers/VPS |
static | Files only | Requires nuxt generate |
vercel | Vercel functions | Serverless |
netlify | Netlify functions | Serverless |
cloudflare-pages | workerd | Edge, no fs |
cloudflare-module | workerd | Workers module |
| Env var | Meaning |
|---|
NITRO_PRESET | Override preset at build |
NUXT_ prefix | Maps to runtimeConfig keys |
NUXT_PUBLIC_* | Maps to runtimeConfig.public |
PORT / HOST | Node server listen address |
NITRO_PRESET=cloudflare-pages nuxt build
nuxt preview # always verify the built artifact
SEO / Head
useSeoMeta({ title: 'Home', description: 'Docs', ogImage: '/og.png' })
useHead({ link: [{ rel: 'canonical', href: 'https://x.dev' }] })
Testing
| Tool | Use |
|---|
environment: 'nuxt' | Vitest env with Nuxt context |
mountSuspended | Mount component, awaits Suspense |
mockNuxtImport | Stub an auto-import |
@nuxt/test-utils/e2e setup | Boot real server |
$fetch / url | Assert against built app |
createPage | Playwright browser test |
Quick Rules
| Do | Don’t |
|---|
useRuntimeConfig() in handlers | process.env.X at module top level |
clearError({ redirect }) | router.push after an error |
createError({ statusCode }) | throw new Error() for HTTP codes |
await mountSuspended() | sync mount() on Nuxt components |
| Secrets at top level of runtimeConfig | Secrets under public |
nuxt preview before deploy | nuxt dev as a deployment check |
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!