View as Json

Env Configuration

Setup type-safe environment variables with Zod and Dotenv.

Installation Guide

Install the component using the servercn CLI:

npx servercn-cli@latest add env-config

Basic Implementation

src/configs/env.ts
import dotenv from "dotenv-flow";
dotenv.config();
import { z } from "zod";
 
export const envSchema = z.object({
  NODE_ENV: z
    .enum(["development", "test", "production"])
    .default("development"),
 
  PORT: z.string().regex(/^\d+$/, "PORT must be a number").transform(Number),
 
  DATABASE_URL: z.url(),
 
  CORS_ORIGIN: z.string(),
 
  LOG_LEVEL: z
    .enum(["fatal", "error", "warn", "info", "debug", "trace"])
    .default("info"),
 
  JWT_ACCESS_SECRET: z.string().min(32),
  JWT_REFRESH_SECRET: z.string().min(32),
 
  CRYPTO_SECRET: z.string().min(32),
 
  SMTP_HOST: z.string(),
  SMTP_PORT: z
    .string()
    .regex(/^\d+$/, "SMTP_PORT must be a number")
    .transform(Number),
  SMTP_USER: z.string(),
  SMTP_PASS: z.string(),
  EMAIL_FROM: z.email(),
 
  CLOUDINARY_CLOUD_NAME: z.string(),
  CLOUDINARY_API_KEY: z.string(),
  CLOUDINARY_API_SECRET: z.string(),
 
  GOOGLE_CLIENT_ID: z.string(),
  GOOGLE_CLIENT_SECRET: z.string(),
  GOOGLE_REDIRECT_URI: z.url(),
 
  GITHUB_CLIENT_ID: z.string(),
  GITHUB_CLIENT_SECRET: z.string(),
  GITHUB_REDIRECT_URI: z.url()
});
 
export type Env = z.infer<typeof envSchema>;
 
const result = envSchema.safeParse(process.env);
 
if (!result.success) {
  console.error("❌ Invalid environment configuration");
  console.error(z.prettifyError(result.error));
  process.exit(1);
}
 
export const env: Readonly<Env> = Object.freeze(result.data);
 
export default env;

Usage

You can now import the env object anywhere in your application and get full type safety and auto-completion.

import env from "./configs/env";
 
console.log(env.PORT); // Typed as string
console.log(env.NODE_ENV); // Typed as "development" | "test" | "production"

Why Zod?

Using Zod for environment validation provides several benefits:

  1. Validation: It ensures that environment variables like PORT are actually strings/numbers as expected.
  2. Transformation: You can transform strings into other types (e.g., parsing a string to a boolean or number).
  3. Error Reporting: If an environment variable is missing or wrong, Zod provides detailed error messages.

File & Folder Structure

Loading files...

Installation

npx servercn-cli@latest add env-config

Contributed by