简体   繁体   中英

Why does Create React App .env for api keys doesn't work when uploaded to AWS Amplify

I added a dotenv file for an api key in my react app, i followed this tutorial: https://www.pluralsight.com/guides/hiding-secret-keys-in-create-react-app as well as this: https://create-react-app.dev/docs/adding-custom-environment-variables/ I prefixed it as REACT_APP_API_KEY. The app works locally but not when uploaded to AWS.

This the on load fetch:

useEffect(() => {
    const fetchData = async () => {
      try {
        const url = `https://api.themoviedb.org/3/search/movie/?api_key=${process.env.REACT_APP_API_KEY}&language=en-US&query=all`;
        const response = await fetch(url);
        const data = await response.json();
        setMovieList(data.results);
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);

This the search submit button handler:

const handleSearch = useCallback(async () => {
    try {
      const url = `https://api.themoviedb.org/3/search/movie/?api_key=${process.env.REACT_APP_API_KEY}&language=en-US&query=${query}&page=1&include_adult=false`;
      const response = await fetch(url);
      const jsondata = await response.json();
      await setMovies(jsondata.results);
    } catch (err) {
      console.log(err);
    }
  }, [query]);

Here's the local working app: 在此处输入图片说明

Here's the App uploaded in AWS在此处输入图片说明

Typically, whenever you deploy a React app created with Create React App (CRA), you run yarn build and then upload the build directory to some hosting solution. There is no actual process binary that you run (from React's perspective) after that.

During development, CRA's toolchain (Webpack dev server) is a running process and handles the actual serving and building of content which means it has access to the variables from .env . Once you have run yarn build , CRA is hands off and all the execution is handled by some other server that CRA is oblivious to. Any variables that did exist are hard-injected into the built app at build time Referencing Environment Variables in the HTML .

If you need these variables to change based on a deployment, you should have another .env file that gets used in your build tools or make them regular environment variables available in your build script. Just about every continuous deployment (CI) tool has this capability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM