utilcn logoutilcn
Secrets

env-server

Environment variable validation schema using Zod for server configuration

Backend Implementation Suggested

This function is best implemented on your backend server and should not be exposed to the frontend.

Usage

The file automatically validates environment variables on import and exports a serverEnv object with type-safe access to all validated environment variables. If validation fails, the process will exit with detailed error information.

import { serverEnv } from 'env-server';

// Type-safe access to environment variables
const dbUrl = serverEnv.DATABASE_URL;
const port = serverEnv.PORT; // Already converted to number

Installation

pnpm dlx shadcn@latest add https://utilcn.dev/r/secrets/env-server.json
bunx --bun shadcn@latest add https://utilcn.dev/r/secrets/env-server.json
npx shadcn@latest add https://utilcn.dev/r/secrets/env-server.json
yarn shadcn@latest add https://utilcn.dev/r/secrets/env-server.json

Implementation

import { z } from 'zod';

const serverSchema = z.object({
  DATABASE_URL: z.string(),
  PORT: z.coerce.number(),
});

const parsedEnv = serverSchema.safeParse(process.env);
if (!parsedEnv.success) {
  const errors = parsedEnv.error.issues;
  for (const error of errors) {
    console.error(JSON.stringify(error, null, 2));
  }

  process.exit(1);
}

export const serverEnv = parsedEnv.data;