Search code examples
reactjsapienvironment-variablesgatsby

Why doesn't my API work when I use info from an env file in my React app?


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))

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

And below is the contents of my gatsby-config.js file:

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  siteMetadata: {
    title: `Site Name`,
    siteUrl: `https://www.yourdomain.tld`
  },
  plugins: ["gatsby-plugin-image", "gatsby-plugin-react-helmet", "gatsby-plugin-sitemap", {
    resolve: 'gatsby-plugin-manifest',
    options: {
      "icon": "src/images/icon.png"
    }
  }, "gatsby-plugin-mdx", "gatsby-transformer-remark", "gatsby-plugin-sharp", "gatsby-transformer-sharp", {
      resolve: 'gatsby-source-filesystem',
      options: {
        "name": "images",
        "path": "./src/images/"
      },
      __key: "images"
    }, {
      resolve: 'gatsby-source-filesystem',
      options: {
        "name": "pages",
        "path": "./src/pages/"
      },
      __key: "pages"
    }]
};

Why doesn't it work with .env?


Solution

  • If you want your .env variables to be accessible on Gatsby's frontend, you need to prefix those variables with GATSBY_ prefix