New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@vwinterdev/vite-env-validator

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vwinterdev/vite-env-validator

Vite plugin for validating environment variables with built-in validators

latest
Source
npmnpm
Version
2.0.4
Version published
Maintainers
1
Created
Source

@vwinterdev/vite-env-validator

Vite plugin for validating environment variables with built-in schema validators and customizable rendering.

Installation

npm install @vwinterdev/vite-env-validator
# or
pnpm add @vwinterdev/vite-env-validator
# or
yarn add @vwinterdev/vite-env-validator

Note: If you want to use the zod validator, you also need to install zod:

npm install zod
# or
pnpm add zod
# or
yarn add zod

Features

  • ✅ Built-in schema validators (no additional dependencies required)
  • ✅ Support for multiple validators: built-in Schema (default) and zod
  • ✅ Customizable rendering: table view, console logs, or custom render function
  • ✅ Automatic type conversion from strings (numbers, booleans, etc.)
  • ✅ Beautiful error messages with detailed validation feedback

Quick Start

// vite.config.ts
import { defineConfig } from 'vite'
import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

export default defineConfig({
  plugins: [
    ValidateEnv({
      schema: {
        VITE_API_URL: Schema.string({ format: 'url' }),
        VITE_PORT: Schema.number(),
        VITE_DEBUG: Schema.boolean(),
        VITE_API_KEY: Schema.string(),
      },
    }),
  ],
})

Basic Usage

The package exports a Schema object that provides all validation methods. No additional imports needed!

// vite.config.ts
import { defineConfig } from 'vite'
import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

export default defineConfig({
  plugins: [
    ValidateEnv({
      schema: {
        VITE_API_URL: Schema.string({ format: 'url' }),
        VITE_PORT: Schema.number(),
        VITE_DEBUG: Schema.boolean(),
        VITE_API_KEY: Schema.string(),
      },
    }),
  ],
})

Using Zod Validator (Alternative)

// vite.config.ts
import { defineConfig } from 'vite'
import ValidateEnv from '@vwinterdev/vite-env-validator'
import { z } from 'zod'

export default defineConfig({
  plugins: [
    ValidateEnv({
      validator: 'zod',
      schema: {
        VITE_API_URL: z.string().url(),
        VITE_PORT: z.coerce.number(),
        VITE_DEBUG: z.coerce.boolean(),
        VITE_API_KEY: z.string().min(10),
      },
    }),
  ],
})

Built-in Schema Examples

String Validators

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    // Basic string
    VITE_API_KEY: Schema.string(),
    
    // URL format
    VITE_API_URL: Schema.string({ format: 'url' }),
    
    // Email format
    VITE_EMAIL: Schema.string({ format: 'email' }),
    
    // UUID format
    VITE_UUID: Schema.string({ format: 'uuid' }),
    
    // Host format (domain or IP)
    VITE_HOST: Schema.string({ format: 'host' }),
    
    // Optional string
    VITE_OPTIONAL_KEY: Schema.string.optional(),
  },
})

Number Validators

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    // Basic number (automatically converts strings to numbers)
    VITE_PORT: Schema.number(),
    
    // Number with validation
    VITE_TIMEOUT: Schema.number(),
    
    // Optional number
    VITE_OPTIONAL_PORT: Schema.number.optional(),
  },
})

Boolean Validators

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    // Basic boolean (converts 'true'/'1' → true, 'false'/'0' → false)
    VITE_DEBUG: Schema.boolean(),
    
    // Boolean flag
    VITE_CACHE: Schema.boolean(),
    
    // Optional boolean
    VITE_OPTIONAL_FLAG: Schema.boolean.optional(),
  },
})

Enum Validators

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    // Environment enum
    VITE_ENV: Schema.enum(['development', 'production', 'staging'] as const),
    
    // Log level enum
    VITE_LOG_LEVEL: Schema.enum(['debug', 'info', 'warn', 'error'] as const),
    
    // API version enum
    VITE_API_VERSION: Schema.enum(['v1', 'v2', 'v3'] as const),
  },
})

Complete Real-World Example

// vite.config.ts
import { defineConfig } from 'vite'
import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

export default defineConfig({
  plugins: [
    ValidateEnv({
      schema: {
        // API Configuration
        VITE_API_URL: Schema.string({ format: 'url' }),
        VITE_API_KEY: Schema.string(),
        VITE_API_TIMEOUT: Schema.number(),
        
        // Server Configuration
        VITE_PORT: Schema.number(),
        VITE_HOST: Schema.string({ format: 'host' }),
        
        // Feature Flags
        VITE_DEBUG: Schema.boolean(),
        VITE_ENABLE_CACHE: Schema.boolean(),
        VITE_ENABLE_ANALYTICS: Schema.boolean(),
        
        // Environment
        VITE_ENV: Schema.enum(['development', 'production', 'staging'] as const),
        
        // Optional Configuration
        VITE_CDN_URL: Schema.string({ format: 'url' }).optional(),
        VITE_MAX_RETRIES: Schema.number().optional(),
      },
    }),
  ],
})
# .env
VITE_API_URL=https://api.example.com
VITE_API_KEY=secret-key-12345
VITE_API_TIMEOUT=5000
VITE_PORT=3000
VITE_HOST=localhost
VITE_DEBUG=true
VITE_ENABLE_CACHE=true
VITE_ENABLE_ANALYTICS=false
VITE_ENV=development
VITE_CDN_URL=https://cdn.example.com
VITE_MAX_RETRIES=3

API Reference

ValidateEnv(options)

Main plugin function that validates environment variables.

Options

interface ValidatorOptions {
  validator?: 'default' | 'zod'  // Default: 'default'
  schema: Schema                  // Required: validation schema
  render?: 'table' | 'console' | ((logs: Log[]) => void)  // Default: 'table'
}

Parameters

  • validator (optional): Type of validator to use

    • 'default': Uses built-in Schema from the package (recommended, no dependencies)
    • 'zod': Uses Zod library (requires zod to be installed)
  • schema (required): Validation schema object

    • For 'default' validator: Use Schema exported from the package
    • For 'zod' validator: Use Zod schemas
  • render (optional): How to display validation results

    • 'table': Beautiful table view (default)
    • 'console': Console logs with colors
    • Custom function: (logs: Log[]) => void

Built-in Schema API

The Schema object provides the following methods:

Schema.string(options?)

Validates a string value.

Schema.string()                    // Any string
Schema.string({ format: 'url' })   // URL format
Schema.string({ format: 'email' }) // Email format
Schema.string({ format: 'uuid' })  // UUID format
Schema.string({ format: 'host' })  // Host format
Schema.string.optional()           // Optional string

Schema.number()

Validates and converts a number value (automatically converts strings to numbers).

Schema.number()         // Any number
Schema.number.optional() // Optional number

Schema.boolean()

Validates and converts a boolean value (converts 'true'/'1' → true, 'false'/'0' → false).

Schema.boolean()         // Any boolean
Schema.boolean.optional() // Optional boolean

Schema.enum(values)

Validates that the value is one of the provided enum values.

Schema.enum(['value1', 'value2', 'value3'] as const)

Rendering Options

Table Render (Default)

Displays a beautiful table with validation results:

Key              Value                    Message
─────────────────────────────────────────────────────
VITE_API_URL     https://api.example.com ✓ success
VITE_PORT        3000                    ✓ success
VITE_DEBUG       true                     ✓ success
ValidateEnv({
  schema: { /* ... */ },
  render: 'table', // or omit this (default)
})

Console Render

Shows colored console logs:

ValidateEnv({
  schema: { /* ... */ },
  render: 'console',
})

Output:

✓ VITE_API_URL: https://api.example.com -> success
✓ VITE_PORT: 3000 -> success
✓ VITE_DEBUG: true -> success

Custom Render Function

ValidateEnv({
  schema: { /* ... */ },
  render: (logs) => {
    logs.forEach((log) => {
      if (log.isError) {
        console.error(`❌ ${log.key}: ${log.message}`)
      } else {
        console.log(`✅ ${log.key}: ${log.value}`)
      }
    })
  },
})

More Examples

Example 1: API Configuration

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    VITE_API_BASE_URL: Schema.string({ format: 'url' }),
    VITE_API_VERSION: Schema.enum(['v1', 'v2'] as const),
    VITE_API_KEY: Schema.string(),
    VITE_API_TIMEOUT: Schema.number(),
    VITE_API_RETRY_COUNT: Schema.number().optional(),
  },
})

Example 2: Database Configuration

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    VITE_DB_HOST: Schema.string({ format: 'host' }),
    VITE_DB_PORT: Schema.number(),
    VITE_DB_NAME: Schema.string(),
    VITE_DB_USER: Schema.string(),
    VITE_DB_PASSWORD: Schema.string(),
    VITE_DB_SSL: Schema.boolean(),
  },
})

Example 3: Feature Flags

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    VITE_FEATURE_NEW_UI: Schema.boolean(),
    VITE_FEATURE_ANALYTICS: Schema.boolean(),
    VITE_FEATURE_DARK_MODE: Schema.boolean(),
    VITE_FEATURE_BETA: Schema.boolean().optional(),
  },
})

Example 4: Authentication

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    VITE_AUTH_PROVIDER: Schema.enum(['google', 'github', 'email'] as const),
    VITE_AUTH_SECRET: Schema.string(),
    VITE_AUTH_EXPIRES_IN: Schema.number(),
    VITE_AUTH_REFRESH_TOKEN: Schema.boolean(),
  },
})

Example 5: Mixed Types

import ValidateEnv, { Schema } from '@vwinterdev/vite-env-validator'

ValidateEnv({
  schema: {
    // Required
    VITE_APP_NAME: Schema.string(),
    VITE_APP_URL: Schema.string({ format: 'url' }),
    VITE_APP_PORT: Schema.number(),
    VITE_APP_ENV: Schema.enum(['dev', 'prod'] as const),
    VITE_APP_DEBUG: Schema.boolean(),
    
    // Optional
    VITE_APP_DESCRIPTION: Schema.string().optional(),
    VITE_APP_VERSION: Schema.string().optional(),
    VITE_APP_MAX_USERS: Schema.number().optional(),
    VITE_APP_MAINTENANCE: Schema.boolean().optional(),
  },
})

Error Handling

When validation fails, the plugin will:

  • Display all validation errors in a clear format
  • Show which environment variables were found
  • Stop the build process with an error

Example error output:

Environment variables validation error:
  - VITE_PORT: Missing environment variable "VITE_PORT"
  - VITE_API_URL: Invalid URL format

Found environment variables:
  - VITE_DEBUG
  - VITE_API_KEY

Please check your .env file

Type Safety

The plugin automatically converts string values from .env files to appropriate types:

  • Schema.number() → converts "123"123
  • Schema.boolean() → converts "true"true, "false"false
  • z.coerce.number() → converts "123"123 (Zod validator)
  • z.coerce.boolean() → converts "true"true (Zod validator)

Development

Setup

pnpm install

Build

pnpm build

Test

pnpm test

CI/CD

This project uses GitHub Actions for automated testing and publishing.

Automatic Publishing

The package is automatically published to npm when you create a git tag:

# Bump version manually in package.json
git add package.json
git commit -m "chore: bump version to 2.0.3"
git tag v2.0.3
git push origin main --tags

Manual Publishing via GitHub Actions

You can also trigger a version bump and publish manually:

  • Go to Actions tab in GitHub
  • Select Publish to npm workflow
  • Click Run workflow
  • Choose version bump type (patch, minor, major)
  • Click Run workflow

Setup NPM Token

To enable automatic publishing, add your npm token to GitHub Secrets:

  • Go to your repository SettingsSecrets and variablesActions
  • Click New repository secret
  • Name: NPM_TOKEN
  • Value: Your npm access token (create at https://www.npmjs.com/settings/vwinterdev/tokens)
  • Click Add secret

License

MIT

Keywords

vite

FAQs

Package last updated on 06 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts