Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Validate your environment variables with Zod
Douglas Moura
Douglas Moura

Posted on • Originally published atdouglasmoura.dev

Validate your environment variables with Zod

Zod is the most famous validation library in the TypeScript ecosystem. With Zod, you create aschema and validate your data according to the schema. Observe the schema below:

import{z}from'zod'constUserSchema=z.object({name:z.string().min(1),age:z.number({coerce:true}).min(18),email:z.string().email(),})
Enter fullscreen modeExit fullscreen mode

This schema can be used to validate an object as follows:

constdata={name:'John Doe',age:18,email:'john@example.com',}// If there is a validation error, it throws an errorconstvalidatedData=UserSchema.parse(data)// If there is a validation error, it returns an error object for you to handle laterconstsafeValidatedData=UserSchema.safeParse(data)// => { success: false; error: ZodError }// => { success: true; data: 'billie' }
Enter fullscreen modeExit fullscreen mode

Zod is capable of performing various types of validations on your data, so be sure to read thedocumentation for more details.

Validating Environment Variables

We can use Zod to validate the values present inprocess.env and even process them before using the environment variables in our application. Usually, I like to create anenvironment.ts file, as in the example below:

import{z}from'zod'constenvironmentSchema=z.object({// Define the possible values for NODE_ENV, always leaving a default value:NODE_ENV:z.enum(['test','development','production']).default('production'),// Environment variables are always defined as strings. Here, convert the string to a number and set a default value:PORT:z.number({coerce:true}).default(3000),})exportconstenv=environmentSchema.parse(process.env)
Enter fullscreen modeExit fullscreen mode

Then, just import the variable and use it throughout my application:

importFastifyfrom'fastify'import{env}from'./environment.js'constapp=Fastify({logger:true})app.listen({port:env.PORT},(err)=>{if(err){app.log.error(err)process.exit(1)}})
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer from Sao Paulo, Brazil. Interested in the intricate aspects of Computer Science.
  • Location
    São Paulo, Brasil
  • Work
    Software Engineer at Trela
  • Joined

More fromDouglas Moura

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp