Runtime Config
Exposing
To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your nuxt.config file, using the runtimeConfig option.
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.
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)$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, and the session helpers 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:
openssl rand -base64 32In 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.
.env file in development, build and generate. But when you run your built server, your .env file will not be read.
Runtime config values are automatically replaced by matching environment variables at runtime.
There are two key requirements:
- Custom runtime config variables must be defined in your
nuxt.config. This ensures that arbitrary environment variables are not exposed to your application code. - 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.
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.Environment variable values are converted to the type of the value they replace:
| 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 (for example NUXT_PORT=abc for a numeric port). See Validating With a Schema to declare the type of a value without giving it a default.
Example
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.orgexport 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 that also implements Standard JSON Schema, such as a schema from Zod or ArkType, or a Valibot schema wrapped in toStandardJsonSchema(). The schema sets the type of the value, and its default value (if any) is used as the default.
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, or set by a module with updateRuntimeConfig(). A plain value set in a higher layer, or in your own nuxt.config, becomes the default for a schema declared further down.
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.
Reading
Vue App
Within the Vue part of your Nuxt app, you will need to call useRuntimeConfig() to access the runtime config.
The behavior is different between the client-side and server-side:
- On client-side, only keys in
runtimeConfig.publicandruntimeConfig.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 you should treat it as read-only. 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 logs a warning when it is mutated during server-side rendering.
<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>useState.Plugins
If you want to use the runtime config within any (custom) plugin, you can use useRuntimeConfig() inside of your defineNuxtPlugin function.
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.
export default defineEventHandler(async (event) => {
const { apiSecret } = useRuntimeConfig()
const result = await $fetch('https://my.api.com/test', {
headers: {
Authorization: `Bearer ${apiSecret}`,
},
})
return result
})Typing Runtime Config
Nuxt generates types for your runtime config from the type of each value, or from its schema. Environment variables are converted to the same types when the server starts, so the 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 rather than by augmenting the RuntimeConfig interface:
import { z } from 'zod'
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: z.string(),
public: {
apiBase: z.url().default('/api'),
},
},
})RuntimeConfig or PublicRuntimeConfig from nuxt/schema changes the types only. Values are still converted according to their default, so an augmented type can describe a value your app never receives.Was this helpful?