1

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.

anshul
  • 2,431
  • 2
  • 10
  • 22

1 Answers1

5

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")
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • Thanks Chris! I came here for exactly this. Is that first line of code using the Heroku CLI? – lifelonglearner Aug 20 '20 at 14:23
  • @lifelonglearner, yes. That's a [Heroku CLI command](https://devcenter.heroku.com/articles/config-vars#using-the-heroku-cli). You can also [set config vars via Heroku's graphical web dashboard](https://devcenter.heroku.com/articles/config-vars#using-the-heroku-dashboard) if you prefer. – ChrisGPT was on strike Aug 20 '20 at 14:41
  • Ok, I did exactly that. I tried to access my environment variables with the code below (Typescript): `9 API_KEY = process.env.API_KEY;` It doesn't seem to recognize `process`, do I need to install some package so that my code can get then environment vars from Heroku? Here's the error I got: ERROR in src/app/services/weatherdata.service.ts:9:13 - error TS2591: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. – lifelonglearner Aug 20 '20 at 14:43
  • @lifelonglearner, please don't try to share code in comments. It's very hard to read, and this isn't the place for new questions. See if [this](https://stackoverflow.com/q/53529521/354577) helps. – ChrisGPT was on strike Aug 20 '20 at 14:45