Skip to content

Instantly share code, notes, and snippets.

@ilomon10
Last active June 15, 2025 12:23
Show Gist options
  • Save ilomon10/856cdae156f14208962326fd14917537 to your computer and use it in GitHub Desktop.
Save ilomon10/856cdae156f14208962326fd14917537 to your computer and use it in GitHub Desktop.
load environment file like nextjs, it can load multiple .env file and can replace in multiple stage
// Deno
import { loadSync } from "jsr:@std/dotenv";
import { log } from "./logging.ts";
const loadMatrix = async (paths: string[]): Promise<Record<string, string>> => {
let result: Record<string, string> = {};
const loadedFrom: string[] = [];
for (const path of paths) {
const res = loadSync({
envPath: path,
});
if (Object.keys(res).length > 0) {
loadedFrom.push(path);
}
result = {
...result,
...res,
};
}
for (const [key, value] of Object.entries(result)) {
Deno.env.set(key, value);
}
log.info(`Loaded env from: ${loadedFrom.join(", ")}`);
return result;
};
await loadMatrix([".env", ".env.local", ".env.production.local"]);
// then import on `main.ts` file
// import "load-env.deno.ts";
// Node Javascript
import { configDotenv } from 'dotenv'
const loadMatrix = async (paths) => {
let result = {}
const loadedFrom = []
for (const path of paths) {
const res = configDotenv({
debug: true,
path: path,
encoding: 'utf-8',
})
if (!res.error) {
loadedFrom.push(path)
}
result = {
...result,
...res,
}
}
console.info(`Loaded env from: ${loadedFrom.join(', ')}`)
return result
}
await loadMatrix(['.env', '.env.local', '.env.production.local'])
// then import on `index.js` file
// import "load-env.js"
// Node Typescript
import { configDotenv } from 'dotenv';
const loadMatrix = async (paths: string[]): Promise<Record<string, string>> => {
let result: Record<string, string> = {};
const loadedFrom: string[] = [];
for (const path of paths) {
const res = configDotenv({
debug: true,
path: path,
encoding: 'utf-8',
});
if (!res.error) {
loadedFrom.push(path);
};
result = {
...result,
...res,
};
}
console.info(`Loaded env from: ${loadedFrom.join(', ')}`);
return result;
}
await loadMatrix(['.env', '.env.local', '.env.production.local'])
// then import on `index.ts` file
// import "load-env.ts"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment