---
title: "Runtime Config"
description: "Nuxt provides a runtime config API to expose configuration and secrets within your application."
canonical_url: "https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/guide/going-further/runtime-config"
---
# Runtime Config

> Nuxt provides a runtime config API to expose configuration and secrets within your application.

## Exposing

To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your [`nuxt.config`](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/directory-structure/nuxt-config) file, using the [`runtimeConfig`](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/api/nuxt-config#runtimeconfig-1) option.

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  runtimeConfig: {
    // The private keys which are only available within server-side
    apiSecret: '123',
    // Keys within public, will be also exposed to the client-side
    public: {
      apiBase: '/api',
    },
  },
})
```

When adding `apiBase` to the `runtimeConfig.public`, Nuxt adds it to each page payload. We can universally access `apiBase` in both server and browser.

```ts
const runtimeConfig = useRuntimeConfig()

console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
```

::tip
Public runtime config is accessible in Vue templates with `$config.public`.
::

### Application Secret

Runtime config keys prefixed with `app` are reserved for Nuxt (currently `runtimeConfig.app` and `runtimeConfig.appSecret`). Do not use them for your own values.

Nuxt provides a private `runtimeConfig.appSecret` as the application's root secret. Modules and server features derive their own secrets from it with [`deriveSecret`](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/guide/going-further/server-imports#deriving-secrets), and the [session helpers](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/guide/going-further/server-imports#sessions) seal with one by default. The value defaults to an empty string, is only available on the server, and you can set it with `NUXT_APP_SECRET` without declaring the key in `nuxt.config`.

Generate a secret that contains at least 32 random bytes:

```bash [Terminal]
openssl rand -base64 32
```

::important
Use a different value for each environment, but keep it stable across deployments and server instances within that environment. Changing the value invalidates any sessions or signatures that depend on it.
::

Nitro parses environment overrides, so a secret made only of digits or one that looks like JSON arrives as a number, boolean or object rather than a string. Wrap such a value in quotes (`NUXT_APP_SECRET='"12345..."'`) or set `runtimeConfig.appSecret` in `nuxt.config` instead.

In development, Nuxt generates a random secret and stores it in `.nuxt/app-secret` only when `appSecret` is unset, so features that depend on it work without any setup. A configured value is always used as is. Nuxt logs a warning the first time a derived secret is used with the generated value. Builds never generate one: set `NUXT_APP_SECRET` in every environment you deploy to.

Nuxt does not require `NUXT_APP_SECRET` unless a module or server feature uses it.

### Serialization

Your runtime config will be serialized before being passed to Nitro. This means that anything that cannot be serialized and then deserialized (such as functions, Sets, Maps, and so on), should not be set in your `nuxt.config`.

Instead of passing non-serializable objects or functions into your application from your `nuxt.config`, you can place this code in a Nuxt or Nitro plugin or middleware.

### Environment Variables

The most common way to provide configuration is by using environment variables.

::note
The Nuxt CLI has built-in support for reading your `.env` file in development, build and generate. But when you run your built server, **your `.env` file will not be read**.
:read-more{to="https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/directory-structure/env"}
::

Runtime config values are **automatically replaced by matching environment variables at runtime**.

There are two key requirements:

1. Custom runtime config variables must be defined in your `nuxt.config`. This ensures that arbitrary environment variables are not exposed to your application code.
2. Only a specially-named environment variable can override a runtime config property. That is, an uppercase environment variable starting with `NUXT_` which uses `_` to separate keys and case changes.

::warning
Setting the default of `runtimeConfig` values to *differently named environment variables* (for example setting `myVar` to `process.env.OTHER_VARIABLE`) will only work during build-time and will break on runtime.
It is advised to use environment variables that match the structure of your `runtimeConfig` object.

Values set in `nuxt.config`, including values read from `process.env`, are written into the server build output. Anyone who can read your project files, including clients of a dev server you have exposed to the network, can read them. Leave private values empty in `nuxt.config` and provide them with `NUXT_` environment variables, as in the [example below](#example).
::

::warning
Environment variable values are automatically cast to their JavaScript type using [`destr`](https://github.com/unjs/destr). For example, `NUXT_MY_VAR=4848e0` becomes the number `4848`. To keep a value a string, the environment variable value itself must contain literal double quotes: in a `.env` file, write `NUXT_MY_VAR='"4848e0"'`; when setting the variable directly (in a shell, Dockerfile, or hosting dashboard), make sure the quotes are part of the value and not stripped by the shell (for example `NUXT_MY_VAR='"4848e0"' node .output/server/index.mjs`).

Values declared [with a schema](#validating-with-a-schema) are converted to the type of their schema instead, so `NUXT_MY_VAR=4848e0` stays a string for a `z.string()` value.
::

With `future.compatibilityVersion: 5`, every environment variable value is converted to the type of the value it replaces rather than cast with `destr`:

| Type of the default | Environment variable            | Value                                                        |
| ------------------- | ------------------------------- | ------------------------------------------------------------ |
| `string`            | `NUXT_MY_VAR=4848e0`            | `'4848e0'`                                                   |
| `number`            | `NUXT_MY_VAR=8080`              | `8080`                                                       |
| `boolean`           | `NUXT_MY_VAR=false`             | `false` (also `true`, `1`, `0`, `yes`, `no`, `on` and `off`) |
| array               | `NUXT_MY_VAR='["value"]'`       | `['value']`                                                  |
| object              | `NUXT_MY_VAR='{"key":"value"}'` | `{ key: 'value' }`, merged over the default                  |

A plain default of `null` or `undefined` is replaced with an empty string, so it is set as a string. To keep a `null` default and still coerce a variable to another type, use a schema such as `z.number().nullable().default(null)`.

Nested keys of an object can also be set individually, such as `NUXT_SESSION_MAX_AGE` for `runtimeConfig.session.maxAge`. An empty variable is ignored for a key that cannot be an empty string.

The server does not start if an environment variable cannot be converted to the type of a schema in your `nuxt.config`, or with `compatibilityVersion: 5` to the type of any schema or default (for example `NUXT_PORT=abc` for a numeric `port`). For a schema set by a module, Nuxt warns instead and the value keeps its default. See [Validating With a Schema](#validating-with-a-schema) to declare the type of a value without giving it a default.

::tip{icon="i-lucide-video" to="https://youtu.be/_FYV5WfiWvs" target="_blank"}
Watch a video from Alexander Lichter showcasing the top mistake developers make using runtimeConfig.
::

#### Example

```ini [.env]
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org
```

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  runtimeConfig: {
    apiSecret: '', // can be overridden by NUXT_API_SECRET environment variable
    public: {
      apiBase: '', // can be overridden by NUXT_PUBLIC_API_BASE environment variable
    },
  },
})
```

### Validating With a Schema

Any value in `runtimeConfig` can be a [Standard Schema](https://standardschema.dev) that also implements [Standard JSON Schema](https://standardschema.dev/json-schema), such as a schema from [Zod](https://zod.dev) or [ArkType](https://arktype.io), or a [Valibot](https://valibot.dev) schema wrapped in `toStandardJsonSchema()`. The schema sets the type of the value, and its default value (if any) is used as the default.

```ts [nuxt.config.ts]
import { z } from 'zod'

export default defineNuxtConfig({
  runtimeConfig: {
    apiSecret: z.string(),
    session: z.object({
      maxAge: z.number().int().default(60 * 60),
      secure: z.boolean().default(true),
    }),
    public: {
      mode: z.enum(['preview', 'production']).default('production'),
    },
  },
})
```

A value without a default, such as `apiSecret` above, is required. Nuxt warns about a missing value while building, and the server does not start until it is provided (here with `NUXT_API_SECRET`). While prerendering, only reading a missing value throws, so a page that depends on it fails to prerender while other pages are unaffected. Make a value optional with `z.string().optional()` or the equivalent in your schema library.

The schema can also be used for the whole `runtimeConfig`, set in the `nuxt.config` of a [layer](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/getting-started/layers), or set by a module with [`updateRuntimeConfig()`](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/api/kit/runtime-config#schemas). A plain value set in a higher layer, or in your own `nuxt.config`, becomes the default for a schema declared further down.

Unless `compatibilityVersion: 5` is enabled, an invalid or missing value only stops the server, or a prerendered page, when its schema is declared in a `nuxt.config`. For a schema set by a module, Nuxt warns when the server starts and the value keeps its default.

When the server starts, Nuxt checks the runtime config against a compact description of each schema: the type of each value, which values are required, and the allowed values of enums and unions. In development and while building, Nuxt also warns about values that do not match with the environment variables in use at the time.

::note
The schema itself is not included in your server bundle. Refinements, such as a minimum length or a URL format, are not checked, and transforms are not supported.
::

## Reading

### Vue App

Within the Vue part of your Nuxt app, you will need to call [`useRuntimeConfig()`](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/api/composables/use-runtime-config) to access the runtime config.

::important
The behavior is different between the client-side and server-side:

- On client-side, only keys in `runtimeConfig.public` and `runtimeConfig.app` (which is used by Nuxt internally) are available, and the object is both writable and reactive.
- On server-side, the entire runtime config is available, but it is read-only to avoid context sharing. When the server is built with [Nitro v3](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/getting-started/upgrade#testing-nitro-v3), it is a single object shared by every request, so a change made while rendering one request is visible to all later ones. In development, Nuxt then logs a warning when it is mutated during server-side rendering.
::

```vue [app/pages/index.vue]
<script setup lang="ts">
const config = useRuntimeConfig()

console.log('Runtime config:', config)
if (import.meta.server) {
  console.log('API secret:', config.apiSecret)
}
</script>

<template>
  <div>
    <div>Check developer console!</div>
  </div>
</template>
```

::caution
**Security note:** Be careful not to expose runtime config keys to the client-side by either rendering them or passing them to `useState`.
::

### Plugins

If you want to use the runtime config within any (custom) plugin, you can use [`useRuntimeConfig()`](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/api/composables/use-runtime-config) inside of your `defineNuxtPlugin` function.

```ts [app/plugins/config.ts]
export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()

  console.log('API base URL:', config.public.apiBase)
})
```

### Server Routes

You can access runtime config within the server routes as well using `useRuntimeConfig`.

```ts [server/api/test.ts]
export default defineEventHandler(async (event) => {
  const { apiSecret } = useRuntimeConfig(event)
  const result = await $fetch('https://my.api.com/test', {
    headers: {
      Authorization: `Bearer ${apiSecret}`,
    },
  })
  return result
})
```

::note
Giving the `event` as argument to `useRuntimeConfig` is optional, but it is recommended to pass it to get the runtime config overwritten by [environment variables](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/docs/4.x/guide/going-further/runtime-config#environment-variables) at runtime for server routes.
::

## Typing Runtime Config

Nuxt generates types for your runtime config from the type of each value, or from its schema. Values declared with a schema are converted to the same types when the server starts, so their generated types describe the values your app receives.

To give a value a type that its default does not describe, such as a value without a default, an enum or a union, declare it [with a schema](#validating-with-a-schema) rather than by augmenting the `RuntimeConfig` interface:

```ts [nuxt.config.ts]
import { z } from 'zod'

export default defineNuxtConfig({
  runtimeConfig: {
    apiSecret: z.string(),
    public: {
      apiBase: z.url().default('/api'),
    },
  },
})
```

::warning
Augmenting `RuntimeConfig` or `PublicRuntimeConfig` from `nuxt/schema` changes the types only. Values without a schema are still cast with `destr`, so an augmented type can describe a value your app never receives.
::


## Sitemap

See the full [sitemap](https://nuxt-git-feat-image-docs-nuxt-js.vercel.app/sitemap.md) for all pages.
