skip to Main Content

I created an .env.development file in order to store my api key and other environment variables. I got an issue that when i use my api key defined in .env.development file and retrieved with the help of dotenvx dependencies, the website failed to load resources with a status of 401. However, if i used my api key directly without the need of retrieving from the .env.development file, the website fetched normally without any trouble. My api key works fine so dont need to worry about that.

Note: I also want to mention that the API key I obtained is from TMDB, an external API. Other environment variables that i defined are working fine in the backend with dotenvx package.

.env.development:

API_KEY="my_api_key"

api-config.js:

const apiKey = process.env.API_KEY;
const apiUrl = "my_api_url";
const apiKeyParams = `my_api_params`;

error:

Error from fetching with the external api key

I have tried manually with cli bash:

$ dotenvx run -- npm run start

and i have tried preload with npx:

"scripts": {
  "start": "npx dotenvx run --env-file=.env.development -- react-scripts start"
}

it all injected environment variables successfully but it still doesnt work.

2

Answers


  1. Chosen as BEST ANSWER

    Apologies for the confusion earlier. I've found a solution. In the .env.development file, instead of defining API_KEY, it should be defined as REACT_APP_API_KEY:

    .env.development:

    REACT_APP_API_KEY="my_api_key"
    

  2. It looks like this is because you are trying to using npx dotenvx, but dotenvx is actually published to npm as @dotenvx/dotenvx. To fix this do either of the following:

    1. Use npx @dotenvx/dotenvx
    npx @dotenvx/dotenvx run --env-file=.env.development -- react-scripts start
    
    1. Install @dotenvx/dotenvx via npm and use it inside your package.json starts scripts like so:
    $ npm install @dotenvx/dotenvx --save
    
    // package.json
    "scripts": {
      "start": "./node_modules/.bin/dotenvx run -- --env-file=.env.development -- react-scripts start"
    },
    

    Hope that helps! dotenvx is a bit tricky to install sometimes because there are many different (flexible) ways.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search