Help: env.RESEND_API_KEY is undefined in my Worker despite being configured as a Secret

I'm encountering a very frustrating issue with my Cloudflare Worker and hoping someone might have some insight. The problem is: My Worker (luisminutri-email-handler) is failing because an environment variable (RESEND_API_KEY), which is configured as a "Secret" in the Worker settings, consistently comes back as undefined at runtime. Key details: Worker Name: luisminutri-email-handler Worker URL: https://luisminutri-email-handler.masterkhro.workers.dev/ Error in Worker console logs: Worker Error: 'env' object or RESEND_API_KEY is undefined. Check Worker settings. Configuration: The RESEND_API_KEY variable is explicitly set as "Secret" under "Settings" -> "Variables and Secrets", showing "Value encrypted". Relevant Code: I access the variable via env.RESEND_API_KEY inside handleRequest(request, env). Steps already taken: Verified the variable configuration as "Secret" and confirmed the name is correct. Recreated the Worker from scratch (deleted and created a new one). Reviewed code syntax, which is plain JavaScript. Verified CORS headers (the 500 is due to the missing key, not CORS). Cloudflare documentation states there's no difference for the Worker between a regular variable and a secret. Has anyone encountered a similar issue where "Secrets" are not correctly injected into the env object despite being properly configured? Are there any known limitations for Free accounts or an additional debugging step I should consider? Any help or suggestions would be greatly appreciated! Thanks in advance!
No description
5 Replies
skuall
skuallOP7mo ago
No one has an idea? ☹️
Cyb3r-Jak3
Cyb3r-Jak37mo ago
Can you share your worker code which used the environment variable?
skuall
skuallOP7mo ago
Sure! https://pastebin.com/3Q1Cz5J There is the code @Cyb3r-Jok3 Thanks in advance
Cyb3r-Jak3
Cyb3r-Jak37mo ago
It looks like you are using the old, deprecated service worker format. They don't use the env so you don't need to use const RESEND_API_KEY = env.RESEND_API_KEY; as just RESEND_API_KEY should exist (https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/#environment-variables-in-service-worker-format). That being said, I highly recommend migrating to ES modules format https://developers.cloudflare.com/workers/reference/migrate-to-module-workers
skuall
skuallOP7mo ago
I'm going to follow your suggestions, modify my code and test if I can make it work. Big Thanks!!! It worked perfectly! at the moment I have applied the fix to the worker and I am already working on migrating to ES module. Thank you again!!!

Did you find this page helpful?