I saw many articles setting environment variables in Cloudflare workers. but I am not able to read or retrieve it in node.js Code:
async function handleRequest(request) {
  if ('OKOK' == process.env.API_KEY) {
    return new Response('found', {
      headers: { 'content-type': 'text/plain' },
    })
  }
}

wrangler.toml
name = "hello"
type = "javascript"
# account_id = ""
workers_dev = true
[env.production]
name = "API_KEY"
                Cloudflare Workers does not use Node.js. In Workers, environment variables become simple globals. So, to access your environment variable, you would just write API_KEY, not process.env.API_KEY.
(Note: Workers is currently transitioning to a new syntax based on ES modules. In that syntax, environment variables work differently; an env object is passed to the event handler containing all variables. Most people aren't using this new syntax yet, though. You would know if you are using it if your JavaScript uses export default { to define event handlers; on the other hand, if it uses addEventListener("fetch", ...), then it is using the old syntax.)
I recommand you use Miniflare now, pretty easy and strenght forward
"start": "miniflare --watch --debug -e .env"
This is an official Cloudflare lib by the way: https://www.npmjs.com/package/miniflare
Reasone: Miniflare is a simulator for developing and testing Cloudflare Workers.
🎉 Fun: develop workers easily with detailed logging, file watching and pretty error pages supporting source maps.
🔋 Full-featured: supports most Workers features, including KV, Durable Objects, WebSockets, modules and more.
âš¡ Fully-local: test and develop Workers without an internet connection. Reload code on change quickly. It's an alternative to wrangler dev, written in TypeScript, that runs your workers in a sandbox implementing Workers' runtime APIs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With