Simple utility to validate environment variables
No more console logging to see if correct environment variables are set, with zod we can validate envs at runtime or build-time, set defaults, and enforce strict schemas.
Create an env.ts
file.
import { getEnv, z } from '@kpauletti/ts-env';
export const env = getEnv({
DB_HOST: z.string().default('localhost'),
DB_PORT: z.string().default('1337'),
DB_USER: z.string(),
DB_PASS: z.string(),
APP_ENV: z.enum(['development', 'staging', 'qa', 'production']),
SOME_TOKEN: z.string().optional()
})
Now wherever you need to reference an env variable
import { env } from '../utils/env'
await connect({
host: env.DB_HOST,
port: env.DB_PORT,
auth: {
user: env.DB_USER,
pass: env.DB_PASS
}
})
Provides autocomplete for your environment variables as well.
This is heavily inspired by t3-env.