运行时配置
Nuxt 提供了一个运行时配置 API,用于在应用程序中公开配置和秘密信息。
暴露配置
要向应用程序的其余部分公开配置和环境变量,您需要在 nuxt.config
文件中,使用 runtimeConfig
选项定义运行时配置。
nuxt.config.ts
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',
},
},
})
当将 apiBase
添加到 runtimeConfig.public
时,Nuxt 会将其添加到每个页面负载中。我们可以在服务器和浏览器中普遍访问 apiBase
。
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
公共运行时配置可在 Vue 模板中使用
$config.public
访问。序列化
您的运行时配置在传递给 Nitro 之前将被序列化。这意味着任何不能被序列化然后反序列化的内容(例如函数、Set、Map 等)都不应在您的 nuxt.config
中设置。
您可以将这些不可序列化的对象或函数放置在 Nuxt 或 Nitro 插件或中间件中,而不是从 nuxt.config
中传递到您的应用程序。
环境变量
提供配置最常见的方式是使用环境变量.
Nuxt CLI 在开发、构建和生成过程中内置支持读取您的
.env
文件。但是当您运行已构建的服务器时,您的 .env
文件将不会被读取。运行时配置值将在运行时自动被匹配的环境变量替换。
有两个关键要求
- 您所需的变量必须在您的
nuxt.config
中定义。这确保了任意环境变量不会暴露给您的应用程序代码。 - 只有特殊命名的环境变量才能覆盖运行时配置属性。也就是说,一个以
NUXT_
开头、使用_
分隔键和大小写更改的大写环境变量。
将
runtimeConfig
值的默认值设置为不同命名的环境变量(例如将 myVar
设置为 process.env.OTHER_VARIABLE
)只在构建时有效,并在运行时失效。建议使用与您的 runtimeConfig
对象结构匹配的环境变量。示例
.env
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_API_BASE=https://nuxtjs.org.cn
nuxt.config.ts
export 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
},
},
})
读取
Vue 应用程序
在 Nuxt 应用程序的 Vue 部分中,您需要调用 useRuntimeConfig()
来访问运行时配置。
客户端和服务端行为不同
- 在客户端,只有
runtimeConfig.public
和runtimeConfig.app
(Nuxt 内部使用)中的键可用,并且该对象是可写和响应式的。 - 在服务器端,整个运行时配置都可用,但它是只读的,以避免上下文共享。
app/pages/index.vue
<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
将运行时配置键暴露给客户端。插件
如果您想在任何(自定义)插件中使用运行时配置,可以在 defineNuxtPlugin
函数内部使用 useRuntimeConfig()
。
app/plugins/config.ts
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
console.log('API base URL:', config.public.apiBase)
})
服务器路由
您也可以在服务器路由中通过 useRuntimeConfig
访问运行时配置。
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
})
运行时配置类型
Nuxt 尝试使用以下工具自动从提供的运行时配置生成 TypeScript 接口unjs/untyped.
但也可以手动为您的运行时配置添加类型
index.d.ts
declare module 'nuxt/schema' {
interface RuntimeConfig {
apiSecret: string
}
interface PublicRuntimeConfig {
apiBase: string
}
}
// It is always important to ensure you import/export something when augmenting a type
export {}
nuxt/schema
旨在方便终端用户访问其项目中使用的 Nuxt schema 版本。模块作者应转而扩充 @nuxt/schema
。