Env Configuration

Environment variables are a critical part of any production application. They allow you to configure your application based on the environment it's running in (development, testing, production).

To ensure your application has all the required environment variables with the correct types, we recommend using Zod for schema validation and Dotenv for loading variables from a .env file.

Features

  • Type Safety: Automatic TypeScript types for your environment variables.
  • Fail Fast: The application will not start if any required environment variable is missing or invalid.
  • Centralized Access: Access all environment variables through a single, validated env object.
  • Default Values: Easily provide default values for optional environment variables.

Installation Guide

Install the component using the ServerCN CLI:

npx servercn-cli add env-config

Basic Implementation

Create a file named src/configs/env.ts (or similar) and add the following code:

import "dotenv/config";
import { z } from "zod";
 
/**
 * Environment variable schema
 * - All validation happens at startup
 * - Fails fast on misconfiguration
 */
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>;
 
/**
 * Parse and validate environment variables once.
 * This module must be imported before app bootstrap.
 */
const result = envSchema.safeParse(process.env);
 
if (!result.success) {
  console.error("❌ Invalid environment configuration");
  console.error(z.prettifyError(result.error));
  process.exit(1);
}
 
/**
 * Validated, immutable environment object
 */
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.

Example .env file

Make sure to create a .env file in your root directory:

PORT=9000
NODE_ENV=development
DATABASE_URL=mongodb://localhost:27017/mydb
 
CORS_ORIGIN=http://localhost:3000
LOG_LEVEL=info
 
JWT_REFRESH_SECRET=your_refresh_secret
JWT_ACCESS_SECRET=your_access_secret
 
CRYPTO_SECRET=your_crypto_secret
 
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=user@example.com
SMTP_PASS=password
EMAIL_FROM=noreply@example.com
 
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
 
GOOGLE_CLIENT_ID=your_google_id
GOOGLE_CLIENT_SECRET=your_google_secret
GOOGLE_REDIRECT_URI=http://localhost:9000/api/v1/auth/google/callback
 
GITHUB_CLIENT_ID=your_github_id
GITHUB_CLIENT_SECRET=your_github_secret
GITHUB_REDIRECT_URI=http://localhost:9000/api/v1/auth/github/callback

File & Folder Structure

ServerCN

Select a file to view its contents

Installation

npx servercn-cli add env-config