Configuration

Nuxt Configuration Deep Dive

The nuxt.config.ts file is the single source of truth for configuring your Nuxt application. It controls everything from runtime behavior to build settings.

Basic Configuration

// nuxt.config.ts
export default defineNuxtConfig({
  app: {
    head: {
      title: 'My App'
    }
  },
  modules: ['@nuxt/content'],
  devtools: { enabled: true }
})

Runtime Config

Runtime config allows you to expose configuration that can be changed at runtime without rebuilding:

export default defineNuxtConfig({
  runtimeConfig: {
    // Private keys (server-only)
    apiSecret: process.env.API_SECRET,

    // Public keys (exposed to client)
    public: {
      apiBase: process.env.API_BASE || 'https://api.example.com'
    }
  }
})

Accessing Runtime Config

<script setup>
// In components or composables
const config = useRuntimeConfig()
console.log(config.public.apiBase)

// On server
const config = useRuntimeConfig()
console.log(config.apiSecret) // Available
console.log(config.public.apiBase) // Also available
</script>

Environment Variables

Nuxt automatically loads .env files:

# .env
API_SECRET=my-secret-key
NUXT_PUBLIC_API_BASE=https://api.example.com

Variables prefixed with NUXT_PUBLIC_ are automatically added to runtimeConfig.public.

Build-time vs Runtime Config

Build-time config (hard-coded values):

export default defineNuxtConfig({
  app: {
    head: { title: 'My App' }
  }
})

Runtime config (can change without rebuild):

export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiBase: process.env.API_BASE
    }
  }
})

Challenge

Configure public and private runtime config:

  1. In nuxt.config.ts:
    • Add runtimeConfig with a private apiSecret (use 'server-secret-key')
    • Add public.apiBase (use 'https://api.example.com')
    • Add public.appName (use 'My Nuxt App')
  2. In app.vue:
    • Access the public config using useRuntimeConfig()
    • Display the apiBase and appName
    • Try to access apiSecret (this should NOT work on client!)
  3. In server/api/config.ts:
    • Create an API route that returns the apiSecret
    • This demonstrates that secrets are only available on the server

Pitfall: Never put sensitive data in runtimeConfig.public! It's exposed to the client. Use the root runtimeConfig for secrets.

Tip: You can override runtime config with environment variables at runtime without rebuilding your app.

If you get stuck, you can check the solution by clicking the button below.


Runtime configuration is essential for deploying Nuxt apps across different environments (development, staging, production) without rebuilding.

Composables
Nuxt Layers
Nuxt Layers are a powerful mechanism to share configuration, components, and logic across multiple projects. It's like having a full Nuxt application inside your application!
Files
Editor
Initializing WebContainer
Mounting files
Installing dependencies
Starting Nuxt server
Waiting for Nuxt to ready
Terminal