简体   繁体   中英

How to use environmental variables in a static Netlify page

So i have a static Webpage which uses some 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. How do I do that? How do I use Netlify dev tools in native js? 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?

If it's a static site, it won't be able to directly access the hidden netlify env variables. 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.

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 .

See this tutorial for a step-by-step guide.


Update re the new gatsby-build information in comments.

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. 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.

From the cli docs :

Netlify Dev brings the functionality of your Netlify production environment directly to your local machine. This includes custom headers/redirects and environment variables .

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