Search code examples
bashherokucookiesenvironment-variablessinatra

Setting environment variables for a Sinatra app on Heroku


I have a Heroku-hosted Sinatra app for which I need to enable Rack::Protection::AuthenticityToken. To this end, I need to set up an environment variable to enable session cookies:

use Rack::Session::Cookie, secret: ENV['MY_APP_SECRET']

I need the cookies to work both on localhost and on Heroku. Given that it's bad practice to hard-code the variable in one's config.ru like this:

use Rack::Session::Cookie, secret: 123qwerty    

...do I set the variable in my local .bash_profile using this syntax:

export MY_APP_SECRET=123qwerty

...or do I set it on the Heroku CLI with:

heroku config:set MY_APP_SECRET=123qwerty ?

Solution

  • You'll need to set the environment variable for both local development and for Heroku. For local development, you could set it in your .bash_profile, but that would make it available to every process in your shell. Instead you could set it whenever you run your local server like this:

    MY_APP_SECRET=123qwerty shotgun config.ru
    

    A better alternative, IMO, is to use a tool like the dotenv Ruby gem to manage environment variables.

    Either way, you still need to set the variable for the Heroku environment using the heroku config:set command.