skip to Main Content

I would like to import my api key that is saved in .env file like API_KEY = my-key-goes-here, to another js file and save it in variable const key, but when I try I get error 401, can anybody help please?

I expected to import api key from .env file to another js file like this: const key = process.env.API_KEY and it didn’t work, I got an error.

2

Answers


  1. I am not sure if you have this but you need require(‘dotenv’).config() or for ES6 import ‘dotenv/config’ in your file.

    Also have you tried to log the key to the console to make sure it is/isn’t there?

    https://www.npmjs.com/package/dotenv#%EF%B8%8F-usage

    Login or Signup to reply.
  2. REACT_APP_ prefix is required for React to recognize the variable.

    Try to create KEY like below in your environment file (.env),

    REACT_APP_API_KEY=my-key-goes-here
    

    You can access API key in another js file as follows:

    const key = process.env.REACT_APP_API_KEY;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search