Access Protected Resources with Environment Variables

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.

Let’s use an environment variable to store an API key used to access a secure external resource. In this tutorial the resource is an imaginary third-party content management system (CMS). We'll add a handler to the Express.js server in ssr.js that makes requests to the CMS and responds with the protected data. We then access the data by calling the handler.

For security reasons, the API key calls the CMS from server-side code, not client-side code.

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.

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

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

    • Windows: set CMS_API_KEY='my-cms-api-key'
    • Most Unix-like operating systems, including macOS: export CMS_API_KEY='my-cms-api-key'
  2. Check if the environment variable is set correctly by running:

    • Windows: echo %CMS_API_KEY%
    • Most Unix-like operating systems, including macOS: echo $CMS_API_KEY

    The command returns this output: my-cms-api-key

  3. Add this JavaScript code for calling the CMS in ssr.js:

  1. Bind the handler to a route in the Express.js server. Next, start the development server using npm start. Finally navigate to the handler locally to verify the CMS data is returned.

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

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

  1. Call the projects_target_env_var_partial_update endpoint to set the environment variable. This deploys your bundle. Wait for the environment to redeploy before using the API key in your code. You can also use Runtime Admin to manage environment variables. See Environment Variables.
  1. Deploy your bundle from your local machine to your chosen environment.