# 运行时配置

一般来说,你会想要使用“构建时环境变量”来提供你的配置。这样做的原因是运行时配置增加了渲染/初始化开销,并且与“自动静态优化”不兼容。

To add runtime configuration to your app open next.config.jsand add the publicRuntimeConfigand serverRuntimeConfigconfigs:

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',
  },
}

Place any server-only runtime config under serverRuntimeConfig.

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

A page that relies on publicRuntimeConfigmustuse getInitialPropsto opt-out of Automatic Static Optimization . Runtime configuration won't be available to any page (or component in a page) without getInitialProps.

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

Introduction to next.config.jsLearn more about the configuration file used by Next.js. Environment VariablesAccess environment variables in your Next.js application at build time.

Last Updated: 5/13/2023, 8:55:38 PM