How to use environment variables in CloudFlare Worker in local development environment

Viewed 1633

I have a CloudFlare Worker where I have environment variables set in the CF Settings..Environment Variables interface. I also have this wrangler.toml

my wrangler.toml

In my worker's index.js I have code reading the variable REGISTRATION_API_URL. If the code is running in a deployed environment then it injects the value from the CF Settings into REGISTRATION_API_URL just fine.

But if I run wrangler dev or wrangler dev --env local then REGISTRATION_API_URL is undefined.

Originally I expected that the variable would be populated by the CF Settings values, but they aren't. So I tried the two vars setting in the wrangler.toml I show here but no difference. And I have spent a lot of time searching the docs and the greater web.

Are environment variables supported in a local dev environment? Any workarounds that people have come up with? Currently I am looking for undefined and defining the variable with a hard-coded value, but this is not a great answer.

Using wrangler 1.16.0

Thanks.

2 Answers

The docs could be more clear but if your using the newer module syntax, the variables will not be available as global variables.

Environmental variables with module workers

When deploying a Module Worker, any bindings will not be available as global runtime variables. Instead, they are passed to the handler as a parameter – refer to the FetchEvent documentation for further comparisons and examples .

Here's an example.

export default {
  async fetch(request, env, context) {
    return new Response(env.MY_VAR);
  },
};

KV namespaces are also available in the same object.

Maybe a bit late, but: no I don't think you can

But: you can always use self["YOUR_ENV_VARIABLE"] to get the value and then go from there (unfortunately the docs don't mention that)

Here is what I personally do in my Workers Site project to get the Release version (usually inserted via pipeline/action and then inserted via HtmlRewriter into the index.html):

const releaseVersion = self["RELEASE_VERSION"] || 'unknown'
Related