Hiding API keys in JS setup

AnnieP picture AnnieP · Jul 30, 2018 · Viewed 23k times · Source

I'm creating a simple UI with an HTML+CSS+JS setup that uses a third-party API requiring a key and I'd like to keep the key in a file that I can gitignore and access from my Javascript file. I'm not going to be deploying this project, I just want to be able to push it to GitHub without temporarily deleting the variable before every commit.

All responses I've found are related to setups with Node.js, React/Webpack, or other server setups, but I don't have a server or transpiler and don't want to add a bunch of cruft and configurations just for this. Is there a way to do that? I tried storing it in a separate JS file and import/export, but either I couldn't get the syntax right or what I was trying needed a transpiler. Every attempt variation resulted in a syntax error or undefined variable.

Key information:

  1. This is project run entirely locally--as in, just opening index.html in my browser--so I don't think I need to worry about the key being exposed in the client.
  2. My setup pretty much just includes index.html, main.js, and style.css.
  3. I want to push the project to GitHub, so I want to store the api key as a variable in a file separate from main.js that I can add to .gitignore but access in main.js.
  4. I'm keeping this as simple as possible without frameworks, etc. Unless it's super simple and lightweight, I don't want to add libraries just to get this working.

Answer

Paul picture Paul · Jul 30, 2018

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