執行時期設定 (Runtime Config)

警告:

若要為您的應用程式新增執行時期設定,請開啟 next.config.js 並新增 publicRuntimeConfigserverRuntimeConfig 設定:

next.config.js
module.exports = {
  serverRuntimeConfig: {
    // 僅在伺服器端可用
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // 透過環境變數傳遞
  },
  publicRuntimeConfig: {
    // 在伺服器端與客戶端皆可用
    staticFolder: '/static',
  },
}

將任何僅限伺服器使用的執行時期設定置於 serverRuntimeConfig 下。

任何客戶端與伺服器端程式碼皆可存取的內容應置於 publicRuntimeConfig 下。

依賴 publicRuntimeConfig 的頁面必須使用 getInitialPropsgetServerSideProps,或者您的應用程式必須擁有帶有 getInitialProps自訂 App (Custom App) 以退出自動靜態優化 (Automatic Static Optimization)。若未進行伺服器端渲染,執行時期設定將無法用於任何頁面(或頁面中的元件)。

要在應用程式中存取執行時期設定,請使用 next/config,如下所示:

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

// 僅包含 serverRuntimeConfig 與 publicRuntimeConfig
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
// 僅在伺服器端可用
console.log(serverRuntimeConfig.mySecret)
// 在伺服器端與客戶端皆可用
console.log(publicRuntimeConfig.staticFolder)

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

export default MyImage