How can I read environment variable dynamically?

Issue: I am trying to access an environment variable dynamically by process.env[key] but I get undefined. The only way to read an env is process.env.SOME_KEY.

Is there a way to pass the env key to process.env to read the env in runtime?

That should work in theory. Can you share the code snippets (both the working and not working ones)?

apiRouter.get("/:key", (req, res) => {
  const { key } = req.matchedParams;
  const value = process.env[key];

  console.log(value); // display undefiend
  ...
});

environment variables are stored locally in .env file

1 Like

Any updates here ^

Hey,

you do not use process to read env variables in Workers.
If you’re using the service worker syntax (you have a addEventListener('fetch')) then the variable will be available in the global scope. So if you had let’s say SENTRY_DSN = "https://sentry.example.com" you can access it in your code with SENTRY_DSN
example:

const sentry = new Toucan({
    dsn: SENTRY_DSN,
    context: event,
    allowedHeaders: ['user-agent'],
    allowedSearchParams: /(.*)/,
  });

If you’re using the module syntax (you have a export default { fetch() }) then you will access it from the second parameter in fetch/scheduled, the env parameter.
example:

export default {
  fetch(req, env, ctx) {
    const sentry = new Toucan({
      dsn: env.SENTRY_DSN,
      context: ctx,
      allowedHeaders: ['user-agent'],
      allowedSearchParams: /(.*)/,
    });
  }
}

More info available here:
https://developers.cloudflare.com/workers/platform/environment-variables
https://developers.cloudflare.com/workers/learning/migrating-to-module-workers

3 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.