Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 32 ยท Server and API

Runtime config and environment variables

Configure a Nuxt app safely: runtimeConfig vs app.config, public keys, NUXT_ environment overrides, build time vs runtime, and how to avoid leaking secrets.

Every real app needs settings that change between your laptop, a test server and production: a database URL, an API base address, a payment key, a site name. Hard-coding them is wrong, and committing secrets to Git is worse. Nuxt gives you two official places for settings, runtime config and app config, and a simple rule for filling them from environment variables.

This lesson shows what goes where, how the NUXT_ naming rule works, why "build time" and "runtime" are different moments, and how secrets leak when you get it wrong. Nuxt code is read-only on this site, because the framework cannot run here. Two Node stand-ins run live: one merges environment variables into a config object using the same naming rule, and one shows exactly what the browser receives. They are models of the behavior, not Nuxt itself.

Two places for settings

runtimeConfig Server secrets and public values; env can override.
app.config.ts Public UI settings fixed at build time.
1 / 3

runtimeConfig

You declare settings in nuxt.config.ts under runtimeConfig. Keys at the top level are private: they exist only on the server. Keys inside public are public: they are available on the server and in the browser.

TypeScript
// nuxt.config.ts (read-only)
export default defineNuxtConfig({
  runtimeConfig: {
    dbUrl: '',                 // private, filled from the environment
    apiSecret: 'dev-secret',   // private, with a safe local default
    public: {
      apiBase: '/api',         // public
      siteName: 'My Shop',     // public
    },
  },
});

You read the values with useRuntimeConfig():

TypeScript
// server/api/orders.get.ts (read-only)
export default defineEventHandler(async () => {
  const config = useRuntimeConfig();
  return await fetchOrders(config.dbUrl, config.apiSecret); // server: everything is available
});
VUE
<!-- app/pages/index.vue (read-only) -->
<script setup lang="ts">
const config = useRuntimeConfig();
// In the browser only config.public exists. config.apiSecret is not there.
const base = config.public.apiBase;
</script>

Use useRuntimeConfig(event) inside server handlers when your Nuxt version asks for the event; the plain call works in most code. Treat the config object as read-only: changing it at run time is not supported and changes would not be shared the way you hope.

The NUXT_ environment rule

Here is the idea that makes runtime config useful: any key declared in runtimeConfig can be overridden by an environment variable, without rebuilding. The name is built from the key path:

  1. Write the path with each part in UPPER_SNAKE_CASE.
  2. Join the parts with _.
  3. Start with NUXT_.

So apiSecret becomes NUXT_API_SECRET, and public.apiBase becomes NUXT_PUBLIC_API_BASE (the word public is part of the path). A nested key such as public.analytics.enabled becomes NUXT_PUBLIC_ANALYTICS_ENABLED.

Two details matter in practice:

  • A key must exist in nuxt.config.ts to be overridable. Declare it with an empty string or a default value. Setting NUXT_SOMETHING_NEW for a key you never declared does nothing.
  • Environment values are strings, but simple values such as true or a number are converted to match. Check the type in your own app rather than assuming, and keep the default in the config so a missing variable gives a predictable value.

The first stand-in applies this rule. It builds each env name from a key path and merges matching variables into the config. Real Nuxt does this inside Nitro when the server starts; this version is only the naming and merging idea.

Node.js NUXT_ variables override runtimeConfig

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output starts with the three env names (NUXT_API_SECRET, NUXT_PUBLIC_API_BASE, NUXT_PUBLIC_ANALYTICS_ENABLED) followed by the merged config. Look at what happened: dbUrl and public.apiBase were replaced, analytics.enabled changed from false to the boolean true, apiSecret kept its default because no NUXT_API_SECRET was set, and NUXT_PUBLIC_UNKNOWN_KEY and DATABASE_URL were ignored, the first because no such key is declared and the second because it has no NUXT_ prefix.

Build time versus runtime

This is the most misunderstood part, so take it slowly. A Nuxt app goes through two moments:

  • Build time is when you run nuxt build. Your code is compiled into the .output/ folder.
  • Runtime is when the built server is running and answering requests.

runtimeConfig is resolved at runtime. You build once, and the same .output can run in staging with one set of variables and in production with another. That is exactly why it exists.

Other things happen at build time and are frozen into the output: values you read directly in nuxt.config.ts, anything that depends on process.env in a module that is bundled at build, and pages that are prerendered (see Rendering modes). If you read process.env.API_URL straight in a component or a config option, the value found while building is the one you ship.

Two more points about where variables come from:

  • In development, Nuxt loads a .env file from the project root for you.
  • In production, the built server does not read .env by itself. Provide real environment variables from your host, container or process manager. On Node 20 or newer, node --env-file=.env .output/server/index.mjs loads a file explicitly, which is handy on a plain server.

Keep a .env.example in Git with the names and harmless sample values, and keep the real .env out of Git with .gitignore.

app.config.ts

app.config.ts is the second place. It holds public, non-secret settings that are known at build time, usually for the interface:

TypeScript
// app/app.config.ts (read-only)
export default defineAppConfig({
  theme: { primary: '#0b6cff', radius: 8 },
  socials: { github: 'https://github.com/example' },
});
TypeScript
const appConfig = useAppConfig();
console.log(appConfig.theme.primary);

The differences are worth memorizing:

runtimeConfig app.config.ts
Resolved at runtime at build time
Environment variables yes, with NUXT_ no
Secrets yes (top level, server only) never; always public
Reactive and updatable in the browser no yes
Typical content URLs, keys, flags theme, labels, UI options

A good test: if the value must differ per environment or must be secret, it is runtimeConfig. If it is a design decision you would change by editing code, it is app.config.ts.

How secrets leak

The most serious mistake is putting a secret under public. Everything in runtimeConfig.public is serialized into the HTML of every page so the browser can read it. Anyone can open "view source" and copy it. The same happens when you return useRuntimeConfig() from an API route or pass the whole config to a component prop: the top-level private keys come along.

The second stand-in plays out what the browser sees. It models the page payload as one JSON blob inside a script tag. Real Nuxt uses its own serialization format, but the principle holds: only public is sent.

Node.js What the browser actually receives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The output proves the point: the server view has the keys stripeSecretKey, dbUrl and public, while the client payload has only public, and the HTML holds 0 secrets. After the mistake, one secret appears in the HTML and the guard prints WARNING: public.stripeSecretKey looks secret. A tiny check like that in your tests or CI is cheap insurance.

Some values are meant to be public. A Stripe publishable key, an analytics site id or the URL of your public API belong in public. Ask one question for each value: "Would I be fine with a stranger reading this?" If not, keep it at the top level and use it only in server/ code.

Practical habits

  • Declare every setting in nuxt.config.ts with a safe default (an empty string is fine) so the key is overridable and the shape is documented.
  • Read private config only in server/ code. Return only the fields a page needs from your API routes.
  • Name the same secret the same way everywhere: key in config, NUXT_ variable in the environment, entry in .env.example.
  • Never log the whole config.
  • Fail early: check at startup that required values are non-empty and throw a clear error if not.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which environment variable overrides runtimeConfig.public.apiBase?

    The name is NUXT_ plus the key path in UPPER_SNAKE_CASE. The path includes the public segment, giving NUXT_PUBLIC_API_BASE.
  2. 2. Where does a private runtimeConfig key such as apiSecret exist?

    Top-level runtimeConfig keys stay on the server. Only the public section is sent to the browser.
  3. 3. Why does an environment override of a key you never declared in nuxt.config.ts have no effect?

    Nuxt looks up the env names of the keys it knows about. Declare a key with a default or an empty string to make it overridable.
  4. 4. Which value belongs in app.config.ts rather than runtimeConfig?

    app.config.ts holds public, build-time UI settings. Secrets and per-environment values belong in runtimeConfig.
  5. 5. What is the main risk of putting a secret key under runtimeConfig.public?

    Public config is included in the page payload for the browser, so it must contain nothing you want to keep private.

Summary

  • runtimeConfig holds settings: top-level keys are private and server-only, public keys are sent to the browser.
  • A declared key is overridden by NUXT_ plus its path in UPPER_SNAKE_CASE, such as NUXT_PUBLIC_API_BASE, without rebuilding.
  • Build time freezes what you read directly; runtime config is resolved when the server runs.
  • Production does not read .env automatically: supply real environment variables.
  • app.config.ts is for public, build-time UI settings and cannot use environment overrides.
  • Never put secrets under public, and read private config only in server code.

Next, connect your server routes to real data in Databases and ORMs.