Programmatically Validate Environment Variables
Ethan Glover
1const envVariables = process.env;
2
3export const envCheck = () => {
4 const defaultVariables = {
5 API_TOKEN: undefined,
6 API_ROOT: 'https://example.com',
7 DATABASE_URL: undefined,
8 };
9
10 const envVariableKeys = Object.keys(envVariables);
11 const defaultVariableKeys = Object.keys(defaultVariables);
12 const missingKeys = [];
13
14 for (const key of defaultVariableKeys) {
15 if (!envVariableKeys.includes(key) || envVariables[key] === undefined) {
16 missingKeys.push(key);
17 }
18 }
19
20 if (missingKeys.length > 0) {
21 throw new Error(
22 `Missing the following env variables, add them to .env: ${missingKeys.join(
23 ', '
24 )}`
25 );
26}