'next.js .env.local - process.env keys missing when referenced with a string [duplicate]

I have a lot of values inside a .env.local file.

NEXT_PUBLIC_GA_ID = myvariablevalue

I wrote a function that checks if these are present:

export const getEnvValue = (name: string, required = true) => {
  const value = process.env[name];
  console.log('process.env: ', process.env);
  console.log('process.env.NEXT_PUBLIC_GA_ID: ', process.env['NEXT_PUBLIC_GA_ID']);
  console.log('name: ', name);
  console.log('process.env[name]: ', process.env[name]);

  if (!value && required) {
    throw new Error(`Missing env variable ${name}`);
  }
  return value;
};

I call this function inside a useEffect hook in my component:

useEffect(() => {
    // Setup GA
    const GAVar = getEnvValue('NEXT_PUBLIC_GA_ID');
    if (GAVar) {
      ReactGA.initialize(GAVar);
    }

  }, []);

This console.logs the following:

process.env:  {}
envHelpers.ts?280e:4 process.env.NEXT_PUBLIC_GA_ID:  myvariablevalue
envHelpers.ts?280e:5 name:  NEXT_PUBLIC_GA_ID
envHelpers.ts?280e:6 process.env[name]:  undefined
envHelpers.ts?280e:9 Uncaught Error: Missing env variable NEXT_PUBLIC_GA_ID

How come the variable is there when referenced correctly, but is missing when I pass the object key as a string?



Solution 1:[1]

Usages of process.env.* will be replaced with the values at build time so you're not able to load dynamic env vars. See Loading Environment Variables

Note: In order to keep server-only secrets safe, Next.js replaces process.env.* with the correct values at build time. This means that process.env is not a standard JavaScript object, so you’re not able to use object destructuring. Environment variables must be referenced as e.g. process.env.PUBLISHABLE_KEY, not const { PUBLISHABLE_KEY } = process.env.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FINDarkside