# envalid - validate your required environment variables

![Environment Variables (bash)](https://cdn.hashnode.com/res/hashnode/image/upload/v1612732537777/aWZTN2W7w.jpeg)

In the software world - thanks to people who create and maintain open source libraries - there aren't many problems that aren't already solved.

In my quest to manage required environment variables for my Node.js applications, I stumbled upon [envalid](https://www.npmjs.com/package/envalid) - a neat utility to ensure that all necessary variables are set before bootstrapping the application.

#### Manual validation
```js
const cachePath = process.env.CACHE_PATH;
if(typeof cachePath === 'string') {
  // Perform other validations
} else {
  console.error('Missing CACHE_PATH environment variable.');
  process.exit(1);
}

// Repeat for more variables
```

#### With envalid
````js
const {cleanEnv, str} = require('envalid');

// Verify required environment variables
const env = cleanEnv(process.env, {
  CACHE_PATH: str(),
});
````

#### Custom validators

Further, `envalid` supports custom validators to add additional checks.

```js
const { makeValidator } = require('envalid');
const fs = require('fs');
const path = require('path');
const {cleanEnv, str} = require('envalid');

const exists = makeValidator(x => {
  // Correct path according to current platform
  const normalized = path.normalize(x);
  if (fs.existsSync(normalized)) {
    return normalized;
  } else { 
    throw new Error('Directory does not exist.');
  }
}, 'exists');

const env = cleanEnv(process.env, {
  CACHE_PATH: exists(),
});

console.log(env.CACHE_PATH);
```

#### Further

If you require custom error reporting, you can [read more about it](https://www.npmjs.com/package/envalid#error-reporting).
