---
title: "运行时配置"
description: "了解如何将 Nuxt 2 的运行时配置迁移到 Nuxt 3。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/migration/runtime-config"
---
# 运行时配置

> 了解如何将 Nuxt 2 的运行时配置迁移到 Nuxt 3。

如果你希望在 Nuxt 3 应用中引用环境变量，你需要使用运行时配置（runtime config）。

在组件中引用这些变量时，你需要在 setup 方法（或 Nuxt 插件）中使用 [`useRuntimeConfig`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-runtime-config) 组合式函数。

在应用的 `server/` 部分中，你可以无需导入即可使用 [`useRuntimeConfig`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-runtime-config)。

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/guide/going-further/runtime-config"}
::

## 迁移

1. 将应用中使用的所有环境变量添加到 `nuxt.config` 文件的 `runtimeConfig` 属性中。
2. 将应用的 Vue 部分中的 `process.env` 迁移为 [`useRuntimeConfig`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-runtime-config)。

::code-group
```ts [nuxt.config.ts]
export default defineNuxtConfig({
  runtimeConfig: {
    // Private config that is only available on the server
    apiSecret: '123',
    // Config within public will be also exposed to the client
    public: {
      apiBase: '/api',
    },
  },
})
```

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

// instead of process.env you will now access config.public.apiBase
console.log(config.public.apiBase)
</script>
```

```ts [server/api/hello.ts]
export default defineEventhandler((event) => {
  const config = useRuntimeConfig(event)
  // In server, you can now access config.apiSecret, in addition to config.public
  console.log(config.apiSecret)
  console.log(config.public.apiBase)
})
```

```ini [.env]
# Runtime config values are automatically replaced by matching environment variables at runtime
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org
```
::


## Sitemap

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