reactjs 如何在 create-react-app 中隐藏 API 密钥?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48699820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:25:18  来源:igfitidea点击:

How do I hide API key in create-react-app?

reactjsapigithubcreate-react-appapi-key

提问by J. Kim

I made a weather app in create-react-app. How do I hide the API key so that I can commit to GitHub?

我在 create-react-app 中做了一个天气应用。如何隐藏 API 密钥以便我可以提交到 GitHub?

Right now the key is in App.js: const API_KEY = "123456";

现在关键是在 App.js 中: const API_KEY = "123456";

回答by richardsonae

Disclaimer

免责声明

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

警告:不要在你的 React 应用程序中存储任何秘密(例如私有 API 密钥)!

环境变量嵌入到构建中,这意味着任何人都可以通过检查您的应用程序文件来查看它们。

The following answer provides correct way to store non-secret data in environment variables. Remember that secret data is accessible through developer tools making it unsafe to store as environment variables.If you want to store some secret data then storing in backend is better option and if client wants to access secret data, it can be accessed by making request to the server. (Refer to @Antonia's answer for more details on storing secret data.)

以下答案提供了在环境变量中存储非机密数据的正确方法。请记住,可以通过开发人员工具访问机密数据,因此将其存储为环境变量是不安全的。如果你想存储一些秘密数据,那么存储在后端是更好的选择,如果客户端想要访问秘密数据,可以通过向服务器发出请求来访问它。(有关存储秘密数据的更多详细信息,请参阅@Antonia 的回答。)

As it turns out, create-react-app has some built-in functionality to help you with that. Thank you George Karametasfor this insight. To access that functionality, you need to:

事实证明,create-react-app 有一些内置功能可以帮助您解决这个问题。感谢George Karametas的洞察力。要访问该功能,您需要:

1. Create a file called .envin the root of your project's directory.

1..env在项目目录的根目录中创建一个文件。

- your_project_folder
  - node_modules
  - public
  - src
  - .env         <-- create it here
  - .gitignore
  - package-lock.json
  - package.json

2. Inside the .envfile, prepend REACT_APP_to your API key name of choice and assign it.

2. 在.env文件中,REACT_APP_在您选择的 API 密钥名称之前添加并分配它。

The create-react-apptool uses REACT_APP_to identify these variables. If you don't start your API key name with it, create-react-appwon't see it.

create-react-app工具用于REACT_APP_识别这些变量。如果您的 API 密钥名称不以它开头,create-react-app则不会看到它。

// .env

REACT_APP_API_KEY=your_api_key  <-- yes
API_KEY=your_api_key            <-- no

// Example (from ???'s response):
REACT_APP_WEATHER_API_KEY=123456

3. Add the .envfile to your .gitignorefile.

3. 将.env文件添加到您的.gitignore文件中。

After you add the line below, save the .gitignorefile and do a git statusto make sure your .envfile does not appear as a new file in git.

添加以下行后,保存.gitignore文件并执行 agit status以确保您的.env文件不会在 git 中显示为新文件。

// .gitignore

# api keys
.env       <-- add this line

# dependencies
/node_modules
...

4. Access the API key via the process.envobject.

4. 通过process.env对象访问 API 密钥。

To check that you can access your API key, go to your App.jsfile and add a console.logat the top below the requirestatements. After saving the file and reloading the page, if the console log does not show your API key, try restarting the react server. Be sure to remove the console log line before committing your code.

要检查您是否可以访问 API 密钥,请转到您的App.js文件并console.logrequire语句下方的顶部添加一个。保存文件并重新加载页面后,如果控制台日志未显示您的 API 密钥,请尝试重新启动反应服务器。在提交代码之前,请务必删除控制台日志行。

// src/App.js

import React, { Component } from 'react';
import './App.css';

console.log(process.env.REACT_APP_WEATHER_API_KEY)

class App extends Component {
...

回答by ???

DISCLAIMER

免责声明

Unless you're making tutorial apps, don't put secrets like api key in client side (ie, React app).

除非您正在制作教程应用程序,否则不要在客户端(即 React 应用程序)中放置诸如 api 密钥之类的秘密。

From create-react-app's documentation,

从 create-react-app 的文档中,

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

警告:不要在你的 React 应用程序中存储任何秘密(例如私有 API 密钥)!

环境变量嵌入到构建中,这意味着任何人都可以通过检查您的应用程序文件来查看它们。

https://create-react-app.dev/docs/adding-custom-environment-variables/

https://create-react-app.dev/docs/adding-custom-environment-variables/

Original Answer

原答案

To elaborate Arup Rakshit's comment,

详细阐述 Arup Rakshit 的评论,

First, you should make .env file outside of your src folder.

首先,您应该在 src 文件夹之外创建 .env 文件。

Then, add

然后加

REACT_APP_WEATHER_API_KEY=123456

Before commit, you should exclude this .env file so find .gitignore file and add .env.

在提交之前,您应该排除这个 .env 文件,以便找到 .gitignore 文件并添加 .env。

Now you're free to go.

现在你可以走了。

Don't forget to add .env in .gitignore file.

不要忘记在 .gitignore 文件中添加 .env 。



Added:

添加:

  1. How to use env variables in your code:
  1. 如何在代码中使用环境变量:
const API_KEY = process.env.REACT_APP_WEATHER_API_KEY;
  1. env variable is undefined. How do I fix it?
  1. env 变量未定义。我如何解决它?

In order to read env variables, you should restart your server.

为了读取环境变量,您应该重新启动服务器。

回答by Antonia Blair

Unfortunately, keeping any key in your React client, even if you are using gitignore and an .envfile, is not secure. As pointed out by @ClaudiuCreanga, React environment variables are embedded in the build and are publicly accessible.

不幸的是,在你的 React 客户端中保留任何密钥,即使你使用的是 gitignore 和一个.env文件,也是不安全的。正如@CludiuCreanga 所指出的,React 环境变量嵌入在构建中并且可以公开访问。

You should really only save API keys or secrets in your backend such as Node / Express. You can have your client send a request to your backend API, which can then make the actual API call with the API key and send the data back to your client.

您真的应该只在后端(例如 Node / Express)中保存 API 密钥或机密。您可以让您的客户端向您的后端 API 发送请求,然后后端 API 可以使用 API 密钥进行实际的 API 调用,并将数据发送回您的客户端。

回答by Tom Foxtrot

from the react documentation:

来自反应文档

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

警告:不要在你的 React 应用程序中存储任何秘密(例如私有 API 密钥)!

环境变量嵌入到构建中,这意味着任何人都可以通过检查您的应用程序文件来查看它们。

回答by Roger Perez

Here's what worked for me:

以下是对我有用的内容:

I created the .envin the root folder. Within that folder I added my key:

.env在根文件夹中创建了。在该文件夹中,我添加了我的密钥:

 REACT_APP_API_KEY_YT = "key"
//I added YT for youtube which is where my api key is from

Then i went to .gitignore|| or create a .gitignore in your root directory if you don't have it. Within .gitignore I added .env

然后我去了.gitignore|| 或者如果你没有它,在你的根目录中创建一个 .gitignore 。在 .gitignore 我添加了 .env

 #api key
 .env

Then I went back to the root of my app js file. For me that was index.js for other it is probably App.js There I created a const API_KEY

然后我回到我的应用程序 js 文件的根目录。对我来说是 index.js 可能是 App.js 在那里我创建了一个 const API_KEY

 const API_KEY =`${process.env.REACT_APP_API_KEY_YT}`

I checked if it was working by console logging it.

我通过控制台记录它来检查它是否正常工作。

 console.log("API", API_KEY)

I was getting undefined. I stopped the server (Control + C) and restarted the server. Afterwards I was able to see the key.

我得到了undefined。我停止了服务器 ( Control + C) 并重新启动了服务器。之后,我能够看到钥匙。

回答by Yuming Cao

If you use the API key for local development purpose, put it under .env.development file and git ignore it. Credentials in .env file will be picked up by the build process, which will expose the data in production.

如果您将 API 密钥用于本地开发目的,请将其放在 .env.development 文件下并 git 忽略它。.env 文件中的凭据将由构建过程获取,这将在生产中公开数据。

Detail see https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used

详情见https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used

回答by aRtoo

Hope it's not late so here's how I did it. on root folder, if you are using react prepend you environment variable with REACT_APP_so goes like this. REACT_APP_API_KEY=<keye here>you don't. React environment will look at the .envchecks if you prepend REACT_APP_then you can use it.

希望现在还不算晚,所以这就是我的做法。在根文件夹上,如果您使用的是 react,则在您的环境变量前面加上REACT_APP_这样的内容。REACT_APP_API_KEY=<keye here>你没有。React 环境将查看.env检查,如果您预先添加REACT_APP_然后您可以使用它。

import React from 'React';
console.log(`${process.env.REACT_APP_API_KEY}`);

that will get you you're variables.

这会让你成为变量。

if you are using node then you need a package https://www.npmjs.com/package/dotenv

如果您使用的是节点,那么您需要一个包https://www.npmjs.com/package/dotenv

thats it. enjoy :)

就是这样。请享用 :)

回答by Vishnu Anilkumar

Create a config_keys.js file with keys in it. Export them as default

创建一个包含密钥的 config_keys.js 文件。将它们导出为默认值

const API_K = "123456788345345235"
export default API_K

Then import them in your app.js or target .js file

然后将它们导入您的 app.js 或目标 .js 文件中

IMPORT API_K from './config_keys/js'
const API_KEY = API_K

and then add config_keys.js to .gitignore

然后将 config_keys.js 添加到 .gitignore