简体   繁体   English

如何在 static Netlify 页面中使用环境变量

[英]How to use environmental variables in a static Netlify page

So i have a static Webpage which uses some API.所以我有一个 static 网页,它使用了一些 API。 There's app.js file that has API key in it stored in an object property.I need to hide it using Netlify dev.有一个app.js文件,其中包含 API 密钥,存储在 object 属性中。我需要使用Netlify dev 隐藏它。 How do I do that?我怎么做? How do I use Netlify dev tools in native js?如何在原生 js 中使用Netlify开发工具? I most probably need node js installed as well but this topic is not entirely clear to me... Could someone make a step by step tutorial for me?我很可能也需要安装 node js,但这个主题对我来说并不完全清楚......有人可以为我制作一步一步的教程吗?

If it's a static site, it won't be able to directly access the hidden netlify env variables.如果是 static 站点,它将无法直接访问隐藏的 netlify 环境变量。 If you are hosting the app.js file along with your static site then it will be easy for someone to browse to it and see the API key you are trying to hide.如果您将app.js文件与您的 static 站点一起托管,那么有人很容易浏览到它并看到您试图隐藏的 API 密钥。

One solution though is to define a Netlify Function that does the API call, and then the JS in your static site can call that function. One solution though is to define a Netlify Function that does the API call, and then the JS in your static site can call that function. Your Netlify Function will be effectively a backend for your app, and can access the ENV variables you set in the Netlify UI, via process.env .您的 Netlify Function 将有效地成为您应用的后端,并且可以通过process.env访问您在 Netlify UI 中设置的 ENV 变量。

See this tutorial for a step-by-step guide.有关分步指南,请参阅本教程


Update re the new gatsby-build information in comments.更新评论中的新 gatsby-build 信息。

You can put variables in a git-ignored .env file, which means they will not end up on git, but will still get pulled in and included in the gatsby production code, which will be visible to the client, so isn't recommended for API access keys.您可以将变量放在 git 忽略的.env文件中,这意味着它们不会最终出现在 git 上,但仍会被拉入并包含在 gatsby 生产代码中,这将对客户端可见,因此不推荐对于 API 访问密钥。 Ideally you should connect via a backend to secure those keys, as in the above original answer.理想情况下,您应该通过后端连接以保护这些密钥,如上面的原始答案所示。

However, instead of using a.env file, if you are using the Netlify Dev CLI then this will automatically pull down any env vars you have set in the online Netlify settings, and allow you to use those in your local environment.但是,如果您使用的是 Netlify Dev CLI,而不是使用 .env 文件,那么这将自动下拉您在在线 Netlify 设置中设置的任何 env var,并允许您在本地环境中使用它们。

From the cli docs :cli 文档

Netlify Dev brings the functionality of your Netlify production environment directly to your local machine. Netlify Dev 将您的 Netlify 生产环境的功能直接带到您的本地机器上。 This includes custom headers/redirects and environment variables .这包括自定义标头/重定向和环境变量

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

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