ReferenceError: ENV_VAR_FROM_SECRET is not defined on Workers

From Environment variables · Cloudflare Workers docs, it looks getting environment variables from Workers secret is pretty straight-forward. I did

wrangler init test-env-from-secret -y

I then create a secret from inside test-env-from-secret directory

wrangler secret put ENV_VAR_FROM_SECRET

Now add a line to log secret in wranger generated src/index.ts (without comments)

export interface Env {

export default {
	async fetch(
		request: Request,
		env: Env,
		ctx: ExecutionContext
	): Promise<Response> {
        console.log(ENV_VAR_FROM_SECRET); // <-------- added // 
		return new Response("Hello World!");

After wrangler publish, Worker URL shows below error message, instead of Hello World!

Error 1101 Worker threw exception

wrangler tail shows the cause

ReferenceError: ENV_VAR_FROM_SECRET is not defined

What am I missing? I also appended [vars] (without the comments) to wrangler.toml as in the docs.

In Module Workers, secrets and env vars are exposed on env instead of as globals. This results in faster and safer workers. In your example, if you log env, you should see env.ENV_VAR_FROM_SECRET.

See the docs for more info: FetchEvent · Cloudflare Workers docs

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.