dev-resources.site
for different kinds of informations.
Validate your environment variables with Zod
Published at
8/16/2024
Categories
typescript
zod
javascript
Author
Douglas Moura
Zod is the most famous validation library in the TypeScript ecosystem. With Zod, you create a schema and validate your data according to the schema. Observe the schema below:
import { z } from 'zod'
const UserSchema = z.object({
name: z.string().min(1),
age: z.number({ coerce: true }).min(18),
email: z.string().email(),
})
This schema can be used to validate an object as follows:
const data = {
name: 'John Doe',
age: 18,
email: '[email protected]',
}
// If there is a validation error, it throws an error
const validatedData = UserSchema.parse(data)
// If there is a validation error, it returns an error object for you to handle later
const safeValidatedData = UserSchema.safeParse(data)
// => { success: false; error: ZodError }
// => { success: true; data: 'billie' }
Zod is capable of performing various types of validations on your data, so be sure to read the documentation for more details.
Validating Environment Variables
We can use Zod to validate the values present in process.env
and even process them before using the environment variables in our application. Usually, I like to create an environment.ts
file, as in the example below:
import { z } from 'zod'
const environmentSchema = 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),
})
export const env = environmentSchema.parse(process.env)
Then, just import the variable and use it throughout my application:
import Fastify from 'fastify'
import { env } from './environment.js'
const app = Fastify({ logger: true })
app.listen({ port: env.PORT }, (err) => {
if (err) {
app.log.error(err)
process.exit(1)
}
})
Articles
12 articles in total
Validate your environment variables with Zod
currently reading
Using TypeScript in Node.js projects
read article
The Powerful Programmer
read article
Generating MD5 hashes on Node.js
read article
Finding the greatest common divisor in TypeScript
read article
Understanding Tail Call Optimization With JavaScript
read article
Desenvolvendo APIs fortemente tipadas de ponta a ponta com tRPC
read article
The minimum you need to know to test your APIs with CURL
read article
Creating native modals with the dialog element
read article
Using fetch with TypeScript
read article
Introduction to GraphQL
read article
What is a first-class citizen in computer science?
read article
Featured ones: