Environment variables
Background
Attach text strings and JSON values as environment variables 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.tomlname = "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.tsexport interface Env { API_HOST: string;
}
export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise<Response> { console.log(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.tomlname = "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:
- Log in to Cloudflare dashboard and select your account.
- Select Workers & Pages.
- In Overview, select your Worker > Settings.
- Under Environment Variables, select Add variable.
- Input a Variable name and its value, which will be made available to your Worker.
- (Optional) To add multiple environment variables, select Add variable.
- Select Save to implement your changes.
Compare secrets and environment variables
Secrets are environment variables. The difference is secret values are not visible within Wrangler or dashboard interfaces 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.