Skip to content

Instantly share code, notes, and snippets.

@t18n
Created October 29, 2024 12:27
Show Gist options
  • Save t18n/7e4d90166b1d5ffbc04bb21b10e28058 to your computer and use it in GitHub Desktop.
Save t18n/7e4d90166b1d5ffbc04bb21b10e28058 to your computer and use it in GitHub Desktop.
Simple environment variable validation with Zod
import 'dotenv/config';
import { z } from 'zod';
/*
* By default, the zod library will throw an error if the environment variable is missing.
* All environment variables are string by default.
* */
function zodEnvCheck(value: string) {
return z.string({ message: `Environment variable missing: ${value}` }).parse(process.env[value]);
}
export const CONFIG = {
LOG_LEVEL: zodEnvCheck('LOG_LEVEL'),
ENVIRONMENT: zodEnvCheck('ENVIRONMENT'),
};
@t18n
Copy link
Author

t18n commented Oct 29, 2024

If an environment variable is missing, Zod will throw an error in this format

[email protected]/node_modules/zod/lib/types.js:55
[0]                 const error = new ZodError_1.ZodError(ctx.common.issues);
[0]                               ^
[0]
[0] ZodError: [
[0]   {
[0]     "code": "invalid_type",
[0]     "expected": "string",
[0]     "received": "undefined",
[0]     "path": [],
[0]     "message": "Environment variable missing: LOG_LEVEL"
[0]   }
[0] ]

so you know exactly which one is missing :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment