Fix: Could Not Access Runtime Config Key in Nuxt

Error message:
Could not access `{key}`. The runtime config was not set.
initialization 2025-01-25

What Causes This Warning?

This warning appears when you try to access a runtime config key that doesn’t exist or wasn’t properly defined in your nuxt.config.ts.

The Problem

<script setup>
const config = useRuntimeConfig()

// ❌ Key doesn't exist
console.log(config.public.nonExistentKey)  // undefined + warning

// ❌ Wrong path
console.log(config.apiKey)  // Should be config.public.apiKey or config.apiKey depending on setup
</script>

The Fix

Define Runtime Config Properly

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // Private keys (server-only)
    apiSecret: '',
    databaseUrl: '',

    // Public keys (exposed to client)
    public: {
      apiBase: '',
      appName: ''
    }
  }
})

Set Values via Environment Variables

# .env
NUXT_API_SECRET=my-secret-key
NUXT_DATABASE_URL=postgres://...
NUXT_PUBLIC_API_BASE=https://api.example.com
NUXT_PUBLIC_APP_NAME=My App

The convention is:

  • NUXT_ prefix for all config
  • NUXT_PUBLIC_ for public config
  • Snake case becomes camelCase

Understanding Runtime Config

Server vs Public

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // Server-only (never sent to client)
    apiSecret: 'secret',      // NUXT_API_SECRET
    dbPassword: 'password',   // NUXT_DB_PASSWORD

    // Client-accessible
    public: {
      apiBase: '/api',        // NUXT_PUBLIC_API_BASE
      siteUrl: ''             // NUXT_PUBLIC_SITE_URL
    }
  }
})

Access in Components

<script setup>
const config = useRuntimeConfig()

// ✅ Access public config (works on client and server)
const apiBase = config.public.apiBase

// ❌ Server-only config not available on client
// config.apiSecret  // undefined on client!
</script>

Access in Server Routes

// server/api/data.ts
export default defineEventHandler((event) => {
  const config = useRuntimeConfig(event)

  // ✅ Can access both private and public
  const secret = config.apiSecret        // Works!
  const apiBase = config.public.apiBase  // Works!

  return { data: 'ok' }
})

Common Mistakes

1. Missing Environment Variable

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    public: {
      apiKey: ''  // Empty default
    }
  }
})
# .env - Missing the variable!
# NUXT_PUBLIC_API_KEY=xxx  ← Not set

Solution:

# .env
NUXT_PUBLIC_API_KEY=your-api-key

2. Wrong Environment Variable Name

// nuxt.config.ts
runtimeConfig: {
  public: {
    apiBaseUrl: ''  // camelCase
  }
}
# .env
# ❌ Wrong naming
NUXT_PUBLIC_API_BASE_URL=https://api.com  # Wrong!
NUXT_PUBLIC_APIBASEURL=https://api.com    # Wrong!

# ✅ Correct - follows the casing pattern
NUXT_PUBLIC_API_BASE_URL=https://api.com
# Maps to apiBaseUrl (snake_case -> camelCase)

3. Accessing Private Config on Client

<script setup>
const config = useRuntimeConfig()

// ❌ Private config is server-only
const secret = config.apiSecret  // undefined on client!

// ✅ Move to server route
</script>

4. Typo in Config Key

// nuxt.config.ts
runtimeConfig: {
  public: {
    apiBase: 'https://api.com'  // Defined as 'apiBase'
  }
}
<script setup>
const config = useRuntimeConfig()

// ❌ Typo
const base = config.public.apibase  // undefined (lowercase 'b')

// ✅ Correct
const base = config.public.apiBase  // Works!
</script>

TypeScript Support

Auto-generated Types

After running nuxi prepare, types are generated in .nuxt/nuxt.d.ts:

// Access with autocomplete
const config = useRuntimeConfig()
config.public.apiBase  // TypeScript knows this exists

Custom Type Declaration

// types/nuxt.d.ts
declare module 'nuxt/schema' {
  interface RuntimeConfig {
    apiSecret: string
    databaseUrl: string
  }

  interface PublicRuntimeConfig {
    apiBase: string
    appName: string
  }
}

Debugging

Check Current Config

<script setup>
const config = useRuntimeConfig()

onMounted(() => {
  // ✅ See what's available (public only on client)
  console.log('Runtime config:', JSON.stringify(config.public, null, 2))
})
</script>

Server-side Debug

// server/api/debug-config.ts
export default defineEventHandler((event) => {
  const config = useRuntimeConfig(event)

  // Only in development!
  if (process.dev) {
    return {
      public: config.public,
      privateKeys: Object.keys(config).filter(k => k !== 'public')
    }
  }

  return { error: 'Not available in production' }
})

Check Environment Variables

# List all NUXT_ variables
env | grep NUXT_

Best Practices

Default Values

// nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    // Provide sensible defaults
    public: {
      apiBase: process.env.NODE_ENV === 'production'
        ? 'https://api.example.com'
        : 'http://localhost:3001'
    }
  }
})

Required Config Validation

// plugins/validate-config.ts
export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig()

  const required = ['apiBase', 'appName']
  for (const key of required) {
    if (!config.public[key]) {
      console.warn(`Missing required config: public.${key}`)
    }
  }
})

Quick Checklist

  • Config key is defined in nuxt.config.ts runtimeConfig
  • Environment variable uses correct naming convention
  • Public config is under runtimeConfig.public
  • Server-only config is accessed only in server context
  • .env file is in project root and loaded
  • Run nuxi prepare to regenerate types
  • Restart dev server after config changes