Runtime Configuration

Generally you’ll want to use build-time environment variables to provide your configuration. The reason for this is that runtime configuration adds rendering / initialization overhead and is incompatible with Automatic Static Optimization.

To add runtime configuration to your app open next.config.js and add the publicRuntimeConfig and serverRuntimeConfig configs:

  1. module.exports = {
  2. serverRuntimeConfig: {
  3. // Will only be available on the server side
  4. mySecret: 'secret',
  5. secondSecret: process.env.SECOND_SECRET, // Pass through env variables
  6. },
  7. publicRuntimeConfig: {
  8. // Will be available on both server and client
  9. staticFolder: '/static',
  10. },
  11. }

Place any server-only runtime config under serverRuntimeConfig.

Anything accessible to both client and server-side code should be under publicRuntimeConfig.

A page that relies on publicRuntimeConfig must use getInitialProps to opt-out of Automatic Static Optimization. Runtime configuration won’t be available to any page (or component in a page) without getInitialProps.

To get access to the runtime configs in your app use next/config, like so:

  1. import getConfig from 'next/config'
  2. // Only holds serverRuntimeConfig and publicRuntimeConfig
  3. const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()
  4. // Will only be available on the server-side
  5. console.log(serverRuntimeConfig.mySecret)
  6. // Will be available on both server-side and client-side
  7. console.log(publicRuntimeConfig.staticFolder)
  8. function MyImage() {
  9. return (
  10. <div>
  11. <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
  12. </div>
  13. )
  14. }
  15. export default MyImage

Related

[

Introduction to next.config.js

Learn more about the configuration file used by Next.js.]($0b4bd5a3a6817758.md)

[

Environment Variables

Access environment variables in your Next.js application at build time.]($cfde255d4d76fde4.md)