執行時期設定 (Runtime Config)

警告:此功能被視為舊版功能,無法與自動靜態優化 (Automatic Static Optimization)輸出檔案追蹤 (Output File Tracing)React 伺服器元件 (React Server Components) 共同使用。請改用環境變數 (environment variables) 以避免初始化開銷。

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

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

請將僅限伺服器端的執行時期設定放在 serverRuntimeConfig 下。

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

依賴 publicRuntimeConfig 的頁面必須使用 getInitialPropsgetServerSideProps,或者您的應用程式必須在自訂 App (Custom App) 中使用 getInitialProps 以退出自動靜態優化 (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