validatenv
TypeScript icon, indicating that this package has built-in type declarations

0.0.17 • Public • Published

validatenv banner

GitHub License NPM bundle minzipped size NPM total downloads Join Discord

Status: Experimental

validatenv is a typesafe library for validating environment variables.

🌟 Motivation

Create a type-safe, straightforward, and lightweight library for validating environment variables using existing validation libraries like Valibot or Zod. Additionally, I didn't trust existing libraries, as reading environment variables is a particularly vulnerable task.

⚖️ Alternatives

📖 Usage

import { validateEnv, validateEnvValue, portValidator, numberMiddleware, devDefault } from 'validatenv';
import { zValidator } from 'validation-adapters/zod';
import * as z from 'zod';

// Load environment variables
import 'dotenv/config';

// Validate multiple environment variables
const env = validateEnv(process.env, {
  // Built-in validator
  port: {
    envKey: 'SERVER_PORT', // Read from SERVER_PORT instead of port
    validator: portValidator,
    defaultValue: devDefault(3000), // Uses default only in development environment
  },
  
  // Zod validator with middleware
  MAX_CONNECTIONS: {
    validator: zValidator(z.number().min(1).max(100)),
    middlewares: [numberMiddleware], // Converts string input to number
    defaultValue: 10
  },

  // Static value
  NODE_ENV: 'development'
});

// Validate single environment variable
const apiKey = validateEnvValue(process.env, {
  envKey: 'API_KEY',
  validator: zValidator(z.string().min(10)),
  description: 'API authentication key', // Shown in validation error messages for better debugging
  example: 'abc123xyz789' // Provides usage example in error messages
});

// Type-safe access
console.log(env.port); // number
console.log(env.MAX_CONNECTIONS); // number
console.log(apiKey); // string

Readme

Keywords

none

Package Sidebar

Install

npm i validatenv

Weekly Downloads

918

Version

0.0.17

License

MIT

Unpacked Size

22.1 kB

Total Files

25

Last publish

Collaborators

  • bennodev