惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
V
Visual Studio Blog
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
L
LangChain Blog
Martin Fowler
Martin Fowler
GbyAI
GbyAI
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop trusting environment variables in your TypeScript apps
Samuel Fontebasso · 2026-06-28 · via DEV Community

Environment variables look simple until one of them is missing, empty, malformed, or interpreted in a way your application did not expect.

In TypeScript projects, this can be easy to overlook. The code may be typed, the build may pass, and the app may still ship with broken configuration.

This is especially common in frontend builds, server-side rendering, backend services, CLI tools, Docker images, and CI/CD pipelines, where configuration is injected from outside the codebase.

That is the problem valitype is designed to address: strict, type-safe validation of environment variables with zero dependencies.

The problem with environment variables

Environment variables are always external input.

They can come from:

  • .env files
  • CI/CD variables
  • Docker or container platforms
  • hosting providers
  • build scripts
  • deployment environments

TypeScript can describe what your code expects, but it cannot guarantee that the environment actually contains valid values.

This looks harmless:

const apiUrl = import.meta.env.VITE_API_URL
const debug = Boolean(import.meta.env.VITE_DEBUG)
const port = Number(process.env.PORT)

But simple casting can hide invalid configuration:

Boolean('false') // true
Boolean('0')     // true

Number('0xff') // 255
Number('1e5')  // 100000
Number('')     // 0

For application configuration, “parseable” is not the same as “valid”.

Invalid configuration should be caught before deployment, either during build, CI, server startup, or a dedicated validation step.

The problem in React and frontend builds

React applications usually do not read environment variables directly at runtime in the browser. Instead, tools like Vite and frameworks like Next.js inject selected values during build time.

That makes validation important.

Once the frontend bundle is built and deployed, changing a bad environment variable usually means rebuilding and redeploying the application.

For frontend apps, validation should answer a few basic questions before shipping:

  • Is the variable present when required?
  • Is the value non-empty?
  • Is the URL really an http or https URL?
  • Is the environment one of the allowed values?
  • Is a numeric value actually written as a decimal number?

A small validation layer can catch these problems early and fail clearly.

Vite environment variables

Vite exposes environment variables through import.meta.env.

By default, only variables prefixed with VITE_ are exposed to client-side code.

Example:

VITE_API_URL=https://api.example.com
VITE_APP_ENV=production
API_SECRET=super-secret-value

In application code:

const apiUrl = import.meta.env.VITE_API_URL
const appEnv = import.meta.env.VITE_APP_ENV

VITE_API_URL and VITE_APP_ENV are available to the frontend bundle. API_SECRET is not exposed because it does not use the VITE_ prefix.

That prefix rule is useful, but it is not validation.

Vite decides what can be exposed. It does not guarantee that the exposed values are present, valid, or safe for your application logic.

With valitype, you can create a small config module:

import { validateValue } from 'valitype'

export const config = {
  apiUrl: validateValue('VITE_API_URL', import.meta.env.VITE_API_URL, {
    type: 'url',
    required: true,
  }),

  appEnv: validateValue('VITE_APP_ENV', import.meta.env.VITE_APP_ENV, {
    type: { enum: ['development', 'staging', 'production'] },
    default: 'development',
  }),
}

Now the application has a clear configuration boundary.

Vite controls exposure. valitype controls validity.

This validation runs when the config module is executed. In frontend-only builds, use this pattern together with a prebuild validation step, CI check, or a tool like envguardr if you want the build itself to fail before deployment.

One rule still applies: never put secrets in VITE_ variables. Anything exposed through import.meta.env.VITE_* should be treated as public configuration.

Next.js environment variables

Next.js has both server-side and public environment variables.

Server-side variables can be read from process.env:

const apiUrl = process.env.API_URL

Public variables use the NEXT_PUBLIC_ prefix and can be exposed to the browser:

const appUrl = process.env.NEXT_PUBLIC_APP_URL

This separation is important, but it does not validate the values.

A safer approach is to create explicit config modules.

For server-side configuration:

import { validateValue } from 'valitype'

export const serverConfig = {
  apiUrl: validateValue('API_URL', process.env.API_URL, {
    type: 'url',
    required: true,
  }),

  nodeEnv: validateValue('NODE_ENV', process.env.NODE_ENV, {
    type: { enum: ['development', 'production', 'test'] },
    default: 'development',
  }),
}

For public configuration:

import { validateValue } from 'valitype'

export const publicConfig = {
  appUrl: validateValue('NEXT_PUBLIC_APP_URL', process.env.NEXT_PUBLIC_APP_URL, {
    type: 'url',
    required: true,
  }),
}

This keeps server-only values and browser-exposed values separate, while still validating both.

The important point is not to validate everything in one place blindly. Public config and server config have different security boundaries.

Node.js backend and CLI usage

Backend services and CLI tools often depend heavily on environment variables.

Examples:

const port = process.env.PORT
const logLevel = process.env.LOG_LEVEL
const region = process.env.AWS_REGION
const queueArn = process.env.QUEUE_ARN

If these values are wrong, the application may start incorrectly, connect to the wrong service, or fail later during execution.

With valitype, you can validate them at startup:

import { validateValue, validators } from 'valitype'

export const config = {
  port: validateValue('PORT', process.env.PORT, {
    type: 'number',
    default: 3000,
  }),

  logLevel: validateValue('LOG_LEVEL', process.env.LOG_LEVEL, {
    type: { enum: ['debug', 'info', 'warn', 'error'] },
    default: 'info',
  }),

  awsRegion: validateValue('AWS_REGION', process.env.AWS_REGION, {
    type: 'custom',
    validator: validators.oneOf([
      'us-east-1',
      'us-east-2',
      'us-west-1',
      'us-west-2',
      'eu-west-1',
      'eu-central-1',
      'ap-southeast-1',
      'ap-southeast-2',
    ]),
    required: true,
  }),

  queueArn: validateValue('QUEUE_ARN', process.env.QUEUE_ARN, {
    type: 'custom',
    validator: validators.awsArn('sqs'),
    required: true,
  }),
}

This is useful for:

  • Node.js APIs
  • workers
  • queue consumers
  • scheduled jobs
  • CLI tools
  • Dockerized services
  • CI/CD scripts

The application either starts with valid configuration or fails early with a clear error.

Validating config with valitype

valitype is a small TypeScript library for validating environment variables and configuration values.

It is not trying to replace full schema validation libraries. If you need complex object parsing, nested schemas, form validation, or full data validation, tools like Zod, Valibot, Joi, or Yup may be a better fit.

valitype focuses on a narrower problem:

  • validate environment variables
  • return typed values
  • avoid runtime dependencies
  • fail early with structured errors
  • keep configuration code easy to read

Example:

import { validateValue } from 'valitype'

const port = validateValue('PORT', process.env.PORT, {
  type: 'number',
  required: true,
})

The return type is inferred from the rule. In this case, port is a number.

For booleans:

const debug = validateValue('DEBUG', process.env.DEBUG, {
  type: 'boolean',
  default: false,
})

For enums:

const environment = validateValue('APP_ENV', process.env.APP_ENV, {
  type: { enum: ['development', 'staging', 'production'] },
  default: 'development',
})

For custom validation:

import { validateValue, validators } from 'valitype'

const apiKey = validateValue('API_KEY', process.env.API_KEY, {
  type: 'custom',
  validator: validators.regex(/^[a-z0-9]{32}$/),
  required: true,
})

Structured error handling

When validation fails, valitype throws a ValidationError.

import { validateValue, ValidationError } from 'valitype'

try {
  validateValue('PORT', '0xff', {
    type: 'number',
    required: true,
  })
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(err.code)
    console.log(err.key)
    console.log(err.value)
    console.log(err.message)
  }
}

This makes errors easier to handle programmatically.

Available error codes include:

REQUIRED
INVALID_NUMBER
INVALID_BOOLEAN
INVALID_URL
INVALID_ENUM
INVALID_CUSTOM
UNKNOWN_RULE

That is useful when you want to format errors differently in a CLI, fail a validation step in CI, or return consistent diagnostics in tooling.

Why strict validation matters

Some JavaScript conversions are convenient, but too permissive for configuration.

For example, valitype rejects values like:

0xff
1e5
''
'   '

for number validation.

It also requires URL values to use http or https, avoiding accidental acceptance of schemes like:

file://
ftp://

For environment variables, strict behavior is usually safer than permissive parsing.

Configuration should be explicit.

Where valitype came from

valitype started as the validation layer behind envguardr, a CLI tool for validating environment variables using a JavaScript or TypeScript schema.

The first version was created while building envguardr for the Amazon Q Developer “Quack The Code” challenge.

Since then, valitype has continued as a standalone open source library focused on strict, dependency-free environment validation for TypeScript projects.

Installation

npm install valitype

Final thoughts

Environment variables are part of your application boundary.

They come from outside your code, so they deserve validation before your app depends on them.

For TypeScript projects, the goal is not just to make configuration typed after reading it. The goal is to reject invalid configuration before it reaches production.

That is where a small tool like valitype can help.