Search code examples
apigithubherokugitignore

Hide API key / files in Github but not Heroku


I made a small web application that uses an API key.

If I make a separate file for it and add it to .gitignore, push it to GitHub, and do git push heroku master, I don't think the API key gets included in the site.

How do I include a file with an API key on Heroku but not GitHub?

I am using Node JS with Express.


Solution

  • You can't ignore a file and also push it to GitHub, since that would require it to be committed. Git's ignore system only prevents files from being tracked. If you commit it, it won't be ignored anymore.

    Instead of loading it from a file, pull your API key in from the environment, which is Heroku's recommended best practice. Exactly how you retrieve this value depends on the language and possibly framework that you're using, but you can set it using heroku config, e.g.

    heroku config:set API_KEY=some-key
    

    This just sets an environment variable, so if you search for "your-language read environment variable" you should find good documentation on how to read the value. A Python example might look like

    import os
    
    api_key = os.getenv("API_KEY", "optional-default")