執行階段配置
警告
- 此功能已過時。 我們建議改用環境變數,其也支援讀取執行階段值。
- 您可以使用
register
函式在伺服器啟動時執行程式碼。- 此功能不適用於自動靜態最佳化、輸出檔案追蹤或 React 伺服器組件。
若要將執行階段配置新增至您的應用程式,請開啟 next.config.js
並新增 publicRuntimeConfig
和 serverRuntimeConfig
配置。
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
的頁面必須使用getInitialProps
或getServerSideProps
,或者您的應用程式必須具有帶有getInitialProps
的自訂 App,才能選擇退出自動靜態最佳化。執行階段配置將無法用於任何未經伺服器端渲染的頁面(或頁面中的組件)。
若要在您的應用程式中存取執行階段配置,請使用 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
這有幫助嗎?