React/Next.js recommended way to set constants such as backend API URLs

Viewed 4844

I am looking through next.js documentation and trying to understand what the suggested approach is for setting URLs that change in different environments. Mostly, I want to ensure that I'm pointing backend URLs correctly in development versus production.

I suppose you can create a constants configuration file, but is there a supported, best practice for this?

2 Answers

Open next.config.js and add publicRuntimeConfig config with your constants:

module.exports = {
  publicRuntimeConfig: {
// Will be available on both server and client
yourKey: 'your-value'
},
}

you can call it from another .js file like this

import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()
console.log(publicRuntimeConfig.yourKey)

or even call it from view like this

${publicRuntimeConfig.yourKey}

You can configure your next app using next-runtime-dotenv, it allows you to specify serverOnly / clientOnly values using next's runtime config.

Then in some component

import getConfig from 'next/config'

const {
  publicRuntimeConfig: {MY_API_URL},  // Available both client and server side
  serverRuntimeConfig: {GITHUB_TOKEN} // Only available server side
} = getConfig()

function HomePage() {
  // Will display the variable on the server’s console
  // Will display undefined into the browser’s console
  console.log(GITHUB_TOKEN)

  return (
    <div>
      My API URL is {MY_API_URL}
    </div>
  )
}

export default HomePage

If you don't need this separation, you can use dotenv lib to load your .env file, and configure Next's env property with it.

// next.config.js

require('dotenv').config()
module.exports = {
  env: {
    // Reference a variable that was defined in the .env file and make it available at Build Time
    TEST_VAR: process.env.TEST_VAR,
  },
}

Check this with-dotenv example.

Related