All posts

Nuxt Production Best Practices

Essential Nuxt best practices for production covering SSR configuration, caching strategies, security headers, and deployment optimization.

Nuxt Production Best Practices

Nuxt 3's hybrid rendering capabilities require thoughtful production configuration. Here are the practices that matter.

Configure Rendering Strategy

Choose the right rendering mode per route:

// nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    '/': { prerender: true },
    '/blog/**': { swr: 3600 },      // Stale-while-revalidate, 1hr
    '/dashboard/**': { ssr: false }, // Client-only for authenticated pages
    '/api/**': { cors: true },
  },
});

Security Headers

export default defineNuxtConfig({
  security: {
    headers: {
      contentSecurityPolicy: {
        'default-src': ["'self'"],
        'script-src': ["'self'", "'nonce-{nonce}'"],
      },
      xFrameOptions: 'DENY',
      xContentTypeOptions: 'nosniff',
    },
  },
});

Data Fetching Patterns

// Use useAsyncData for deduplication and caching
const { data, error } = await useAsyncData('posts', () => {
  return $fetch('/api/posts');
}, {
  transform: (posts) => posts.map(simplifyPost),
  server: true,    // Fetch on server
  lazy: false,     // Block navigation until loaded
});

// Handle errors gracefully
if (error.value) {
  throw createError({
    statusCode: 500,
    statusMessage: 'Failed to load posts',
  });
}

Environment Configuration

export default defineNuxtConfig({
  runtimeConfig: {
    apiSecret: '',    // Server-only, from NUXT_API_SECRET
    public: {
      apiBase: '',    // Client-accessible, from NUXT_PUBLIC_API_BASE
    },
  },
});

Never expose server-only secrets to the client. The runtimeConfig.public namespace is the only safe place for client-visible values.

Performance Optimization

  • Enable payload extraction for smaller client-side JavaScript
  • Use `<NuxtImage>` for automatic image optimization
  • Lazy-load components with <LazyMyComponent />
  • Minimize middleware — each runs on every navigation

Error Handling

Create an error.vue page for global error display and integrate Bugsly to capture unhandled errors in both SSR and client contexts. Nuxt's server-side errors can be particularly hard to debug without proper error tracking in place.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free