React.js: Why does accessing my API key from .env file need REACT_APP prefix when using it? I.e. (process.env.REACT_APP_API_KEY)

huangapple go评论71阅读模式
英文:

React.js: Why does accessing my API key from .env file need REACT_APP prefix when using it? I.e. (process.env.REACT_APP_API_KEY)

问题

根据我的理解,.env 文件应该包含以 REACT_APP 前缀开头的 API 密钥,后跟其名称,要使用该变量,我们必须省略 REACT_APP 前缀,但我注意到在某些情况下有不同的行为。

我在 .env 文件中设置了我的环境变量,例如:REACT_APP_YOUR_KEY_NAME=9999999999999。并且假设可以通过 process.env.YOUR_KEY_NAME 访问它。然而,我注意到在某些情况下(非唯一情况)需要前缀,否则密钥似乎是 undefined。所以只有当我使用 process.env.REACT_APP_YOUR_KEY_NAME 时它才有效。

const FetchData = async () => {
  try {
    const cache = localStorage.getItem('apiData');
    if (cache) {
      return JSON.parse(cache);
    } else {
      const response = await fetch(`${url}?key=${process.env.REACT_APP_API_KEY}`);
      const jsonData = await response.json();
      localStorage.setItem('gameData', JSON.stringify(jsonData));
      return jsonData;
    }
  } catch (error) {
    console.error('发生错误:', error);
    return null;
  }
};

export default FetchData;
英文:

From my understanding the .env file should hold the API key with the REACT_APP prefix followed by its name and to use the variable we must omit the REACT_APP prefix but I am noticing different behavior in some cases.

I set my env variable in my .env file as say: REACT_APP_YOUR_KEY_NAME=9999999999999. And assumed it to be accessed via process.env.YOUR_KEY_NAME. Yet I have noticed in some cases (Not Unique) the prefix is required otherwise the key appears to be undefined. So it only works when I use process.env.REACT_APP_YOUR_KEY_NAME.

const FetchData= async () => {
  try {
    const cache = localStorage.getItem('apiData');
    if (cache) {
      return JSON.parse(cache);
    } else {
      const response = await fetch(`${url}?key=${process.env.REACT_APP_API_KEY}`);
      const jsonData = await response.json();
      localStorage.setItem('gameData', JSON.stringify(jsonData));
      return jsonData;
    }
  } catch (error) {
    console.error('Error occurred:', error);
    return null;
  }
};

export default FetchData;

答案1

得分: 1

我们需要在通过create-react-app创建的应用程序中,对所有自定义环境变量使用REACT_APP_前缀,这是一个要求,如果我们不遵循这个约定,变量将无法访问,就像在VITE中需要使用VITE_..或者在Next.js中需要使用NEXT_PUBLIC...(仅限客户端组件)一样。

另外,请记住所有的值都可以在客户端(浏览器)上访问。您不应该将其用于用户不应该在浏览器中访问的任何数据/凭据以及任何超级机密的API密钥。

为了最大限度地提高安全性,应该在后端使用它,而在后端不需要任何前缀。

要获取更多详细信息,您可以(再次)查看CRA的旧文档:
https://create-react-app.dev/docs/adding-custom-environment-variables

英文:

We need to use REACT_APP_ prefix in env variable names for all custom environment variables in apps created via create-react-app, it's a requirement, if we don't follow the convention, variables will not be accessible, that's it, just like with VITE you will need to put VITE_.. or Nextjs with NEXT_PUBLIC...(only client component)

Also, remember that all the values are accessible on the client-side (browser). You should not use it for any data / credential that your users should not access in the browser and any super secret Api key.

For maximum security it should be used on the backend, and you don't need any prefix on the backend.

For more detail you can (again) check the old documentation on the CRA
https://create-react-app.dev/docs/adding-custom-environment-variables

huangapple
  • 本文由 发表于 2023年7月7日 00:44:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定