Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
next.js .env.local - process.env keys missing when referenced with a string

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda