Nuxt 03 ๐ Configuration & Runtime Config โ Mastering nuxt.config.ts, app.config.ts, useRuntimeConfig(), and NUXT_ environment variables
Configuration is the central nervous system of a Nuxt application. In a modern full-stack environment, developers face the challenge of managing settings that change across different stages of the lifecycle: build-time settings (like which modules to load), server-side secrets (like database passwords), and client-side UI preferences (like theme colors). Nuxt addresses this by splitting configuration into distinct, purpose-built layers: nuxt.config.ts, app.config.ts, and the Runtime Config system.
The nuxt.config.ts file acts as the primary orchestrator for the framework and its ecosystem. It is here that you register modules, configure the Nitro server engine, and define your build-time constants. Because this file is processed during the build phase, it has full access to the Node.js environment, allowing it to read from the file system or environment variables to determine how the final application bundle should be structured.
However, once the application is built and deployed, you often need to change settings without triggering a full rebuildโthis is where Runtime Config comes in. By using the runtimeConfig property, you can define values that can be overridden by environment variables at the moment the server starts. Nuxt ensures a strict security boundary here: “private” keys are only accessible on the server, while “public” keys are safely shared with the browser.
This chapter explores the mechanics of Nuxtโs configuration ecosystem. We will examine how to securely handle secrets, how to utilize the app.config.ts for reactive UI state, and how the NUXT_ environment variable prefix allows for zero-config deployments. By the end of this chapter, you will be able to architect a configuration strategy that is both secure for your backend and flexible for your frontend.
Key point: Nuxt separates configuration into build-time settings (nuxt.config.ts) and runtime settings (runtimeConfig); the latter allows you to securely manage server-side secrets while selectively exposing public keys to the client via useRuntimeConfig().
Why exists
The Security Leak problem
Hardcoding API keys or database credentials directly into a frontend application is a critical security risk. If these values are bundled into the JavaScript sent to the browser, they are essentially public. Nuxt’s runtimeConfig exists to create a “firewall” between the server and the client. Private keys stay on the Nitro server and never reach the browser’s memory, while only explicitly marked public keys are sent across the wire.
The Immutable Build problem
In a traditional CI/CD pipeline, an application is built once and then deployed to multiple environments (Development, Staging, Production). If configuration is baked in at build-time, you would need a separate build for every environment. Runtime Config exists so you can build the application as an “immutable” artifact and then inject environment-specific values (like different API URLs) at the moment the container or server starts.
The Configuration Fatigue problem
Modern web apps require configuring dozens of tools: Vite, PostCSS, TypeScript, Router, and various Nuxt modules. Managing these separately would lead to a fragmented project structure. nuxt.config.ts provides a unified “source of truth.” It acts as a central hub where all these configurations are aggregated and simplified into a single, type-safe TypeScript file.
The Reactive UI State problem
Some configurations are purely visualโthings like a site name, a theme primary color, or whether a “Dark Mode” toggle should be visible. Putting these in environment variables is overkill, and putting them in build-time config makes them hard to update dynamically. app.config.ts exists to handle this “Frontend Configuration.” It provides a reactive, type-safe object that can be easily accessed and even updated within Vue components.
The Environment Variable Overloading problem
Managing .env files can become chaotic as projects scale. Nuxt provides a convention-based approach using the NUXT_ prefix. This allows developers to override any value in the runtimeConfig simply by setting a corresponding environment variable on the host system. This “convention over configuration” approach reduces the need for manual mapping code.
a. Build-time Configuration: nuxt.config.ts
The nuxt.config.ts file is the most important configuration file in your project. It is written in TypeScript and uses the defineNuxtConfig helper to provide full IDE autocomplete and type checking. This file is executed during the build process and handles the “structure” of your application.
// nuxt.config.ts
export default defineNuxtConfig({
// Enable Nuxt DevTools for a better development experience
devtools: { enabled: true },
// Register Nuxt modules (e.g., UI libraries, state management)
modules: ['@nuxtjs/tailwindcss', '@pinia/nuxt'],
// Configure PostCSS for styling
postcss: {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
},
// Define global CSS files
css: ['~/assets/css/main.css'],
// Future flags for Nuxt 4 compatibility
future: {
compatibilityVersion: 4,
}
})
Because this file runs in a Node.js context during build, you can use Node APIs here. However, any code written here will NOT be included in the final client-side bundle. This makes it the perfect place for “meta-logic,” such as scanning the file system to generate dynamic routes or setting up proxy rules for the development server.
b. Runtime Config: Server vs. Client Secrets
Runtime Config is defined within the runtimeConfig property of nuxt.config.ts. It is split into two sections: the root properties (private, server-only) and the public property (accessible by both server and client). This is the foundation of full-stack security in Nuxt.
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// PRIVATE: Only available on the server
apiSecret: 'my-super-secret-key',
// PUBLIC: Available on both server and client
public: {
apiBase: 'https://api.example.com'
}
}
})
To access these values in your application, you use the useRuntimeConfig() composable. On the server (e.g., in an API route), you will see the entire object. On the client (e.g., in a Vue component), the private apiSecret will be undefined, while public.apiBase will be fully accessible.
Nuxt also supports automatic environment variable mapping. If you have an environment variable named NUXT_API_SECRET, it will automatically override the apiSecret value in your config. For nested public values like public.apiBase, you would use NUXT_PUBLIC_API_BASE.
c. App Config: Reactive UI Settings
While Runtime Config is intended for environment-specific “technical” values, app.config.ts is intended for “application-specific” UI settings. This file lives in the root of your project and, unlike the main config, the values here are reactive and merged with the client bundle.
// app.config.ts
export default defineAppConfig({
title: 'My Awesome Nuxt App',
theme: {
dark: true,
colors: {
primary: '#ff0000'
}
}
})
Accessing this is done via the useAppConfig() composable. Because it is reactive, you could theoretically update these values within a component (though they won’t persist across sessions unless you use a store). It is the ideal place to store things that a theme-builder or a CMS might control, such as social media links, button styles, or layout preferences.
The key difference: runtimeConfig is for secrets and server-to-client bridge values; app.config.ts is for UI metadata and theme configurations that don’t change based on where the app is deployed.
Complete Example Session
// ============================================
// PART 1: DEFINING NUXT CONFIG
// ============================================
// File: nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// Secret key for JWT or Database
stripeSecret: '', // Default empty, overridden by NUXT_STRIPE_SECRET
public: {
// Public API endpoint
apiBase: '/api'
}
}
});
// ============================================
// PART 2: DEFINING APP CONFIG
// ============================================
// File: app.config.ts
export default defineAppConfig({
ui: {
primaryColor: 'emerald',
showFooter: true
}
});
// ============================================
// PART 3: THE .env FILE
// ============================================
// File: .env
// NUXT_ prefix tells Nuxt to inject these into runtimeConfig
// NUXT_STRIPE_SECRET="sk_test_51Mz..."
// NUXT_PUBLIC_API_BASE="https://api.production.com"
// ============================================
// PART 4: ACCESSING SECRETS ON THE SERVER
// ============================================
// File: server/api/payment.post.ts
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig();
// Accessing the private secret (Safe here!)
const stripeKey = config.stripeSecret;
return { status: 'authorized', keyUsed: !!stripeKey };
});
// ============================================
// PART 5: ACCESSING PUBLIC CONFIG ON CLIENT
// ============================================
// File: app/pages/index.vue
/*
<script setup>
const config = useRuntimeConfig();
// config.stripeSecret will be undefined here!
const api = config.public.apiBase;
</script>
*/
// ============================================
// PART 6: ACCESSING UI CONFIG IN A COMPONENT
// ============================================
/*
<script setup>
const appConfig = useAppConfig();
const color = appConfig.ui.primaryColor;
</script>
*/
// ============================================
// PART 7: OVERRIDING VIA ENVIRONMENT
// ============================================
// Command: NUXT_PUBLIC_API_BASE=http://localhost:8080 npm run dev
// This overrides the apiBase for this specific session
// ============================================
// PART 8: TYPING RUNTIME CONFIG (Optional)
// ============================================
// You can extend the RuntimeConfig interface in an index.d.ts
// to get full type safety for custom keys.
// ============================================
// PART 9: PRODUCTION BUILD
// ============================================
// npm run build
// The private secrets are NOT in the .mjs client bundle.
// ============================================
// PART 10: DYNAMIC RUNTIME VALUES
// ============================================
// Nitro can also handle runtime config updates via
// process.env if running in a Node environment.
The sequence above demonstrates the lifecycle of a configuration value from the nuxt.config.ts and .env files, through the Nitro server, and safely to the Vue frontend.
Quick Reference
Configuration Files Comparison
| Feature | nuxt.config.ts | runtimeConfig | app.config.ts |
|---|---|---|---|
| Purpose | Build/Module Setup | Secrets & Env Vars | UI & Theme Metadata |
| Execution | Build Time | Runtime | Runtime |
| Env Overrides | No | Yes (NUXT_ prefix) | No |
| Client Access | Only public key | Only public key | Full Access |
| Reactivity | No | Partially | Yes |
Environment Variable Naming Convention
| Config Path | Environment Variable Name |
|---|---|
mySecret | NUXT_MY_SECRET |
public.apiBase | NUXT_PUBLIC_API_BASE |
auth.token | NUXT_AUTH_TOKEN |
public.site.url | NUXT_PUBLIC_SITE_URL |
Accessing Config via Composables
| Context | Composable | Availability |
|---|---|---|
| Vue Components | useRuntimeConfig() | Server & Client (public only) |
| Server API | useRuntimeConfig() | Full access to all keys |
| Global UI | useAppConfig() | Reactive access everywhere |
Best Practices
โ Do This:
// Use runtimeConfig.public for API URLs // โ
// Use root runtimeConfig for API Secrets (Server-only) // โ
// Use NUXT_ prefix for production environment variables // โ
// Use app.config.ts for purely aesthetic UI toggles // โ
// Keep secrets in a .env file and add it to .gitignore // โ
โ Don’t Do This:
// Don't put Database passwords in runtimeConfig.public // โ
// Don't use process.env directly in Vue components // โ
// Don't hardcode sensitive keys in nuxt.config.ts // โ
// Don't use app.config.ts for security-sensitive logic // โ
// Don't omit the public: {} wrapper for client values // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Secret leaked to client | Key was placed inside the public object. | Move sensitive keys to the runtimeConfig root. |
| Env var not working | Missing the NUXT_ prefix or incorrect casing. | Ensure vars are NUXT_UPPER_CASE_SNAKE. |
undefined on client | Trying to access a private key in a Vue file. | Use public or handle logic on the server. |
| Hydration mismatch | Config values different on server vs client. | Ensure .env is identical in both environments. |
| No types for config | TypeScript doesn’t know your custom keys. | Use Module Augmentation to extend RuntimeConfig. |
Real-World Examples
1. Defining a Private Secret
runtimeConfig: { dbPassword: '123' }
2. Defining a Public API Key
runtimeConfig: { public: { stripePk: 'pk_123' } }
3. Overriding in Production
export NUXT_DB_PASSWORD="real_password_here"
4. Accessing in a Middleware
const { authSecret } = useRuntimeConfig();
5. Custom Site Title in App Config
export default defineAppConfig({ name: 'Nuxt Store' });
6. Dynamic Theme Toggle
const app = useAppConfig();
app.theme.dark = !app.theme.dark;
7. Setting up a Proxy in Dev
devServer: { proxy: { '/api': 'http://localhost:8000' } }
8. Disabling SSR for certain routes
routeRules: { '/admin/**': { ssr: false } }
9. Registering a Nuxt Module
modules: ['@nuxt/content']
10. Using PostCSS nesting
postcss: { plugins: { 'postcss-nested': {} } }
Visual
The Configuration Security Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ nuxt.config.ts (The Definition) โ
โ โ
โ runtimeConfig: { โ
โ secretKey: '...', โโโโโ PRIVATE (Stay on Server) โ
โ public: { โโโโโ PUBLIC (Safe for Client) โ
โ api: '...' โ
โ } โ
โ } โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ NITRO SERVER (API) โ โ BROWSER (Vue App) โ
โ โ โ โ
โ โ
Access secretKey โ โ โ Access secretKey โ
โ โ
Access public.api โ โ โ
Access public.api โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Environment Variable Injection
Environment System Nuxt Runtime Config
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ
โ NUXT_DB_PASS โ โโโโโโโโโบ โ dbPass โ
โโโโโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโโโโโโโโโค
โ NUXT_PUBLIC_URL โ โโโโโโโโโบ โ public.url โ
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโ
โฒ โฒ
โ โ
(Deployment Host) (Application)
App Config vs Runtime Config
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ app.config.ts โ โ runtimeConfig โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ - UI/Theme Metadata โ โ - API Keys / Database โ
โ - Reactive in Vue โ โ - Overridden by ENV vars โ
โ - Fully Public โ โ - Server/Client Split โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Main File | nuxt.config.ts |
| UI Config | app.config.ts |
| Private Config | runtimeConfig root (Server only) |
| Public Config | runtimeConfig.public (Server & Client) |
| Env Prefix | NUXT_ |
| Nested Env Sep | _ (e.g., PUBLIC_API) |
| Access Hook | useRuntimeConfig() |
| Reactivity | useAppConfig() is reactive |
Key takeaways:
- Runtime Config is for environment-specific data. It allows you to build your app once and deploy it anywhere by injecting values via environment variables at startup.
- Always prefix env variables with
NUXT_. This is the mandatory convention for Nuxt to recognize and map the variables into your configuration object. - Private is the default. Any key defined outside the
publicobject in your runtime config is strictly hidden from the browser. Use this for database passwords and internal API secrets. app.config.tsis for the “Look and Feel.” It is intended for configuration that doesn’t change based on deployment (like UI themes) and provides a reactive interface for Vue components.nuxt.config.tsis build-time only. It manages modules, build settings, and the general framework structure. It does not provide reactive state to the frontend.- Use TypeScript for safety. By defining your config in
.tsfiles, you get full autocomplete and validation, significantly reducing runtime errors caused by missing environment variables.
Remember: If you can see a value in the browser’s “Network” tab or “Source” tab, it’s public. Never put a secret key in runtimeConfig.public. If an API requires a secret, make that call through a Nuxt server/api route where the secret is safe.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!