コンテンツへスキップ

ランタイム設定

警告

アプリケーションにランタイム設定を追加するには、next.config.jsを開き、publicRuntimeConfigserverRuntimeConfigの設定を追加します。

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