Skip to content

Instantly share code, notes, and snippets.

@AdditionAddict
Created September 1, 2023 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdditionAddict/fd03cd2be1f5ef063e3ba6dfe62b0a40 to your computer and use it in GitHub Desktop.
Save AdditionAddict/fd03cd2be1f5ef063e3ba6dfe62b0a40 to your computer and use it in GitHub Desktop.
Using zod to validate env
// 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