Created
September 1, 2023 00:46
-
-
Save AdditionAddict/fd03cd2be1f5ef063e3ba6dfe62b0a40 to your computer and use it in GitHub Desktop.
Using zod to validate env
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// env.ts | |
import { z } from 'zod'; | |
import dotenv from 'dotenv'; | |
import path from 'path'; | |
const APP_DIR = 'apps/concrete-api'; | |
const envSchema = z.object({ | |
NODE_ENV: z.string(), | |
SUPABASE_DATABASE_URL: z.string(), | |
SUPABASE_ANON_KEY: z.string(), | |
SUPABASE_API_URL: z.string(), | |
}); | |
// Load the correct environment variables based on the current NODE_ENV value | |
const envPath = path.join( | |
APP_DIR, | |
`./.env.${process.env.NODE_ENV || 'development'}`, | |
); | |
dotenv.config({ path: envPath }); | |
envSchema.parse(process.env); | |
declare global { | |
// eslint-disable-next-line @typescript-eslint/no-namespace | |
namespace NodeJS { | |
// eslint-disable-next-line @typescript-eslint/no-empty-interface | |
interface ProcessEnv extends z.infer<typeof envSchema> {} | |
} | |
} | |
export const env = process.env; | |
console.log(JSON.stringify(envSchema.parse(env), null, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment