Skip to main content

运行时配置

警告:

¥Warning:

要将运行时配置添加到你的应用,请打开 next.config.js 并添加 publicRuntimeConfigserverRuntimeConfig 配置:

¥To add runtime configuration to your app, open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:

module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
staticFolder: '/static',
},
}

将任何仅服务器运行时配置放在 serverRuntimeConfig 下。

¥Place any server-only runtime config under serverRuntimeConfig.

客户端和服务器端代码均可访问的任何内容都应位于 publicRuntimeConfig 下。

¥Anything accessible to both client and server-side code should be under publicRuntimeConfig.

依赖 publicRuntimeConfig 的页面必须使用 getInitialPropsgetServerSideProps,或者你的应用必须具有 自定义应用getInitialProps 才能选择退出 自动静态优化。如果没有服务器端渲染,运行时配置将不可用于任何页面(或页面中的组件)。

¥A page that relies on publicRuntimeConfig must use getInitialProps or getServerSideProps or your application must have a Custom App with getInitialProps to opt-out of Automatic Static Optimization. Runtime configuration won't be available to any page (or component in a page) without being server-side rendered.

要访问应用中的运行时配置,请使用 next/config,如下所示:

¥To get access to the runtime configs in your app use next/config, like so:

import getConfig from 'next/config'
import Image from 'next/image'

// Only holds serverRuntimeConfig and publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// Will only be available on the server-side
console.log(serverRuntimeConfig.mySecret)
// Will be available on both server-side and client-side
console.log(publicRuntimeConfig.staticFolder)

function MyImage() {
return (
<div>
<Image
src={`${publicRuntimeConfig.staticFolder}/logo.png`}
alt="logo"
layout="fill"
/>
</div>
)
}

export default MyImage