Motoko-env a simple way to access environment variables

:hammer_and_wrench: motoko-env: Environment Variable Parser for Motoko

Hey Motoko devs,

I recently audited a project and noticed they hardcoded their API key directly into the Motoko codebase :sweat_smile:. Obviously, that’s not ideal — Motoko runs in an isolated environment, and there’s no native support for .env files or environment variables like we’re used to in other ecosystems.

To solve this, I built a simple tool: motoko-env – it parses your .env file and generates a Motoko module so you can access those values in your code.

Installation

# Install globally
npm install -g motoko-env

# Or run directly without installing
npx motoko-env generate

Usage

  1. Create a .env file in your project root:
API_URL = https://example.com/api
CANISTER_ID = rrkah-fqaaa-aaaaa-aaaaq-cai
  1. Generate the Motoko module:
npx motoko-env generate
  1. Import and use in your Motoko code:
import Env "../env";

actor {
  public func getApiUrl() : async Text {
    return Env.API_URL;
  };
}

Right now, it outputs everything as text, but I plan to support primitive type recognition(e.g. Nat Int, Bool, Text) in the near future.

I’m currently testing a Motoko implementation of ChaCha20-Poly1305 for handling sensitive values like API keys. The goal is to encrypt these values in JavaScript and have Motoko decrypt them at runtime.

To ensure compatibility, the Motoko implementation must match the expected test vectors defined in RFC 8439 — otherwise, decryption will fail.

You can view the library here motoko-env - npm. Please let me know what you think !

8 Likes

Hi @demali.icp, this is a cool utility, thanks for publishing it!

I still have the plan to have an official import facility in Motoko to obtain this (or similar) functionality…

Something like

import { API_URL : Text; CANISTER_ID : Principal } = "file:secrets.env";

with explicit bindings, or

import (Env : { API_URL : Text; CANISTER_ID : Principal }) = "file:secrets.env";

as a record to be used as you suggest above. One can dream…

5 Likes

Awesome, would love to see it once it’s ready. We should also make sure its included in the motoko docs as a resource for developers.