Last reviewed by Netlify Support - December 2024
With Jamstack sites, using API keys/tokens to make API calls to other services is a frequent pattern. In some cases, you may want to hard code the keys in your html, when invoking those API calls - which on a service like Netlify means these keys are now public. Anyone can open their browser dev tools and view them, and of course this can lead to someone abusing this access.
In some cases, this is fine. For instance, some types of Firebase and FaunaDB keys are intended to be public; they have a permissions model where little harm can be done and no data can be exported. However, this is NOT the case for AWS access tokens! Youâd definitely not want those details to be public or bad things can happen. There are plenty of horror stories of leaked authentication keys, like this one.
There are several things you can do to keep these keys secure at Netlify. One best practice is to never commit any sensitive keys/tokens to your git repository. If you just need a token during build, you can use our Environment Variables build settings to set a value for a $API_TOKEN
environment variable, and reference it during build. Nearly all headless CMSâs use this pattern, for instance - Netlify knows how to access your data from Contentful or Sanity, and pulls it in during build. You may not need the token at browse time, and so it isnât in your HTML output, and youâre safe! We even have a feature to require review on all PRâs from non-Netlify-team-members in case you do list your sensitive environment variables in our UI.
For our Enterprise customers, we also have the Secrets Controller which can more precisely protect your variables and allow specific usages (and protections) of them in specific ways.
Using Functions is another great way to keep those keys secure.
The best way to do that in 2023 is probably via the functionality described in this documentation - which allows you to scope environment variables just to functions at runtime.
But, if you want instead to build something yourself, hereâs a sample project that I call âtoken hiderâ that does just that - makes a request at BROWSE TIME, securely - the value is ONLY known to the function and is NOT in your HTML - and is a great example starting point for anyone wanting to do the same! If you donât hardcode the variable in your function code, youâll want to put the variable in our UI (in the âEnvironment Variablesâ settings under âSite Configurationâ), from where it will be deployed with your function(s).