Search code examples
djangosecuritysecret-key

How to hide SECRET_KEY?


I put my SECRET_KEY in secrets.json, and that one in .gitignore; in settings.py I read the key from the file.

Bottom line: my local server is reading the key. But when I want to produce a git push heroku master, an error is thrown, the file was not found. It is understandable! I added it to .gitignore. And accordingly the question: what to do? Why advise to hide SECRET_KEY in a separate file hidden from git, if then we can’t just push our changes to the server?

I see this way out here: I can explicitly register my key in settings.py, push it on the server, hide it in the file again, push it in the github repository.

But how safe is it? Is SECRETS_KEY hidden only for public repositories?


Solution

  • You're handling secrets correctly by not putting those secrets into your repository unencrypted. To fix this issue, what I usually do is to add a second check in settings.py

    if os.path.exists('secrets.json'):
       # read secrets from json file
    else:
        SECRET_KEY = os.environ['DJANGO_SECRET_KEY']
    

    And in heroku, you would set an environment variable with that name with the value that you want using config vars. This way your secrets are available to heroku and to local, but not put in your repository.