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

241
Visualizações
environment variable undefined defined at top

I have many functions that run uses the same header for api calls so I used a variable and assigned the headers at the top.

However, it's returning undefined for the accesskey and my program is crashing. So I just console logged the access key as well like process.env.ACCESS_KEY, and I'm getting the key. How do I properly assign it to the headers object as well so that it doesn't return undefined?

import axios from 'axios';

const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
  AccessKey: process.env.ACCESS_KEY,
};

const createMan = async (name: string) => {
  const body = JSON.stringify({
    Name: name,
  });
  const resp = await axios.post('https://example.com', body, {
    headers,
  });
  console.log(headers)//AcccessKey is undefined in the headers object
  console.log(process.env.ACCESS_KEY) //shows the access key. How?
  
  return id;
};
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It sounds like process.env.ACCESS_KEY gets added to process.env (which is modifiable) later, in other code not shown, rather than being set by Node.js when the process starts. Three ways to address this:

  1. Make that other code update headers as well.

  2. Make AccessKey an accessor property that retrieves from process.env.ACCESS_KEY every time it's used:

    const headers = {
        Accept: "application/json",
        "Content-Type": "application/json",
        get AccessKey() { return process.env.ACCESS_KEY; })
    };
    
  3. Have a module that both A) Gets the access key (however it is that process.env.ACCESS_KEY is being assigned to) and B)  creates and exports an Axios instance. (More below.)

I would use #1 or #3 if possible, but #2 will work as well if the process.env.ACCESS_KEY value has been populated before AccessKey is used.

More on #3:

Axios has a useful feature where you can create an instance of it preconfigured with modified defaults, so you don't have to specify those defaults on every call. It looks like this (from the documentation):

const instance = axios.create({
    baseURL: "https://some-domain.com/api/",
    timeout: 1000,
    headers: {"X-Custom-Header": "foobar"}
});

So in whatever code you currently have that's setting process.env.ACCESS_KEY, you might do this:

const accessKey = codeThatGetsTheAccessKey();
export const myAxios = axios.create({
    headers: {
       Accept: "application/json",
       "Content-Type": "application/json",
       AccessKey: accessKey,
    }
});

Then, you'd import that Axios instance (rather than using the global instance) and use it

import { myAxios } from "./your-module.js";

const createMan = async (name: string) => {
    const body = JSON.stringify({
        Name: name,
    });
    const resp = await myAxios.post("https://example.com", body);
    return id; // ??? I'm not sure where this came from
};
about 4 years ago · Juan Pablo Isaza Relatório

0

First of all, if you have many calls which use the same header so you can set the header value for once, no need to send headers in each call.

axios.defaults.headers.common['AccessKey'] = process.env.ACCESS_KEY;

if you're not getting value from your environment variables so use https://www.npmjs.com/package/dotenv

App.js

require('dotenv').config() // import at the top
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