Package Exports
- validate-env-vars
Readme
validate-env-vars
A lightweight utility to check the presence and validity of environment variables, as specified by a Zod schema
Installation
Using npm:
npm install validate-env-vars --save-dev
Usage Examples
Create an executable JS file to check an .env file against a Zod schema:
#!/usr/bin/env node
import { z } from 'zod';
import validateEnvVars from 'validate-env-vars';
const envSchema = z.object({
PORT: z.string(),
NODE_ENV: z.string(),
API_URL: z.string(),
});
validateEnvVars(envSchema);
Programmatically check an .env.production file against a Zod schema:
import { z } from 'zod';
import validateEnvVars from 'validate-env-vars';
const envSchema = z.object({
PORT: z.string(),
NODE_ENV: z.string(),
GITHUB_USERNAME: z.string(),
});
const prefilight() => {
try {
validateEnvVars(envSchema, '.env.production');
// ... other code
}
catch (error) {
console.error(error);
// ... other code
}
}
Check env vars before Vite startup and build:
- Define a Zod schema in a .ts file at the root of your project
import { z } from 'zod';
// define the schema for the environment variables
const envSchema = z.object({
PATH_PREFIX: z.string(),
NODE_ENV: z.enum(['development', 'production', 'test']),
API_URL: z.string().url(),
});
// make the type of the environment variables available globally
declare global {
type Env = z.infer<typeof envSchema>;
}
export default envSchema;
- Import
validateEnvVars
and your schema and add a plugin to your Vite config to callvalidateEnvVars
onbuildStart
import { defineConfig } from 'vitest/config';
import envConfigSchema from './env.config';
import validateEnvVars from 'validate-env-vars';
export default defineConfig({
plugins: [
{
name: 'validate-env-vars',
buildStart: () => validateEnvVars(envConfigSchema),
},
// other plugins...
],
// other options...
- Enable typehints and intellisense for the environment variables in your
vite-env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv extends globalThis.Env {}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
- Add your schema configuration file to your tsconfig's
include