Validate Your Environment Variables Easily with env-vars-validator
Secure your environment variables in Javascript & Typescript
Table of contents
As a developer, you know that working with environment variables is a fundamental aspect of building applications. However, validating them can be a bit tricky. This is where env-vars-validator
comes into play.
env-vars-validator
is a TypeScript library that enables you to validate your environment variables easily. It's available on GitHub and on NPM.
Installation
You can install env-vars-validator
with NPM using the following command:
npm install env-vars-validator
pnpm install env-vars-validator
yarn install env-vars-validator
Usage
Using env-vars-validator
is simple. First, import the validateEnv
function from the library:
const { validateEnv } = require("env-vars-validator");
Then, you can use it to validate your environment variables from an AJV schema:
validateEnv(
{
NODE_ENV: { type: 'string' },
PORT: { type: 'integer' },
},
{
requiredProperties: ['NODE_ENV'],
},
);
This example validates that NODE_ENV
is a string and that PORT
is an integer. Additionally, it requires that NODE_ENV
is present in the environment variables.
API
env-vars-validator
provides several additional functions that can help you work with environment variables:
currentEnv()
: Returns the currentNODE_ENV
without spaces and in lowercase format.isProductionEnv()
: Returnstrue
if the currentNODE_ENV
is equal toproduction
.isPreProductionEnv()
: Returnstrue
if the currentNODE_ENV
is equal toproduction
.isStagingEnv()
: Returnstrue
if the currentNODE_ENV
is equal tostaging
.isDevelopmentEnv()
: Returnstrue
if the currentNODE_ENV
is equal todevelopment
.isTestEnv()
: Returnstrue
if the currentNODE_ENV
is equal totest
.isDeployedEnv()
: Returnstrue
if the currentNODE_ENV
is not equal todevelopment
ortest
.
Conclusion
env-vars-validator
is a simple and powerful library that makes it easy to validate your environment variables. With its intuitive API and TypeScript support, it's a great choice for any project that needs to work with environment variables. Try it out today!