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:
- Env is missing.
- Env type is incorrect.
- 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
To validate env variables using zod, install it first:
npm install zod
Then, create a new file env.ts
.
touch env.ts
Open the file and follow these steps:
- Create a variable named
envSchema
that defines the schema and validation rules of env variables using zod. - Create a variable named
env
by parsingprocess.env
withenvSchema
. - 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)
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
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"
// }
// ]
Top comments (0)