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 or getServerSideProps or your application must have a Custom App with getInitialProps to opt-out of Automatic Static Optimization. Runtime configuration won’t be available to any page (or component in a page) without being server-side rendered.

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

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

Introduction to next.config.jsLearn more about the configuration file used by Next.js.

Environment VariablesAccess environment variables in your Next.js application at build time.