Home > Back-end >  Why doesn't my API work when I use info from an env file in my React app?
Why doesn't my API work when I use info from an env file in my React app?

Time:06-25

I have a React app where I access data from an API.

I works perfectly when I hard code all the info in my API function, but when I try to get it from an .env file, it does not work.

Below is the API code:

const [data, setDatas] = useState()
let myHeaders = new Headers();
const getDatas = async () => {
    myHeaders.append("Access-Control-Request-Headers", process.env.REACT_APP_ACCESS_CONTROL);
    myHeaders.append("Authorization", process.env.REACT_APP_BEARER);
    const requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
    };
    try {
        let response = await fetch(
            process.env.REACT_APP_DATAS_API, requestOptions);
        let result = await response.json();
        setDatas(result)
    } catch (err) { console.error(err); }
};
console.log(datas && Object.values(datas))

And below is what the .env file looks like:

REACT_APP_PROJECTS_API=https://this-is-the-api-uri

REACT_APP_ACCESS_CONTROL=this-is-the-access-control

REACT_APP_BEARER=Bearer this-is-the-bearer-token

Why doesn't it work with .env?

CodePudding user response:

You should run npm start again

CodePudding user response:

It'd be helpful if you'd share your configuration, but one option is that you just didn't configure the build pipeline to use .env.

You might need a plugin in case of webpack or additional configuration in case of CRA.

  • Related