Suzanne
CDCloudflare Developers
•Created by Suzanne on 10/13/2024 in #workers-help
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;
};
2 replies