> ## Documentation Index
> Fetch the complete documentation index at: https://checklyhq.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Environment Variables

> Learn how to use environment variables in your Checkly project

export const YoutubeEmbed = ({id, allowFullScreen = true, end, loading = "eager", start, title = "YouTube video"}) => {
  if (!id) {
    console.error("YouTube component requires an id prop");
  }
  const params = new URLSearchParams();
  if (start) params.append("start", start.toString());
  if (end) params.append("end", end.toString());
  const src = `https://www.youtube.com/embed/${id}?${params.toString()}`;
  return <iframe src={src} title={title} loading={loading} className="w-full aspect-video rounded-xl" allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen={allowFullScreen} />;
};

There are two types of environment variables (env vars) in the Checkly CLI context.

* Local environment variables.
* Remote environment variables.

To get a quick overview of when to use which, checkout this video 👇

<YoutubeEmbed id="nEIOBRSbjAk" title="How to use Checkly local and remote environment variables" />

## Local Environment Variables

Local environment variables exist on your local machine, your CI environment, or anywhere you run the Checkly CLI. They
normally are part of your shell session or stored in a `.env` file in your app's Git repo. Here is what you need to
remember:

1. Use local environment variables to replace values in your constructs before `test` and `deploy` invocations.
2. Local environment variables are not interpreted in code dependencies like `.spec.ts` files or setup and teardown scripts.

Use local environment variables to inject or replace values in your `Check`, `AlertChannel` or other constructs at
**build time** when the CLI compiles your constructs for testing and deploying.

Here is an example of setting up an `SmsAlertChannel` where we pass in the actual phone number from a local environment
variable. Note the exclamation mark `!` at the end. This is to tell the Typescript compiler the value will be set.
Alternatively you can use a string template.

```ts Alert-Channel.check.ts theme={null}
import { SmsAlertChannel } from 'checkly/constructs'

export const smsChannel = new SmsAlertChannel('sms-channel-1', {
  phoneNumber: process.env.PHONE_NUMBER!
  // phoneNumber: `${process.env.PHONE_NUMBER}` this also works
})
```

When you execute `test` or `deploy` the variable needs to part of the parent process `env` object. This is typically
done by just prepending the variable to the command.

```
PHONE_NUMBER=0987654321 npx checkly deploy
```

The above command will replace `process.env.PHONE_NUMBER` with the actual `PHONE_NUMBER` you prepended and then create
that SMS channel in your Checkly account.

## Remote Environment Variables

Checkly also stores environment variables in your Checkly account. These can exist at [the
Global, Group or Check level](/platform/variables). Here is what you need to remember:

1. Use remote environment variables to dynamically inject or replace values during runtime of a check.
2. Remote variables can be set and overridden when invoking the `test` command.

You will typically use remote environment variables inside the code dependencies you write, e.g. Playwright tests, setup
and teardown scripts. The point is that the `process.env.SOME_VARIABLE` stays in your code and are only interpreted when
a check executes on the Checkly cloud.

### Using the `-e` flag

Here is an example of a Playwright script using an `ENVIRONMENT_URL` variable to define the page to visit. We also added
a fallback value in case that variable is not defined for some reason.

```ts home.check.ts theme={null}
import { test } from '@playwright/test'

test('Check Home Page', async ({ page }) => {
  const response = await page.goto(process.env.ENVIRONMENT_URL! || 'https://wwww.checklyhq.com')
  await page.screenshot({ path: 'home.jpg' })
})
```

Here is an example of a Checkly [ApiCheck construct](/constructs/api-check) using an `ENVIRONMENT_URL` variable to define the page to visit. Notice the `{{ENVIRONMENT_URL}}` is wrapped in double handlebars and must be written this way for a remote environment variable to be parsed within an ApiCheck construct.

```ts api.check.ts theme={null}
import * as path from 'path'
import { ApiCheck, AssertionBuilder } from 'checkly/constructs'
import { websiteGroup } from './website-group.check'

new ApiCheck('books-api-check-1', {
  name: 'Books API',
  group: websiteGroup,
  degradedResponseTime: 10000,
  maxResponseTime: 20000,
  setupScript: {
    entrypoint: path.join(__dirname, './utils/setup.ts'),
  },
  request: {
    url: '{{ENVIRONMENT_URL}}' || 'https://danube-web.shop/api/books',
    method: 'GET',
    followRedirects: true,
    skipSSL: false,
    assertions: [AssertionBuilder.statusCode().equals(200)],
  },
  runParallel: true,
})
```

You can now test this check and temporarily set the environment variable as follows.

```bash Terminal theme={null}
npx checkly test -e ENVIRONMENT_URL="https://staging.checklyhq.com"
```

* Notice that we pass in the variable using the `-e` flag. This means it will be passed to the cloud environment and made
  available during runtime.
* After deploying this check, the `ENVIRONMENT_URL` needs to be set at the Account, Group or Check level. If not set, the Check
  will use the fallback URL.
* Prepending the variable like `ENVIRONMENT_URL="https://staging.checklyhq.com" npx checkly test` has no effect as local
  environment variables are not replaced in code dependencies.

### Using the `--env-file` flag

If you have a lot of variables, it makes sense to store them in a `.env` file. Make sure to add that to your `.gitignore` file!

```bash Terminal theme={null}
ENVIRONMENT_URL=https://checklyhq.com
USER_NAME=admin
PASSWORD=admin
```

You can reference that file in the `test` as follows:

```bash Terminal theme={null}
npx checkly test --env-file="./.env"
```

You can also pull in the variables from your account and store them in a file using [the `npx checkly env pull` command](/cli/checkly-env#pull).
See the examples below.

### Managing Remote Environment Variables

Manage your remote environment variables with the CLI using the [`checkly env` command](/cli/checkly-env). You can list, add, update, remove
and export your global variables.

List all your stored variables and lock it.

```bash theme={null}
npx checkly env ls
```

Create a new variable.

```bash theme={null}
npx checkly env add MY_PASSWORD 123test
```

Pull in the variables from your account and store them in a file.

```bash theme={null}
npx checkly env pull .env.prod
```

Reference that file in your `test` command.

<Tip>[See the full reference documentation for the `checkly env` command](/cli/checkly-env).</Tip>

## Securing Environment Variables

For storing and securing environment variables, we advise the following:

1. Store local environment variables in your shell or in `.env` files that are not committed to your git repo. Add those
   files to your `.gitignore` file.
2. In a CI context, e.g. GitHub Actions, store sensitive variables as secrets. Almost all CI providers have such a feature.
3. For remote variables, store sensitive data as secrets in Checkly. For more information on how to manage secrets in Checkly see [variables and secrets](/platform/variables).

All variables are stored encrypted at rest and in transfer.
