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

推荐订阅源

Martin Fowler
Martin Fowler
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
IT之家
IT之家
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Y
Y Combinator Blog
博客园 - 【当耐特】
The Cloudflare Blog
宝玉的分享
宝玉的分享
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Visual Studio Blog
小众软件
小众软件
博客园_首页
Last Week in AI
Last Week in AI
J
Java Code Geeks
V
V2EX
雷峰网
雷峰网
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
腾讯CDC
博客园 - 司徒正美
Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
DataBreaches.Net
博客园 - 三生石上(FineUI控件)
MyScale Blog
MyScale Blog
云风的 BLOG
云风的 BLOG
The Register - Security
The Register - Security
M
MIT News - Artificial intelligence
Microsoft Azure Blog
Microsoft Azure Blog
T
The Blog of Author Tim Ferriss
N
Netflix TechBlog - Medium
F
Full Disclosure
B
Blog
H
Help Net Security
C
Check Point Blog
WordPress大学
WordPress大学
人人都是产品经理
人人都是产品经理
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Jina AI
Jina AI
酷 壳 – CoolShell
酷 壳 – CoolShell
Blog — PlanetScale
Blog — PlanetScale
L
LangChain Blog
P
Proofpoint News Feed
D
Docker
Microsoft Security Blog
Microsoft Security Blog

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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.