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

> Nuxt 提供了运行时配置 API，用于在应用程序中公开配置和机密信息。

## 公开配置

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

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

将 `apiBase` 添加到 `runtimeConfig.public` 后，Nuxt 会将其添加到每个页面负载中。我们可以在服务器和浏览器端统一访问 `apiBase`。

```ts
const runtimeConfig = useRuntimeConfig()

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

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

### 序列化

您的运行时配置在传递给 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/3.x/directory-structure/env"}
::

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

有两个关键要求：

1. 你希望的变量必须在 `nuxt.config` 中定义。这样可以确保不会暴露任意环境变量给应用代码。
2. 只有特定命名的环境变量可以覆盖运行时配置属性。即以大写字母开头且以 `NUXT_` 前缀的环境变量，使用 `_` 连接键名和大小写转换。

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

::tip{icon="i-lucide-video" to="https://youtu.be/_FYV5WfiWvs" target="_blank"}
观看 Alexander Lichter 关于开发者使用 runtimeConfig 时常犯重大错误的视频。
::

#### 示例

```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/3.x/api/composables/use-runtime-config) 来访问运行时配置。

::important
客户端和服务器端行为不同：

- 客户端：只能访问 `runtimeConfig.public` 和 `runtimeConfig.app`（Nuxt 内部使用）中的键，且对象是可写且响应式的。
- 服务器端：可以访问完整的运行时配置，但为避免上下文共享，该对象为只读。
::

```vue [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` 将运行时配置的敏感键暴露给客户端。
::

### 插件

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

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

  console.log('API base 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
向 `useRuntimeConfig` 传入 `event` 参数是可选的，但建议传入，以便服务器路由中的运行时配置能在运行时被[环境变量](https://nuxt.zhcndoc.com/docs/3.x/guide/going-further/runtime-config#environment-variables)覆盖。
::

## 运行时配置的类型定义

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`。
::


## Sitemap

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