Skip to content

Use environment variables via .env files in Phoenix

Published: at 09:30 AM

It’s a common practice to use .env files in projects to include config values such as tokens. As of now (v1.7) when you create a new project in Phoennix framework it reads some values from system environment (such as PHX_SERVER) but you have to either set them manually when running the command like

PHX_SERVER=XYZ mix phx.server

or even if you create .env file you have to first source it

source .env

and then run the command.

It can be easier! so let’s adjust our new project :)

For this we’ll use dotenvy. It’s pretty easy and straight forward.

First add the library to your mix.exs file:

+      {:dotenvy, "~> 1.1"}

And then run

mix deps.get

Then create a .env file in the root folder of your project and put the variables you need there.

API_KEY="ABC"
PLATFORM_SECRET="XYZ"

As you can see I’m putting all the values inside double quotes. This is not always required but helps when you have spaces or special characters in the value.

Next step is to add the .env file to your .gitignore file to avoid accidentally committing secrets into your repository.

.env

Now we need to adjust config/runtime.exs file to read the values from .env file.

import Config
+import Dotenvy
+
+source!([
+  Path.absname(".env"),
+  System.get_env()
+])

Now in the same file (.config/runtime/exs) we can add configs from the .env file into application configs. For example:

config :my_app,
  api_key: env!("API_KEY", :string!),

or if you want to set the config for a specific module:

config :my_app, PlatformModule,
  platform_secret: env!("PLATFORM_SECRET", :string!),

and just like that you can use thos configs anywhere in your app

Application.get_env(:my_app, :api_key)
Application.get_env(:my_app, PlatformModule)[:platform_secret]

In the examples above, I used :string! in both cases, which means it converts the value into string and will raise an error if there is no value. You can see all the possible values here

This is a minimal way to use dot env configuration in your Phoenix application. You can read more about it in Dotenvy’s documentation

Happy Hacking!