跳至內容

執行時期設定 (Runtime Config)

警告 (Warning)

要在應用程式中新增執行階段設定,請開啟 next.config.js 並新增 publicRuntimeConfigserverRuntimeConfig 設定

next.config.js
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 下。

任何客戶端和伺服器端程式碼皆可存取的設定都應放在 publicRuntimeConfig 下。

依賴 publicRuntimeConfig 的頁面**必須**使用 getInitialPropsgetServerSideProps,或者您的應用程式必須具有帶有 getInitialProps自訂應用程式 以停用 自動靜態優化。未經伺服器端渲染的頁面(或頁面中的元件)將無法使用執行階段設定。

要存取應用程式中的執行階段設定,請使用 next/config,如下所示

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