Hiding API keys in JS setup

六眼飞鱼酱① 提交于 2019-12-04 07:33:50

Your best bet is to pull whatever secrets you need from the environment itself, either your environment variables or a secrets store.

The specific implementation will depend on what serverless provider you're using, but for example AWS Lambda lets you configure env vars:

https://docs.aws.amazon.com/lambda/latest/dg/env_variables.html

and you can use the Key Management Service or Parameter Store depending on your preference and requirements:

https://aws.amazon.com/blogs/mt/the-right-way-to-store-secrets-using-parameter-store/


Leaving the above in place in case folks find this via looking at the Serverless tag. Updates below based on the updated question.

So, if I understand the updated question correctly, you want to check in all your code to git except the API key, serve the files only on your local file system and have that local copy be able to access the API key.

The simplest way to do this would be to just have another .js file that defines the variable(s) in question like so:

// config.js
var config = { // this should be const instead if you're using ES6 standards
  apiKey : '123456789XYZ'
}

Then, in index.html have another script tag that calls that before any scripts that need the config, e.g.:

  <script src='./config.js'></script>
  <script src='./main.js'></script>
</body>

In main.js you will then be able to reference the variable config for use, and similarly you can .gitignore 'config.js'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!