DEV Community

Ibrahim
Ibrahim

Posted on

Validating Environment Variables in Node.js Using Zod

Environment variables are variables configured outside the source code and used within the application.

Zod is a JavaScript library to validate variables, schemas, and more.

Env variables should be validated to prevent issues sush as:

  1. Env is missing.
  2. Env type is incorrect.
  3. Env value is invalid.

In Node.js, env variables are accessible via the process.env object. All values are stored as strings. For example:

// index.ts
const port = process.env.PORT
const googleClientId = process.env.GOOGLE_CLIENT_ID
const googleSecret = process.env.GOOGLE_SECRET

console.log(port) // 3000
console.log(googleClientId) // 230193-wkork
console.log(googleSecret) // undefined
Enter fullscreen mode Exit fullscreen mode

To validate env variables using zod, install it first:

npm install zod
Enter fullscreen mode Exit fullscreen mode

Then, create a new file env.ts.

touch env.ts
Enter fullscreen mode Exit fullscreen mode

Open the file and follow these steps:

  1. Create a variable named envSchema that defines the schema and validation rules of env variables using zod.
  2. Create a variable named env by parsing process.env with envSchema.
  3. Export the env variable so it can be used in other files.

For example:

// env.ts
import { z } from 'zod'

const envSchema = z.object({
    PORT: z.coerce.number().min(1000),
    GOOGLE_CLIENT_ID: z.string().min(1),
    GOOGLE_SECRET: z.string().min(1)
})

const env = envSchema.parse(process.env)

export default env
// or export default envSchema.parse(process.env)
Enter fullscreen mode Exit fullscreen mode

Now, any part of the application that needs env variables should import them from the env.ts file. For example:

// index.ts
import env from './env'

const port = env.PORT
const googleClientId = env.GOOGLE_CLIENT_ID
const googleSecret = env.GOOGLE_SECRET

console.log(port) // 3000
console.log(googleClientId) // 947320184652-qw9jx71vaz38ykpblm4ud0thrn5c6i2g.apps.googleusercontent.com
console.log(googleSecret) // ZKYMHD-f4Qv7cWpN9sLx1udK30FeVpgtrwXA
Enter fullscreen mode Exit fullscreen mode

If the env variables do not match the defined schema, the program will throw an error. For example:

// ZodError: [
//   {
//     "code": "invalid_type",
//     "expected": "string",
//     "received": "undefined",
//     "path": ["GOOGLE_CLIENT_ID"],
//     "message": "Required"
//   }
// ]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)