How to set conn.secret_key_base in a Phoenix application
This should be specified by default when you create your phoenix application:
https://github.com/phoenixframework/phoenix/blob/2861f0db3df3d81ee6ce79f928ef4e0b439c4dcd/installer/templates/new/config/config.exs#L16
If this config is missing for you, put the following in config/config.exs
:
config :my_app, MyApp.Endpoint,
secret_key_base: "some_secret",
You can use the mix phx.gen.secret
task to generate the value you should use instead of "some_secret".
You set this in config/prod.secret.exs . Note that this shouldn't go into your version control since it is supposed to be secret.
# config/prod.secret.exs
use Mix.Config
config :trope_api, MyApp.Endpoint,
secret_key_base: "SOMEVERYLONGSTRING"
This file is included in config/prod.exs at the bottom
# config/prod.exs
# Finally import the config/prod.secret.exs
# which should be versioned separately.
import_config "prod.secret.exs"
An other approach than to just keep it out of your version control system would be to use environment variables to set it when you start your app.
You can access them in your app like this:
# config/prod.exs
# Just a test vaule for env variables
config :my_app, MyApp,
test_value: System.get_env("TESTCONFIG")
And then set them when starting your server
$ PORT=4001 MIX_ENV=prod TESTCONFIG=testvalue mix phoenix.server
If you want to use this during development as well, you could export the variables to your shell. Or just create a file named .env
(or whatever you like) in your project root and add it to your .gitignore. There you add your environment variables, like so:
export TESTCONFIG="Test Config Value"
export OTHERTESTCONFIG="Other Test Config Value"
When starting a new terminal session, just quickly run source .env
inside your project folder. This is also useful for database credentials. This way they stay out of version control and more importantly are not hardcoded. So when you work in a team, everyone can have their own .env
file with the correct values for their local development setup (db etc.)
When deploying an app into production, you can use .env
files on your server or in your container for an easier but secure start.