michelle
michelle
CDCloudflare Developers
Created by michelle on 5/22/2024 in #workers-help
Env Vars in Worker
Hi, I am having an issue using an environment variable in my Worker code. I have set the environment variable in my Worker's dashboard, and am trying to access it in my Worker JS code, but it won't work. When I console log the env var it either shows up as 'Null' or 'Cannot read properties of undefined'. I have tried to simplify my code to see if I can pinpoint the issue, but am not sure what I'm doing wrong. Is it necessary to use a Wrangler file, or am I implementing it incorrectly? addEventListener('fetch', event => { event.respondWith(handleRequest(event)); }); async function handleRequest(event) { const { env } = event; // Access the environment variable const myEnvVar = env.MAILCHIMP_API_KEY; // Log the environment variable console.log(MY_ENV_VAR: ${myEnvVar}); // Respond with a simple message return new Response(Environment variable MAILCHIMP_API_KEY: ${myEnvVar}, { headers: { 'Content-Type': 'text/plain' }, }); }
11 replies