Of course, one thing we always do when creating a JavaScript, Node.js, Bun, etc. project is to handle environment variables. To do this, we create an .env
file and read it with process.env
. However, this can be a bit tedious, validating that all variables exist, that they have a default value, etc.
Requirements
- The first thing is to have a JavaScript, Node.js, Bun, etc. project.
- Install the zod library.
Steps
- Install the zod library
npm install zod # npmyarn add zod # yarnbun add zod # bunpnpm add zod # pnpm
- Create a
.env
file with the environment variables
PORT=3000DB_HOST=
- Create an
env.ts
orenv.js
file with the following content
const z = require("zod");
const envSchema = z.object({ PORT: z.string().default("3000"), DB_HOST: z.string().default("localhost"),});
const env = envSchema.parse(process.env);
module.exports = env;
import { z } from "zod";
const envSchema = z.object({ PORT: z.string().default("3000"), DB_HOST: z.string().default("localhost"),});
// If you need Bun you can change the process.env to Bun.envexport const env = envSchema.parse(process.env);
Thanks to zod, we can validate that environment variables exist and have a default value. If they do not exist, the default value will be used.
We can also say that they are optional with z.string().optional()
.
or that they have a minimum number of characters with z.string().min(3)
.
- Using environment variables
const env = require("./env.js");
console.log(env.PORT); // "3000"console.log(env.DB_HOST); // "localhost"
import { env } from "./env";
console.log(env.PORT); // "3000"console.log(env.DB_HOST); // "localhost"
In this way, we can manage environment variables easily and safely.