Skip to content

Instantly share code, notes, and snippets.

@flybayer
Created September 15, 2020 23:10
Show Gist options
  • Save flybayer/af53e974cf295be8b93aae487f0b5b16 to your computer and use it in GitHub Desktop.
Save flybayer/af53e974cf295be8b93aae487f0b5b16 to your computer and use it in GitHub Desktop.
zod env validation
// config/env.ts
import assert from "utils/assert"
import * as z from "zod"
assert(typeof window === "undefined",
"The config/env.ts file cannot be used in the browser")
const isProduction = process.env.NODE_ENV === "production"
const isDevelopment = process.env.NODE_ENV === "development"
const isTest = process.env.NODE_ENV === "test"
// -------------------
// Base env schema
// -------------------
const baseSchema = z
.object({
production: z.boolean(),
development: z.boolean(),
test: z.boolean(),
APP_ORIGIN: z.string(),
})
.nonstrict()
// ----------------------
// Production env schema
// ----------------------
let productionEnvSchema = z.object({
VERCEL_URL: z.string(),
SENDGRID_API_KEY: z.string(),
})
let envSchema
if (isProduction) {
envSchema = baseSchema.merge(productionEnvSchema)
} else {
envSchema = baseSchema.merge(productionEnvSchema.partial())
}
export const env = envSchema.parse({
...process.env,
production: isProduction,
development: isDevelopment,
test: isTest,
APP_ORIGIN: isProduction ? process.env.VERCEL_URL : "http://localhost:3000",
})
// --------------------------------------------
// --------------------------------------------
// --------------------------------------------
// And then use it like this:
import {env} from 'config/env'
if (env.production) {
// stuff
}
env.APP_ORIGIN // Guaranteed to be defined
env.SENDGRID_API_KEY // Guaranteed to be defined in production
// Photo by Alex Beaz on Unsplash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment