Hiding API keys in JS setup

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