---
title: "运行时配置"
description: "Nuxt 提供了一个运行时配置 API，用于在应用中公开配置和密钥。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/runtime-config"
---
# 运行时配置

> Nuxt 提供了一个运行时配置 API，用于在应用中公开配置和密钥。

## 暴露

要向应用的其余部分公开配置和环境变量，你需要在 [`nuxt.config`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/nuxt-config) 文件中使用 [`runtimeConfig`](https://nuxt.zhcndoc.com/docs/4.x/api/nuxt-config#runtimeconfig) 选项定义运行时配置。

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  runtimeConfig: {
    // 只有服务器端可用的私有密钥
    apiSecret: '123',
    // public 中的键也会暴露给客户端
    public: {
      apiBase: '/api',
    },
  },
})
```

当把 `apiBase` 添加到 `runtimeConfig.public` 时，Nuxt 会把它加入到每个页面的 payload 中。我们可以在服务端和浏览器端通用地访问 `apiBase`。

```ts
const runtimeConfig = useRuntimeConfig()

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

<tip>

公共运行时配置可以在 Vue 模板中通过 `$config.public` 访问。

</tip>

### 应用密钥

以 `app` 为前缀的运行时配置键由 Nuxt 保留（目前包括 `runtimeConfig.app` 和 `runtimeConfig.appSecret`）。请勿将它们用于你自己的值。

Nuxt 提供了私有的 `runtimeConfig.appSecret`，作为应用的根密钥。模块和服务器功能会使用 [`deriveSecret`](https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/server-imports#deriving-secrets) 从中派生各自的密钥，并且 [会话辅助函数](https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/server-imports#sessions) 默认使用它进行密封。该值默认为空字符串，仅在服务器端可用，并且你可以通过 `NUXT_APP_SECRET` 设置它，而无需在 `nuxt.config` 中声明此键。

生成一个至少包含 32 个随机字节的密钥：

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

<important>

为每个环境使用不同的值，但要确保该值在同一环境中的各次部署和服务器实例之间保持稳定。更改该值会使依赖它的任何会话或签名失效。

</important>

Nitro 会解析环境变量覆盖值，因此，仅由数字组成或看起来像 JSON 的密钥会被解析为数字、布尔值或对象，而不是字符串。请将这类值用引号括起来（`NUXT_APP_SECRET='"12345..."'`），或改为在 `nuxt.config` 中设置 `runtimeConfig.appSecret`。

在开发环境中，如果未设置 `appSecret`，Nuxt 会生成一个随机密钥并将其存储在 `.nuxt/app-secret` 中，这样依赖它的功能无需任何设置即可运行。已配置的值始终会按原样使用。派生密钥首次使用生成的值时，Nuxt 会记录一条警告。构建时不会生成密钥：请在每个部署环境中设置 `NUXT_APP_SECRET`。

除非某个模块或服务器功能使用 `NUXT_APP_SECRET`，否则 Nuxt 不会要求设置它。

### 序列化

你的运行时配置会在传递给 Nitro 之前被序列化。这意味着任何不能被序列化然后反序列化的东西（例如函数、Set、Map 等）都不应当在你的 `nuxt.config` 中设置。

如果需要把不可序列化的对象或函数传入应用，建议将这段代码放在 Nuxt 或 Nitro 的插件或中间件中。

### 环境变量

提供配置最常见的方式是使用 [环境变量](https://medium.com/chingu/an-introduction-to-environment-variables-and-how-to-use-them-f602f66d15fa)。

<note>

Nuxt CLI 内置了对在开发、构建和生成过程中读取 `.env` 文件的支持。但运行构建后的服务器时，**不会读取你的 .env 文件**。

<read-more to="https://nuxt.zhcndoc.com/docs/4.x/directory-structure/env">



</read-more>
</note>

运行时配置值会在运行时**自动被匹配的环境变量替换**。

有两个关键要求：

1. 自定义运行时配置变量必须在你的 `nuxt.config` 中定义。这可以确保任意环境变量不会暴露给你的应用代码。
2. 只有特定命名的环境变量可以覆盖运行时配置属性。也就是说，必须是以 `NUXT_` 为前缀的全大写环境变量，并使用 `_` 来分隔键和大小写变化。

<warning>

将 `runtimeConfig` 值的默认值设置为*不同命名的环境变量*（例如将 `myVar` 设置为 `process.env.OTHER_VARIABLE`）只会在构建时生效，运行时会失效并导致问题。
建议使用与 `runtimeConfig` 对象结构相匹配的环境变量。

</warning>

<warning>

环境变量值会使用 [`destr`](https://github.com/unjs/destr) 自动转换为对应的 JavaScript 类型。例如，`NUXT_MY_VAR=4848e0` 会变成数字 `4848`。如果要保持值为字符串，环境变量值本身必须包含字面量双引号：在 `.env` 文件中写 `NUXT_MY_VAR='"4848e0"'`；当直接设置变量时（例如在 shell、Dockerfile 或托管控制面板中），要确保引号是值的一部分，而不是被 shell 去掉（例如 `NUXT_MY_VAR='"4848e0"' node .output/server/index.mjs`）。

</warning>

<tip icon="i-lucide-video" target="_blank" to="https://youtu.be/_FYV5WfiWvs">

观看 Alexander Lichter 的视频，了解开发者在使用 runtimeConfig 时最常犯的错误。

</tip>

#### 示例

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

```ts [nuxt.config.ts]
export default defineNuxtConfig({
  runtimeConfig: {
    apiSecret: '', // 可以被 NUXT_API_SECRET 环境变量覆盖
    public: {
      apiBase: '', // 可以被 NUXT_PUBLIC_API_BASE 环境变量覆盖
    },
  },
})
```

## 读取

### Vue 应用

在 Nuxt 应用的 Vue 部分，你需要调用 [`useRuntimeConfig()`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-runtime-config) 来访问运行时配置。

<important>

客户端和服务端的行为不同：

- 在客户端，只有 `runtimeConfig.public` 和 `runtimeConfig.app`（Nuxt 内部使用）中的键可用，并且对象是可写且响应式的。
- 在服务端，整个运行时配置都是可用的，但为避免上下文共享，配置是只读的。

</important>

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

console.log('运行时配置:', config)
if (import.meta.server) {
  console.log('API 密钥:', config.apiSecret)
}
</script>

<template>
  <div>
    <div>查看开发者控制台！</div>
  </div>
</template>
```

<caution>

**安全提示：** 注意不要通过渲染或传递给 `useState` 的方式将运行时配置的键暴露给客户端。

</caution>

### 插件

如果你想在任何（自定义）插件中使用运行时配置，可以在 `defineNuxtPlugin` 函数中使用 [`useRuntimeConfig()`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-runtime-config)。

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

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

### 服务器路由

你也可以在服务器路由中使用 `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>

将 `event` 作为参数传递给 `useRuntimeConfig` 是可选的，但建议传入它，以便服务器路由在运行时通过[环境变量](https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/runtime-config#environment-variables)覆盖运行时配置。

</note>

Nuxt 会尝试使用 [unjs/untyped](https://github.com/unjs/untyped) 从提供的运行时配置自动生成 TypeScript 接口。

但你也可以手动为运行时配置添加类型：

```ts [index.d.ts]
declare module 'nuxt/schema' {
  interface RuntimeConfig {
    apiSecret: string
  }
  interface PublicRuntimeConfig {
    apiBase: string
  }
}
// 在扩展类型时确保导入/导出某些内容总是很重要的
export {}
```

<note>

`nuxt/schema` 为最终用户提供了一种便捷方式，用于访问 Nuxt 在其项目中使用的模式版本。模块作者应当改为扩展 `@nuxt/schema`。

</note>


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
