0

Having an issue with attaching an API key from my .env file. The key works if its placed in the component. However if I import it from the .env file it doesnt work. Getting a 401 (Unauthorized). Used the Create React App. Tried many different ways to try to make it work (add const, add REACT_APP before the var..).

The .env file...

REACT_APP_OPEN_WEATHER_API_KEY=`123456789123456789`;

The .jsx file...

import React from "react";
import REACT_APP_OPEN_WEATHER_API_KEY from '../.env';

const REACT_APP_API_ADDRESS = REACT_APP_OPEN_WEATHER_API_KEY;

class WeatherInfo extends React.Component {

        constructor() {
            super();
            this.state = {
                items: [],
                isLoaded: false,
            }
        }
        componentDidMount() {
            
            fetch(`https://api.openweathermap.org/data/2.5/forecast?q=Austin,USA&appid=${REACT_APP_API_ADDRESS}&units=imperial`)

enter image description here

2 Answers 2

2

You should not load ENV files like this. There is a special node package which is pretty usefull for that, it does multiple things but the most important from them is that it really hides your .env and just inject the value into your process.env so that those values are not publicly accessible.

https://www.npmjs.com/package/dotenv

Sign up to request clarification or add additional context in comments.

Comments

0

Follow the guidance from here: Node.js Everywhere with Environment Variables!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.