| | |

Nuxt 03 ๐Ÿ’š Configuration & Runtime Config โ€” Mastering nuxt.config.ts, app.config.ts, useRuntimeConfig(), and NUXT_ environment variables

โฑ๏ธ Estimated read: 11 min | |

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

Featurenuxt.config.tsruntimeConfigapp.config.ts
PurposeBuild/Module SetupSecrets & Env VarsUI & Theme Metadata
ExecutionBuild TimeRuntimeRuntime
Env OverridesNoYes (NUXT_ prefix)No
Client AccessOnly public keyOnly public keyFull Access
ReactivityNoPartiallyYes

Environment Variable Naming Convention

Config PathEnvironment Variable Name
mySecretNUXT_MY_SECRET
public.apiBaseNUXT_PUBLIC_API_BASE
auth.tokenNUXT_AUTH_TOKEN
public.site.urlNUXT_PUBLIC_SITE_URL

Accessing Config via Composables

ContextComposableAvailability
Vue ComponentsuseRuntimeConfig()Server & Client (public only)
Server APIuseRuntimeConfig()Full access to all keys
Global UIuseAppConfig()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

PitfallWhy It HappensFix
Secret leaked to clientKey was placed inside the public object.Move sensitive keys to the runtimeConfig root.
Env var not workingMissing the NUXT_ prefix or incorrect casing.Ensure vars are NUXT_UPPER_CASE_SNAKE.
undefined on clientTrying to access a private key in a Vue file.Use public or handle logic on the server.
Hydration mismatchConfig values different on server vs client.Ensure .env is identical in both environments.
No types for configTypeScript 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

ItemValue
Main Filenuxt.config.ts
UI Configapp.config.ts
Private ConfigruntimeConfig root (Server only)
Public ConfigruntimeConfig.public (Server & Client)
Env PrefixNUXT_
Nested Env Sep_ (e.g., PUBLIC_API)
Access HookuseRuntimeConfig()
ReactivityuseAppConfig() 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 public object in your runtime config is strictly hidden from the browser. Use this for database passwords and internal API secrets.
  • app.config.ts is 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.ts is 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 .ts files, 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.

Was this helpful?


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!