Use Environment Variables in React.js

Managed Runtime environment variables allow you to add variables to the application process running in an environment, without having to make code changes. Environment variables are stored securely, making them ideal for use cases such as:

  • Calling third-party resources that are protected by API keys
  • Conditionally changing React.js rendering

For more details, see Environment Variables.

In this tutorial, we'll use environment variables to alter React.js rendering without changing code. You access environment variables through process.env, which is only available in Node.js and not in browsers. PWA Kit rendering is isomorphic, in that it renders on both the client and the server. So to make environment variables available in React.js, you can add them to your PWA Kit configuration files as shown in this tutorial.

In this example, we'll use an environment variable to enable a feature on your site. For instance, for a limited time, you can test a new feature such as express checkout. You can then monitor shopper engagement with the feature to understand its impact.

Before running the commands in this tutorial, replace any placeholders with actual values. Placeholders are formatted like this: $PLACEHOLDER.

To complete this tutorial, first:

  • Get access to Managed Runtime and Runtime Admin. See Managed Runtime Administration.
  • Have an API key to use the Managed Runtime API. To find your API key, log in to the Runtime Admin tool and go to the Account Settings page.
  • Have a developer or admin role on the project for which you’re setting environment variables. If you don't have access, ask someone in a Managed Runtime admin role to help you with that.

In your project, create your chosen content or feature. For example, create a hero banner on your homepage.

  1. To set the environment variable in the current session, open a terminal and run this command:

    • Windows: set ENABLE_FEATURE='true'
    • macOS: export ENABLE_FEATURE=‘true’
  2. Check if the environment variable is set correctly by running:

    • Windows: echo %$ENABLE_FEATURE%
    • macOS: echo $ENABLE_FEATURE

    The command returns this output: true

  3. Add this JavaScript code to the configuration file in your project — config/default.js:

  1. Add this JavaScript code to the home page in your project — app/pages/home/index.jsx:

Start the development server using npm start then navigate to the homepage locally to see your feature rendered.

We recommend testing these steps in a non-production environment before deploying your changes to production.

  1. Use cURL to call the projects_target_env_var_partial_update API endpoint and set a feature flag as an environment variable. This deploys your bundle. Wait for the environment to redeploy before using the environment variable in your code.
  1. Deploy your bundle from your local machine to your chosen environment.