Amon Otis Poston
Human Rights Focused Computer Scientist
PGP Fingerprint: 856B 3022 A763 BB23 EA1E DD91 E784 D6D5 7CAB 42A2

How to Use an .env File with Nim.
07/24/25

I've been working in Nim (Nim-lang) and love it. But I ran into the problem of importing an env files.

Why std/os (getEnv()) isn't working.

If you just run something like:

import std/os
echo getEnv("CLIENT_ID")

It wont work as intended. This is because it is loading the environment variables from the current shell environment and isn't looking for a .env file.

You can see all the environment variables currently affecting your program by compiling and running a nim files with the following lines:

import std/envvars

for i in envPairs():
  echo i

If you run export RANDOMTESTTHING="YOOOOOO!" in your shell terminal before running the above code, you will see it RANDOMTESTTHING as an env variable.

So... how do I get the .env file work?

If you want to automatically run your program with .env files install the dotenv nimble package.

nimble install dotenv

Then import dotenv into your project and run load() with optional file locations.

import std/envvars
import dotenv

dotenv.load() # adding library name ("dotenv") for clarity

let CLIENT_ID= getEnv("CLIENT_ID")

Note..

Loading dotenv.load() doesn't remove your shell current session variables. So beware of overloading environment variables.

-Amon