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
- Create a
.env
file with the environment variables
- Create an
env.ts
orenv.js
file with the following content
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
In this way, we can manage environment variables easily and safely.