-
Notifications
You must be signed in to change notification settings - Fork 32
Description
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 typesOptionally, install @node/types and add it to tsconfig.json's compilerOptions.types array.
Start the wrangler dev server:
> npm run devDescribe 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