Type-safe environment variables with zod

Short and sweet. I have certainly mistyped my fair share of environment variables before. Also, if you ever want to rename, what a nightmare. If we use zod we can easily solve this problem.

It's quite simple, define your environment file object with zod:

let schema = z.object({
  NEXT_PUBLIC_DOMAIN: z.string().nonempty(),
  MY_SECRET: z.string().nonempty(),
})

Then use zod's parse function and export:

export const env = schema.parse(process.env)

Now, whenever you use env you will have type-safe access to your exposed environment variables

Stay up to date

Get notified when I publish something new, and unsubscribe at any time.