Skip to content

env isn't working in Cloudflare worker #162

@amadsen

Description

@amadsen

Environment

I'm not getting environment variables via std-env in a new cloudflare worker.

index.ts

import { env, runtimeInfo } from "std-env";
import { getEnv } from './env';

export default {
	async fetch(request, env_arg, ctx): Promise<Response> {
		console.log({ runtimeInfo, env, env_arg });
		const greeting = env['GREETING'] || getEnv('GREETING') || 'Hello';
		return new Response(`${greeting} World!`);
	},
} satisfies ExportedHandler<Env>;

env.ts

// See https://developers.cloudflare.com/workers/runtime-apis/bindings/#importing-env-as-a-global
import { env } from "cloudflare:workers";


export const getEnv = (name: string): string | undefined => {
  const _env = env as unknown as { [k: string ]: unknown };
  return (_env && name in _env && typeof _env[name] === 'string') ? _env[name] : undefined
};
export default env;

Resulting log message (both on localhost test environment and in worker logs):

{
  runtimeInfo: { name: 'workerd' },
  env: [Object: null prototype] {},
  env_arg: { GREETING: 'Howdy' }
}

Reproduction

> npm create cloudflare@latest -- my-first-worker
> cd my-first-worker
> npm install -s std-env

Add a GREETING environment variable to wrangler.jsonc like

...
"vars": { "GREETING": "Howdy" },
...

Create srcd/index.ts and src/env.ts as documented here.

Update wrangler types:

> wrangler types

Optionally, install @node/types and add it to tsconfig.json's compilerOptions.types array.

Start the wrangler dev server:

> npm run dev

Describe the bug

The env proxy provided by std-env doesn't pick up the environment variables in a Cloudflare worker with a compatibility_date of 2025-07-05. This appears to be because it is trying to use the globalThis object for environment variables (as apparently used to be supported.) It is possible to get environment variables from the env parameter passed to the fetch handler, but that's not really helpful because it isn't compatible with how most other environments expose them. The alternative that I found was to use import { env } from "cloudflare:workers"; (I haven't tested it with a dynamic import yet.)

Additional context

No response

Logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions