Runtime config and environment variables
Some values differ between your computer and the production server: API keys, passwords, the site address. They are not written into the code but set as environment variables, values the operating system passes to a running program. In Nuxt such settings are described in the runtimeConfig section of nuxt.config.ts.
Describing the settings
// nuxt.config.ts
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
runtimeConfig: {
adminPassword: '',
public: {
siteName: 'My blog'
}
}
})Values in nuxt.config.ts are defaults. Top-level keys (adminPassword) are available only on the server. Keys inside public are visible in the browser too.
The .env file
Create a .env file in the project root:
NUXT_ADMIN_PASSWORD=secret123
NUXT_PUBLIC_SITE_NAME="Anna's blog"Nuxt matches variables to settings by name: the NUXT_ prefix, then the key name in capitals with underscores between words. NUXT_PUBLIC_ refers to the public section. Restart npm run dev so Nuxt reads the file. Add .env to .gitignore: passwords must not end up in the repository.
Reading on the server
// server/api/admin/check.post.ts
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig(event)
const body = await readBody<{ password?: string }>(event)
if (body.password !== config.adminPassword) {
throw createError({ statusCode: 401, message: 'Wrong password' })
}
return { ok: true }
})useRuntimeConfig(event) returns all settings. A request with the password secret123 gets { ok: true }, any other gets a 401 error.
Reading in components
<!-- app/layouts/default.vue -->
<script setup lang="ts">
const config = useRuntimeConfig()
</script>
<template>
<header>
<NuxtLink to="/">{{ config.public.siteName }}</NuxtLink>
</header>
</template>The header shows "Anna's blog" from .env. Reading config.adminPassword in the browser returns undefined: secret keys are not sent there.
runtimeConfig and appConfig
| Where | What for |
|---|---|
runtimeConfig | Values changed by environment variables, secrets included |
app/app.config.ts | Public look-and-feel settings known at build time: colours, texts |
.env on the production server
The .env file is read only during development, build and npm run preview. On the production server, variables are set through the hosting tools or at startup: NUXT_ADMIN_PASSWORD=... node .output/server/index.mjs.
Common mistake
Putting a secret into the public section: public: { apiKey: '...' }. Everything in public ends up in the HTML and in the JavaScript any visitor downloads. Keep API keys and passwords at the top level of runtimeConfig and use them only in the server/ folder.