ランタイム設定
警告
- この機能は非推奨です。代わりに、実行時値の読み取りもサポートする環境変数の使用を推奨します。
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
この情報は役立ちましたか?