简体   繁体   English

如何将 Netlify 的环境变量与 vanilla JavaScript 一起使用?

[英]How do I use Netlify's environment variables with vanilla JavaScript?

I am not using React or Node.我没有使用 React 或 Node。 I want to use an API key for a small project that I don't want to commit to Github.我想将 API 密钥用于我不想提交给 Github 的小项目。 Netlify has built in environment variables . Netlify 内置了环境变量

You set them up in a name key pair in Netlify something like您将它们设置在 Netlify 中的名称密钥对中,例如

SECRET_NAME = secretkey SECRET_NAME = 密钥

When the site builds, Node would replace anywhere I used process.env.SECRET_NAME with secretkey.当站点建立时,Node 会用 secretkey 替换我使用 process.env.SECRET_NAME 的任何地方。

But I am not using Node, or a build process, so of course when I call process.env.ENV_VAR_NAME in my code it fails with the error Uncaught ReferenceError: process is not defined但是我没有使用 Node 或构建过程,所以当我在代码中调用process.env.ENV_VAR_NAME时,它当然会失败并出现错误Uncaught ReferenceError: process is not defined

What is the easiest way to utilize Netlify's environment variables with just vanilla Javascript?仅使用普通 Javascript 来利用 Netlify 的环境变量的最简单方法是什么?

Saw this question which suggests using a Netlify Lambda function , but it still uses Node which I am not using.看到这个建议使用 Netlify Lambda function 的问题,但它仍然使用我没有使用的节点。

After more reading, I know 2 things.经过更多阅读,我知道了两件事。

  1. How to do this.这个怎么做。 This video was helpful . 这个视频很有帮助

  2. You should not do this to try and hide API secrets or keys.您不应该这样做来尝试隐藏 API 机密或密钥。

While it is true the keys won't be in your source code, the problem is once Netlify replaces the API secrets or keys then the client can see them.虽然密钥确实不在您的源代码中,但问题是一旦 Netlify 替换了 API 密钥或密钥,客户端就可以看到它们。 Not good.不好。

Issue: There are no "secrets" client-side.问题:没有“秘密”客户端。

It's a common misconception that you can store secrets in React apps...despite my attempts to make this clear in the docs .一个常见的误解是你可以在 React 应用程序中存储秘密......尽管我试图在文档中明确这一点。

To avoid exposing your API key, you'll need to both store and read the key on a server.为避免暴露您的 API 密钥,您需要在服务器上存储和读取密钥。 This means you'll need to build an app using a server-side framework such as Node.js.这意味着您需要使用诸如 Node.js 之类的服务器端框架来构建应用程序。

Recommended Solution: Netlify Function推荐解决方案:Netlify Function

Netlify Functions are a convenient way to create an endpoint within the same repository/deployment. Netlify 函数是在同一存储库/部署中创建端点的便捷方式。

Alternative Solution: Separate API替代解决方案:单独的 API

Create a separate API that fetches from the third-party API and returns the data.创建一个单独的 API 从第三方 API 提取并返回数据。

Consider securing your API/function with CORS考虑使用 CORS 保护您的 API/功能

You can make it harder (there are ways around this) for other sites to use your API by implementing CORS to only allow fetching from your frontend domain.您可以通过实施 CORS 来使其他站点更难(有解决此问题的方法)使用您的API以仅允许从您的前端域获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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