Skip to content

direnv

direnv is a shell extension that automatically loads and unloads environment variables when you enter and leave a directory. By combining it with varlock, you can get validated, schema-driven environment variables loaded directly into your shell session.

direnv works by executing a .envrc file in your project directory and capturing any exported variables into the current shell. Varlock’s --format shell flag outputs your resolved env vars as export KEY=VALUE lines that direnv can capture via eval.

.envrc
eval "$(varlock load --format shell)"

When you cd into your project, direnv runs this command and exports all your validated environment variables into the shell.

  1. Install direnv

    Follow the official direnv installation guide for your platform and shell, then hook it into your shell profile. For example, for bash:

    Terminal window
    echo 'eval "$(direnv hook bash)"' >> ~/.bashrc
  2. Create a .envrc file in your project root

    .envrc
    watch_file .env .env.*
    eval "$(varlock load --format shell)"

    The watch_file line tells direnv to re-evaluate whenever any of your .env files change. Note that new files added after the initial load will not be watched until you run direnv reload — but this is rarely a concern since adding new env files is uncommon.

  3. Allow the .envrc file

    Terminal window
    direnv allow

Once set up, when you cd into your project directory, direnv automatically loads your varlock-validated environment:

Terminal window
$ cd my-project
direnv: loading .envrc
direnv: export +API_URL +DB_PASS +PORT

And when you leave the directory, those variables are automatically unloaded.

By default, varlock outputs an empty assignment for undefined optional variables (e.g. OPTIONAL_VAR=""). If you prefer to skip undefined values entirely, use the --compact flag:

.envrc
watch_file .env .env.*
eval "$(varlock load --format shell --compact)"