# 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](/docs/commerce/b2c-commerce/guide/environment-variables.md).

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.

## Prerequisites

To complete this tutorial, first:

- Get access to Managed Runtime and Runtime Admin. See [Managed Runtime Administration](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/managed-runtime-administration.md).
- Have an API key to use the Managed Runtime API. To find your API key, log in to the [Runtime Admin](https://runtime.commercecloud.com/) tool and go to the [Account Settings](https://runtime.commercecloud.com/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.

## On Your Local Machine

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

### Set the Environment Variable Locally

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`:

```jsx
async function fetchCMSData() {
  const key = process.env.CMS_API_KEY;
  if (!key) {
    throw new Error("Environment variable CMS_API_KEY isn't set.");
  }

  return await fetch("https://api.example.com/", {
    headers: {
      Authorization: "Bearer " + key,
    },
  }).json();
}

async function handlerCMS(req, res) {
  try {
    const data = await fetchCMSData();
    return res.json(data);
  } catch (err) {
    return res.status(500).json({ error: err.message });
  }
}
```

4. 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.

## In a Non-production or Production Environment

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](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/references/mrt-admin?meta=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](/docs/commerce/b2c-commerce/guide/environment-variables.md).

Use the [B2C CLI](/docs/commerce/b2c-commerce/guide/b2c-developer-tooling.md):

```bash
export MRT_API_KEY='your-runtime-admin-api-key'
npx @salesforce/b2c-cli mrt env var set 'CMS_API_KEY=your-cms-api-key' \
  --project my-storefront --environment staging
```

Alternatively, use the API:

```bash
curl "https://cloud.mobify.com/api/projects/$PROJECT_ID/target/$ENVIRONMENT_ID/env-var/" \
  --request 'PATCH' \
  --header 'Content-Type: application/json' \
  --header 'Accept: application/json' \
  --header "Authorization: Bearer $MOBIFY_API_KEY" \
  --data   '{"CMS_API_KEY": {"value": "'$YOUR_API_KEY_VALUE'"}}'
```

2. [Deploy your bundle](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/pushing-and-deploying-bundles.md) from your local machine to your chosen environment.

## See Also

- [Environment Variables](/docs/commerce/b2c-commerce/guide/environment-variables.md)
- [Environment Variable Tutorials](/docs/commerce/b2c-commerce/guide/environment-variables.md#tutorials)
- [Troubleshoot Environment Variables](/docs/commerce/b2c-commerce/guide/environment-variables.md#troubleshoot-environment-variables)
- [Debugging Locally](https://developer.salesforce.com/docs/commerce/pwa-kit-managed-runtime/guide/debugging.md#debugging-locally)
