rsnext/docs/api-reference/next.config.js/runtime-configuration.md
Luis Alvarez D d1fdd2bbf8 Add descriptions to documentation pages (#9901)
* Added descriptions

* Added descriptions to API Reference

* Added descriptions to API Routes

* Added descriptions to basic features

* Added descriptions to the routing docs

* Update exportPathMap.md

Co-authored-by: Joe Haddad <timer150@gmail.com>
2020-01-03 13:16:51 -05:00

2 KiB

description
Add client and server runtime configuration to your Next.js app.

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.

Runtime configuration is not available when using the serverless target.

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

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',
  },
}

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.

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

import getConfig from 'next/config'

// 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>
      <img src={`${publicRuntimeConfig.staticFolder}/logo.png`} alt="logo" />
    </div>
  )
}

export default MyImage