Cloudflare Docs
Workers
Edit this page on GitHub
Set theme to dark (⇧+D)

Environment variables

​​ Background

Environment variables are a type of binding that allow you to attach text strings or JSON values to your Worker. Environment variables are available on the env parameter passed to your Worker’s fetch event handler.

Text strings and JSON values are not encrypted and are useful for storing application configuration.

​​ Add environment variables via Wrangler

Text and JSON values are defined via the [vars] configuration in your wrangler.toml file. In the following example, API_HOST and API_ACCOUNT_ID are text values and SERVICE_X_DATA is a JSON value.

wrangler.toml
name = "my-worker-dev"
[vars]
API_HOST = "example.com"
API_ACCOUNT_ID = "example_user"
SERVICE_X_DATA = { URL = "service-x-api.dev.example", MY_ID = 123 }

Refer to the following example on how to access the API_HOST environment variable in your Worker code:

index.js
export default {
async fetch(request, env, ctx) {
return new Response(`API host: ${env.API_HOST}`);
}
}
index.ts
export interface Env {
API_HOST: string;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return new Response(`API host: ${env.API_HOST}`);
}
}

vars is a non-inheritable key. Non-inheritable keys are configurable at the top-level, but cannot be inherited by environments and must be specified for each environment.

To define environment variables for different environments, refer to the example below:

wrangler.toml
name = "my-worker-dev"
[env.staging.vars]
API_HOST = "staging.example.com"
API_ACCOUNT_ID = "staging_example_user"
SERVICE_X_DATA = { URL = "service-x-api.dev.example", MY_ID = 123 }
[env.production.vars]
API_HOST = "production.example.com"
API_ACCOUNT_ID = "production_example_user"
SERVICE_X_DATA = { URL = "service-x-api.prod.example", MY_ID = 456 }

​​ Add environment variables via the dashboard

To add environment variables via the dashboard:

  1. Log in to Cloudflare dashboard and select your account.
  2. Select Workers & Pages.
  3. In Overview, select your Worker.
  4. Select Settings.
  5. Select Variables.
  6. Under Environment Variables, select Add variable.
  7. Input a Variable name and its Value, which will be made available to your Worker.
  8. (Optional) To add multiple environment variables, select Add variable.
  9. Select Save and deploy to implement your changes.

​​ Compare secrets and environment variables

Secrets are environment variables. The difference is secret values are not visible within Wrangler or Cloudflare dashboard after you define them. This means that sensitive data, including passwords or API tokens, should always be encrypted to prevent data leaks. To your Worker, there is no difference between an environment variable and a secret. The secret’s value is passed through as defined.

  • Learn how to access environment variables in ES modules syntax for an optimized experience.