","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-1","name":"Pinia store module: Composition API pattern with actions and getters","description":"Code example","text":"// stores/product.ts\nimport { defineStore } from 'pinia'\n\nexport const useProductStore = defineStore('product', () => {\n const products = ref([])\n const filters = reactive({ category: '', priceMin: 0, priceMax: 999999 })\n \n const filteredProducts = computed(() => \n products.value.filter(p => \n (!filters.category || p.category === filters.category) &&\n p.price >= filters.priceMin &&\n p.price <= filters.priceMax\n )\n )\n \n const fetchProducts = async (query = {}) => {\n products.value = await $fetch('/api/products', { query })\n }\n \n const setFilter = (key, value) => {\n filters[key] = value\n }\n \n const addProduct = (product) => {\n products.value.push(product)\n }\n \n return { products, filters, filteredProducts, fetchProducts, setFilter, addProduct }\n})\n\n// pages/products.vue\nconst store = useProductStore()\nawait store.fetchProducts()\nconst filtered = computed(() => store.filteredProducts)","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-2","name":"Route-based code splitting: Lazy-load heavy components dynamically","description":"Code example","text":"// pages/dashboard.vue\nconst HeavyChart = defineAsyncComponent(() => import('~/components/Chart.vue'))\nconst Analytics = defineAsyncComponent(() => import('~/components/Analytics.vue'))\n\n// In template with Suspense fallback\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-3","name":"Advanced middleware composition: Multi-step authentication flow","description":"Code example","text":"// middleware/admin.ts\nexport default defineRouteMiddleware(async (to, from) => {\n const user = useAuthStore()\n const hasPermission = usePermissionStore()\n \n if (!user.isAuthenticated) {\n return navigateTo('/login')\n }\n \n if (to.path.startsWith('/admin')) {\n const canAccess = await hasPermission.checkAdminAccess(user.id)\n if (!canAccess) {\n return navigateTo('/forbidden')\n }\n }\n})\n\n// pages/admin/dashboard.vue\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-4","name":"Server-side caching with routeRules: SWR and ISR strategies","description":"Code example","text":"// nuxt.config.ts\nexport default defineNuxtConfig({\n routeRules: {\n // Prerendered static pages\n '/': { prerender: true },\n '/about': { prerender: true },\n \n // SWR: Cache 1 hour, serve stale while revalidating\n '/blog/**': { swr: 3600 },\n '/products/**': { cache: { maxAge: 60 * 60 } },\n \n // Network-only for dynamic content\n '/api/user/**': { cache: { maxAge: 60 } },\n \n // ISR: Revalidate on-demand\n '/news/**': { swr: 3600, prerender: true },\n \n // Disable caching for real-time\n '/live/**': { cache: false },\n \n // SPA mode (no SSR)\n '/admin/**': { ssr: false }\n }\n})","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-5","name":"useAsyncData with request deduplication: Collapse concurrent API calls","description":"Code example","text":"// composables/useUserData.ts\nexport const useUserData = (userId) => {\n const { data: user, pending } = useAsyncData(\n `user-${userId}`,\n () => $fetch(`/api/users/${userId}`),\n { watch: [() => userId] } // Refetch on userId change\n )\n \n const { data: posts } = useAsyncData(\n `user-posts-${userId}`,\n () => $fetch(`/api/users/${userId}/posts`),\n { server: true } // Pre-fetch on server\n )\n \n return { user, posts, pending }\n}\n\n// Multiple components using same userId collapse to single request\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-6","name":"Conditional page layout: Dynamic layout switching based on route","description":"Code example","text":"// layouts/default.vue\n\n\n\n\n// pages/auth/login.vue\n\n\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-7","name":"Error boundary with fallback: Graceful error handling in components","description":"Code example","text":"// pages/complex-feature.vue\n\n\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-8","name":"useHead with reactive metadata: Dynamic SEO based on data","description":"Code example","text":"// pages/blog/[slug].vue\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-9","name":"Pinia store persistence: localStorage sync with hydration","description":"Code example","text":"// stores/preferences.ts\nimport { defineStore } from 'pinia'\n\nexport const usePreferencesStore = defineStore('preferences', () => {\n const theme = ref('light')\n const sidebarCollapsed = ref(false)\n \n const restore = () => {\n if (process.client) {\n const stored = localStorage.getItem('preferences')\n if (stored) {\n const data = JSON.parse(stored)\n theme.value = data.theme\n sidebarCollapsed.value = data.sidebarCollapsed\n }\n }\n }\n \n const save = () => {\n if (process.client) {\n localStorage.setItem('preferences', JSON.stringify({\n theme: theme.value,\n sidebarCollapsed: sidebarCollapsed.value\n }))\n }\n }\n \n watch([theme, sidebarCollapsed], () => save(), { deep: true })\n \n return { theme, sidebarCollapsed, restore, save }\n}, {\n hydrate: (state, initialState) => Object.assign(state, initialState)\n})\n\n// app.vue\nconst prefs = usePreferencesStore()\nonBeforeMount(() => prefs.restore())","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-10","name":"Composable with dependency injection: Testable reactive logic","description":"Code example","text":"// composables/useFetchData.ts\nexport const useFetchData = (url, options = {}) => {\n const data = ref(null)\n const error = ref(null)\n const pending = ref(false)\n const cache = new Map()\n \n const fetch = async (forceRefresh = false) => {\n if (!forceRefresh && cache.has(url)) {\n data.value = cache.get(url)\n return\n }\n \n pending.value = true\n try {\n data.value = await $fetch(url, options)\n cache.set(url, data.value)\n } catch (e) {\n error.value = e\n } finally {\n pending.value = false\n }\n }\n \n const refresh = () => fetch(true)\n \n onMounted(() => fetch())\n \n return { data, error, pending, fetch, refresh }\n}\n\n// pages/dashboard.vue\nconst { data: stats, pending, refresh } = useFetchData('/api/stats')\nconst { data: users } = useFetchData('/api/users', { params: { limit: 10 } })","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-11","name":"Server middleware for request transformation: Logging and timing","description":"Code example","text":"// server/middleware/timing.ts\nexport default defineEventHandler((event) => {\n const startTime = Date.now()\n \n const originalSend = event.node.res.end\n event.node.res.end = function(...args) {\n const duration = Date.now() - startTime\n console.log(`[${event.node.req.method}] ${event.node.req.url} - ${duration}ms`)\n return originalSend.apply(this, args)\n }\n})\n\n// Logs all requests with response time\n// Output: [GET] /api/users - 45ms","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-12","name":"Nuxt payload extraction: Inline data in HTML for faster hydration","description":"Code example","text":"// nuxt.config.ts\nexport default defineNuxtConfig({\n experimental: {\n payloadExtraction: true\n }\n})\n\n// pages/blog/[slug].vue\nconst { data: post } = await useAsyncData(\n `post-${route.params.slug}`,\n () => queryContent(`blog/${route.params.slug}`).findOne()\n)\n\n// HTML contains pre-rendered post data inline\n// \n// Eliminates separate API call on page load","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-13","name":"Route metadata with typed pages: Type-safe route definitions","description":"Code example","text":"// Define app.vue with experimental appManifest\n// Enable: experimental.appManifest in nuxt.config.ts\n\n// pages/dashboard.vue\n\n\n// Composable with typed access\nconst route = useRoute()\nconst routeMeta = route.meta as Record\nconsole.log(routeMeta.description) // Type-safe access","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-14","name":"useNuxtData: Server-side data availability in browser","description":"Code example","text":"// pages/index.vue\nconst { data: initialData } = await useAsyncData('home-data', () => $fetch('/api/home-data'))\n\n// In another component\nconst cachedData = useNuxtData('home-data') // Reuses pre-fetched data\n\n// Both components share same server-rendered data, no duplicate requests","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-15","name":"Nuxt session storage: server-side session management","description":"Code example","text":"// server/api/auth/login.post.ts\nexport default defineEventHandler(async (event) => {\n const body = await readBody(event)\n const user = await validateCredentials(body)\n \n if (!user) {\n throw createError({ statusCode: 401, message: 'Invalid credentials' })\n }\n \n // Store session server-side\n await useStorage().setItem(`session:${user.id}`, { userId: user.id, role: user.role })\n \n // Set session cookie\n setCookie(event, 'session_id', user.id, { maxAge: 60 * 60 * 24 })\n \n return { success: true, user: { id: user.id, name: user.name } }\n})\n\n// server/middleware/auth.ts\nexport default defineEventHandler(async (event) => {\n const sessionId = getCookie(event, 'session_id')\n if (sessionId) {\n const session = await useStorage().getItem(`session:${sessionId}`)\n event.context.user = session\n }\n})","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-16","name":"Lazy route preloading: Prefetch routes on idle time","description":"Code example","text":"// nuxt.config.ts\nexport default defineNuxtConfig({\n experimental: {\n payloadExtraction: true\n }\n})\n\n// composables/usePrefetchRoutes.ts\nexport const usePrefetchRoutes = (routes = []) => {\n if (process.client) {\n const prefetch = () => {\n routes.forEach(route => {\n const link = document.createElement('link')\n link.rel = 'prefetch'\n link.href = route\n document.head.appendChild(link)\n })\n }\n \n if ('requestIdleCallback' in window) {\n requestIdleCallback(prefetch)\n } else {\n setTimeout(prefetch, 2000)\n }\n }\n}\n\n// pages/index.vue\nuseMount(() => {\n usePrefetchRoutes(['/about', '/products', '/blog'])\n})","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-17","name":"Conditional server-rendering: SPA mode for admin with SSR fallback","description":"Code example","text":"// nuxt.config.ts\nexport default defineNuxtConfig({\n routeRules: {\n // Admin section: SPA only (no SSR overhead)\n '/admin/**': { ssr: false },\n // Public pages: Full SSR for SEO\n '/**': { ssr: true }\n },\n // Or per-page\n app: {\n pageTransition: { name: 'page', mode: 'out-in' }\n }\n})\n\n// pages/admin/dashboard.vue\n","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-18","name":"Composable with cleanup: Prevent memory leaks in data fetching","description":"Code example","text":"// composables/usePollingData.ts\nexport const usePollingData = (url, interval = 5000) => {\n const data = ref(null)\n const pollId = ref(null)\n \n const startPolling = async () => {\n const fetchData = async () => {\n data.value = await $fetch(url)\n }\n \n await fetchData() // Initial fetch\n pollId.value = setInterval(fetchData, interval)\n }\n \n const stopPolling = () => {\n if (pollId.value) clearInterval(pollId.value)\n }\n \n onMounted(() => startPolling())\n onUnmounted(() => stopPolling())\n \n return { data, startPolling, stopPolling }\n}\n\n// pages/live-metrics.vue\nconst { data: metrics } = usePollingData('/api/metrics', 3000)\n// Polling stops automatically when component unmounts","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-19","name":"Request caching with etag: Conditional GET requests","description":"Code example","text":"// server/api/data.ts\nexport default defineEventHandler(async (event) => {\n const data = await fetchExpensiveData()\n const etag = generateETag(JSON.stringify(data))\n const ifNoneMatch = getHeader(event, 'if-none-match')\n \n setHeader(event, 'etag', etag)\n \n if (ifNoneMatch === etag) {\n event.node.res.statusCode = 304\n return\n }\n \n return data\n})\n\n// Client automatically handles 304 Not Modified responses\nconst { data } = await useFetch('/api/data', { watch: false })","inLanguage":"javascript"},{"@type":"CreativeWork","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#snippet-20","name":"Global error handler with Sentry integration","description":"Code example","text":"// plugins/errorHandler.client.ts\nexport default defineNuxtPlugin((nuxtApp) => {\n if (process.client) {\n const router = useRouter()\n \n nuxtApp.hook('vue:error', (error, instance) => {\n // Send to Sentry\n if (window.__SENTRY__) {\n window.__SENTRY__.captureException(error)\n }\n \n console.error('Vue error caught:', error)\n })\n \n router.afterEach((to, from, failure) => {\n if (failure) {\n console.error('Navigation failed:', failure)\n }\n })\n }\n})","inLanguage":"javascript"}],"keywords":"Nuxt 3 advanced, Performance optimization, State management Pinia, Advanced routing, Middleware composition, Caching strategies, Server-side rendering optimization, Bundle splitting, Request deduplication, TypeScript patterns, Nuxt3-Advanced, Performance, StateManagement, Optimization, Architecture","about":[{"@type":"Thing","name":"Nuxt3-Advanced"},{"@type":"Thing","name":"Performance"},{"@type":"Thing","name":"StateManagement"},{"@type":"Thing","name":"Optimization"},{"@type":"Thing","name":"Architecture"}]},{"@type":"ItemList","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#topics","name":"Core Concepts - Nuxt 3 Advanced DATA | Performance Optimization + State Management Guide","numberOfItems":5,"itemListElement":[{"@type":"ListItem","position":1,"name":"Advanced routing patterns: Dynamic nested routes with parameters","description":"Nuxt intermediate skill: Mastering complex route hierarchies with catch-all routes, optional parameters, and dynamic segments. Routes like /blog/[category]/[...slug].vue enable flexible URL structures. See dynamic route examples below for production patterns.","url":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#core-concepts"},{"@type":"ListItem","position":2,"name":"State management advanced: Pinia modules with composables pattern","description":"Production state management: Pinia stores with getters, actions, computed properties, and module composition. Reactive state shared across components without prop drilling. See Pinia module organization and testing patterns.","url":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#core-concepts"},{"@type":"ListItem","position":3,"name":"Performance optimization: Code splitting and lazy loading routes","description":"Nuxt intermediate optimization: Route-based code splitting automatically enabled. Lazy-load heavy components with defineAsyncComponent(), implement route-level prefetching with NuxtLink prefetch attribute. Reduces initial bundle by 40-60%.","url":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#core-concepts"},{"@type":"ListItem","position":4,"name":"Advanced middleware: Composition, guards, and conditional execution","description":"Middleware composition chains multiple middleware functions. Route-specific guards validate permissions, conditionally redirect based on auth state. Global middleware runs on every route, per-route middleware applies selectively. See middleware orchestration patterns.","url":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#core-concepts"},{"@type":"ListItem","position":5,"name":"Server-side caching: Route rules and ISR (Incremental Static Regeneration)","description":"Nuxt intermediate performance: routeRules configuration enables SWR (stale-while-revalidate), cache policies, and ISR. Prerender frequently accessed routes, cache API responses, conditionally regenerate content without full rebuild.","url":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#core-concepts"}]},{"@type":"TechArticle","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#article","headline":"Nuxt 3 Advanced DATA | Performance Optimization + State Management Guide","description":"Complete reference guide","image":[{"@type":"ImageObject","url":"https://yourcheatsheet.org/images/nuxt-3-advanced-og","width":1200,"height":630},{"@type":"ImageObject","url":"https://yourcheatsheet.org/images/nuxt-3-advanced-og","width":800,"height":800}],"author":{"@id":"https://yourcheatsheet.org/author/alice-mcdonnell"},"publisher":{"@id":"https://yourcheatsheet.org/about"},"inLanguage":"en-US","isAccessibleForFree":true,"keywords":"Nuxt 3 advanced, Performance optimization, State management Pinia, Advanced routing, Middleware composition, Caching strategies, Server-side rendering optimization, Bundle splitting, Request deduplication, TypeScript patterns, Nuxt3-Advanced, Performance, StateManagement, Optimization, Architecture","speakable":{"@type":"SpeakableSpecification","cssSelector":["#top","#quick-start","#when-to-use","#core-concepts","#snippets","#master-commands","#production-examples","#production-fixes","#pitfalls","#troubleshooting","#elite-pro-hack","#workflows","#benchmark","#resources"]},"potentialAction":[{"@type":"ReadAction","target":{"@type":"EntryPoint","urlTemplate":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate"}},{"@type":"DownloadAction","name":"Download PDF","target":{"@type":"EntryPoint","urlTemplate":"https://yourcheatsheets.org/downloads/nuxt-intermediate.pdf"}}]},{"@type":"BreadcrumbList","@id":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://yourcheatsheet.org"},{"@type":"ListItem","position":2,"name":"Web-Development","item":"https://yourcheatsheet.org/categories/Web-Development"},{"@type":"ListItem","position":3,"name":"Nuxt 3 Advanced DATA | Performance Optimization + State Management Guide","item":"https://yourcheatsheets.org/cheatsheets/nuxt-intermediate"}]}]}

Quick Start with Nuxt intermediate

Production-ready compilation flags and build commands

Advanced routing patterns: QUICK START (2 minutes)

Copy → Paste → Live

mkdir -p app/middleware app/server/utils && npm install @pinia/nuxt pinia && echo 'export default defineNuxtConfig({ modules: ["@pinia/nuxt"], app: { pageTransition: { name: "page", mode: "out-in" } } })' > nuxt.config.ts
$
✅ Nuxt configured with Pinia and page transitions. Learn more in Advanced State Management section
⚡ 5s Setup

When to Use Nuxt intermediate

Decision matrix per scegliere la tecnologia giusta

IDEAL USE CASES

  • Scaling Nuxt applications with complex state management, advanced middleware patterns, and server-side caching strategies

  • Performance-critical applications requiring code splitting, lazy loading, route prefetching, and bundle optimization techniques

  • Multi-tenant or feature-flag driven applications using middleware composition, route guards, and conditional rendering patterns

AVOID FOR

  • Simple static sites where auto-rendering and basic routing suffice without advanced optimization

  • Real-time applications requiring WebSocket-level communication instead of server-sent events or polling

  • Monolithic applications unable to adopt incremental static regeneration (ISR) or hybrid rendering strategies

Core Concepts of Nuxt intermediate

Production-ready compilation flags and build commands

#1

Advanced routing patterns: Dynamic nested routes with parameters

Nuxt intermediate skill: Mastering complex route hierarchies with catch-all routes, optional parameters, and dynamic segments. Routes like /blog/[category]/[...slug].vue enable flexible URL structures. See dynamic route examples below for production patterns.

✓ Solution
Use spread operator for catch-all: pages/posts/[...slug].vue maps to /posts/any/nested/path, validate parameters with definePageMeta hooks
+55% URL structure flexibility vs basic routing
#2

State management advanced: Pinia modules with composables pattern

Production state management: Pinia stores with getters, actions, computed properties, and module composition. Reactive state shared across components without prop drilling. See Pinia module organization and testing patterns.

+70% code reduction vs manual prop passing
#3

Performance optimization: Code splitting and lazy loading routes

Nuxt intermediate optimization: Route-based code splitting automatically enabled. Lazy-load heavy components with defineAsyncComponent(), implement route-level prefetching with NuxtLink prefetch attribute. Reduces initial bundle by 40-60%.

Bundle size: 800KB → 320KB after splitting, LCP improvement: 2.1s → 850ms
#4

Advanced middleware: Composition, guards, and conditional execution

Middleware composition chains multiple middleware functions. Route-specific guards validate permissions, conditionally redirect based on auth state. Global middleware runs on every route, per-route middleware applies selectively. See middleware orchestration patterns.

✓ Solution
Use middleware chains with early returns, prevent infinite loops with route tracking, handle edge cases explicitly
#5

Server-side caching: Route rules and ISR (Incremental Static Regeneration)

Nuxt intermediate performance: routeRules configuration enables SWR (stale-while-revalidate), cache policies, and ISR. Prerender frequently accessed routes, cache API responses, conditionally regenerate content without full rebuild.

+85% TTFB improvement with proper cache strategy