Code & Coffee

A technology space of the latest trends, tips, and tools for developers.

Published Apr 2021

Per directory environment variables with direnv

With Direnv you can configure environment variables for a given directory.

The environment variables are available into the shell when you enter the directory and unavailable when you leave it.

To create environment variables with direnv, install direnv and activate it in your shell. create a .envrc file in your directory (usually your project root) and fill it with environment variables.

export ENVIRONMENT=production
export DATABASE_URL=postgres://username:password@localhost/db
export S3_BUCKET=mybucket
export S3_REGION=eu-west-2
export JWT_SECRET=zf72jzjsjj43du72h6h6hj23zl6oei23jfzl4oejfl35ndhdbz7efj

Save the file and Direnv will warn you that the .envrc of the current directory has changed with the message :

direnv: error /home/cyprien/.bin/blog/.envrc is blocked. Run `direnv allow` to approve its content

and propose to run direnv allow to re-export the variables in the shell.

After running this command, direnv exports the variable in the shell :

direnv: loading ~/.bin/blog/.envrc                                                                                                                                    

This has been helpfull to me one day when the dotenv file I created for my project was overriden by variables somewhere I couldn't find. I actually found these variables in my .zshrc file where I set them a long time ago. Dotenv fixed this issue.