How do I add API keys and other secure stuff to heroku?

前端 未结 2 1296
清酒与你
清酒与你 2021-02-09 18:41

I read somewhere but cannot seem to find where to add secret keys into Heroku without needing to put it into the source code git repository?

I guess that helps keep it s

相关标签:
2条回答
  • 2021-02-09 18:53

    As Mark has suggested, the best way would be Heroku environment vars. you can read about them here:

    To do so, you need to use Heroku CLI which you need to download and install it based on your operating system. Don't forget to set up Heroku CLI with these 3 steps:

    $ heroku login $ cd ~/myapp $ heroku create (your Heroku app name)

    now it's time to set up config variable. The command is:

    $ heroku config:set <ENVIRONMENT_VARIABLE>=<VALUE>
    

    for example I'm gonna save my API key here as a config var:

    $ heroku config:set DARKSKY_API_KEY=8e11111111162218d22222222229cc22222c6
    

    and now it's time to use it in you server side code. For Nodejs you can access them by:

    process.env.DARKSKY_API_KEY
    

    like so:

      const weatherURL =`https://api.darksky.net/forecast/${process.env.DARKSKY_API_KEY}/${latitude},${longitude}?units=si`;
    

    For other languages like Ruby, Java, ... check this link.

    you can view your config vars by typing:

    $ heroku config
    

    or removing a config var:

    $ heroku config:unset DARKSKY_API_KEY
    

    Also, I was thinking about a .env file for heroku config vars that we can edit them locally and then upload them on heroku. Finally, I come up with this solution.

    To save the cofig vars locally from heroku and be able to change them locally in a file, later down the road when it's needed, we can run:

    $ heroku config | sed 's/: */=/g; /^=/d' >> HEROKU_CONFIG_ENV.env
    

    which HEROKU_CONFIG_ENV.env is just a file name and you can name whatever you like.This script is gonna save HEROKU_CONFIG_ENV.env file on the root of your project.

    After modifying the keys, it's the time to upload them on Heroku and set heroku config vars by running:

    $ heroku config:set $(cat HEROKU_CONFIG_ENV.env | sed '/^$/d; /#[[:print:]]*$/d') 
    

    that's it.

    0 讨论(0)
  • 2021-02-09 19:00

    http://docs.heroku.com/config-vars

    Then add the development keys to an initializer:

    #config/initializers/keys.rb
    
    development:
      SOME_KEY = 'abc123' #not your production key
    
    testing:
      SOME_KEY = 'abc123' #not your production key
    
    #production:
      #blank
    

    Optionally add the initializer to .gitignore. Not required as your production key isn't stored.

    0 讨论(0)
提交回复
热议问题