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:
- In
nuxt.config.ts:- Add
runtimeConfigwith a privateapiSecret(use 'server-secret-key') - Add
public.apiBase(use 'https://api.example.com') - Add
public.appName(use 'My Nuxt App')
- Add
- In
app.vue:- Access the public config using
useRuntimeConfig() - Display the
apiBaseandappName - Try to access
apiSecret(this should NOT work on client!)
- Access the public config using
- In
server/api/config.ts:- Create an API route that returns the
apiSecret - This demonstrates that secrets are only available on the server
- Create an API route that returns the
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.