Search code examples
cloudflare-workers

environment variable use in Cloudflare workers node.js


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' },
    })
  }
}

enter image description here

wrangler.toml

name = "hello"
type = "javascript"

# account_id = ""
workers_dev = true
[env.production]
name = "API_KEY"

Solution

  • 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.)