ランタイム設定

警告:

アプリにランタイム設定を追加するには、next.config.jsを開き、publicRuntimeConfigserverRuntimeConfig設定を追加します:

next.config.js
module.exports = {
  serverRuntimeConfig: {
    // サーバーサイドでのみ利用可能
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // 環境変数を渡す
  },
  publicRuntimeConfig: {
    // サーバーとクライアントの両方で利用可能
    staticFolder: '/static',
  },
}

サーバー専用のランタイム設定はserverRuntimeConfigの下に配置してください。

クライアントとサーバーサイドコードの両方からアクセス可能なものはpublicRuntimeConfigの下に配置します。

publicRuntimeConfigに依存するページでは、必ずgetInitialPropsまたはgetServerSidePropsを使用するか、カスタムAppgetInitialPropsを実装して自動静的最適化を無効にする必要があります。サーバーサイドレンダリングされていないページ(またはページ内のコンポーネント)にはランタイム設定は利用できません。

アプリ内でランタイム設定にアクセスするには、以下のように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="ロゴ"
        layout="fill"
      />
    </div>
  )
}

export default MyImage