Clarify Docs On How To Access Environmental Variables/Secrets in ES Modules format with TypeScript

I want to confirm exactly how to accomplish this, and to understand what exactly my code means. I found two different examples, and neither worked for me until I changed my code slightly. It might help to clarify the docs on these pages. I am not clear on why one example has export interface Env at the top, and the other doesn't. Migrate from Service Workers to ES Modules - https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ Environment variables in ES modules format In ES modules format, environment variables are only available inside the env parameter that is provided at the entrypoint to your Worker application. Environment variables https://developers.cloudflare.com/workers/configuration/environment-variables/ So here is my original code, that had fatal errors: export interface Env { STATIC_PAGE_HANDLER_AUTH_KEY_SECRET: string; } // Access the STATIC_PAGE_HANDLER_AUTH_KEY_SECRET from the environment const authKeySecret = env.STATIC_PAGE_HANDLER_AUTH_KEY_SECRET; // Check requests for a pre-shared secret const hasValidHeader = (request) => { return request.headers.get("X-Custom-Auth-Key") === authKeySecret; }; The error: ✘ [ERROR] service core:user:static-page-handler: Uncaught ReferenceError: env is not defined at null.<anonymous> (index.js:1013:21) ✘ [ERROR] The Workers runtime failed to start. There is likely additional logging output above. Fixed code that runs fine: export interface Env { STATIC_PAGE_HANDLER_AUTH_KEY_SECRET: string; } // Check requests for a pre-shared secret const hasValidHeader = (request) => { // Access the STATIC_PAGE_HANDLER_AUTH_KEY_SECRET from the environment const authKeySecret = env.STATIC_PAGE_HANDLER_AUTH_KEY_SECRET; return request.headers.get("X-Custom-Auth-Key") === authKeySecret; };
Cloudflare Docs
Migrate from Service Workers to ES Modules | Cloudflare Workers docs
Write your Worker code in ES modules syntax for an optimized experience.
Cloudflare Docs
Environment variables | Cloudflare Workers docs
Environment variables are a type of binding that allow you to attach text strings or JSON values to your Worker
1 Reply
Suzanne
SuzanneOP3mo ago
Also, in reading this, I'm wondering what is the purpose of declaring an EnvType like this developer recommends? https://www.giovannibenussi.com/blog/type-safe-environment-variables-in-cloudflare-workers
Type-safe Environment Variables in Cloudflare Workers
How to set types for environment variables in Cloudflare Workers
Want results from more Discord servers?
Add your server