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

推荐订阅源

罗磊的独立博客
S
Secure Thoughts
www.infosecurity-magazine.com
www.infosecurity-magazine.com
N
News and Events Feed by Topic
Google Online Security Blog
Google Online Security Blog
W
WeLiveSecurity
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security @ Cisco Blogs
V
V2EX - 技术
Webroot Blog
Webroot Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hacker News: Ask HN
Hacker News: Ask HN
N
News | PayPal Newsroom
C
CERT Recently Published Vulnerability Notes
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
Project Zero
Project Zero
S
Security Affairs
Scott Helme
Scott Helme
C
CXSECURITY Database RSS Feed - CXSecurity.com
Google DeepMind News
Google DeepMind News
L
LINUX DO - 热门话题
T
The Exploit Database - CXSecurity.com
N
News and Events Feed by Topic
C
Cybersecurity and Infrastructure Security Agency CISA
Cyberwarzone
Cyberwarzone
T
Tor Project blog
S
Security Archives - TechRepublic
Attack and Defense Labs
Attack and Defense Labs
P
Privacy International News Feed
The Hacker News
The Hacker News
SecWiki News
SecWiki News
B
Blog RSS Feed
T
Tenable Blog
Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
NISL@THU
NISL@THU
阮一峰的网络日志
阮一峰的网络日志
D
Docker
L
Lohrmann on Cybersecurity
博客园 - 司徒正美
Know Your Adversary
Know Your Adversary
Engineering at Meta
Engineering at Meta
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
Google Developers Blog
小众软件
小众软件
Recent Announcements
Recent Announcements
Cisco Talos Blog
Cisco Talos Blog
P
Proofpoint News Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More

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
Environment and Config Management in Node.js: The System That Scales Past One Server
ZyVOP · 2026-06-15 · via DEV Community

Every Node.js project starts with a .env file. That is fine. The problem is when the .env approach never evolves — when you still have a single .env.production manually SCP'd to a server at 2 AM before a launch, when a new developer spends three hours figuring out which environment variables are required, when a secret rotates and you realize you have no idea how many places it is set.

Config management is not glamorous but it is the foundation everything else sits on. This guide covers the full system: validated environment variables, environment-specific config, secrets that never touch your codebase, and the patterns that work from a single VPS to a multi-environment deployment.


The Problem With Unmanaged Config

Most teams have at minimum four environments: local development, CI, staging, and production. Each has different values for dozens of variables. Without a system:

  • Variables that exist in production but not in .env.example cause 3 AM surprises

  • A typo in an environment variable name silently falls back to undefined

  • Secrets rotate but old values persist on servers nobody remembers to update

  • A new developer clones the repo and cannot start the app without asking four people for values

The solution is three things: a schema that documents and validates every variable, a clear hierarchy for where values come from in each environment, and a secrets strategy that does not involve passing plaintext passwords in Slack.


Step 1 — Validated Config with Zod

Define every environment variable your app needs in one place. Validate at startup so the app crashes immediately with a clear error rather than failing mysteriously at runtime when a missing variable is first accessed.

// src/config/env.ts
import { z } from 'zod';

const EnvSchema = z.object({
  // ── Server ──────────────────────────────────────────────
  NODE_ENV: z.enum(['development', 'test', 'production', 'staging']),
  PORT:     z.coerce.number().int().min(1).max(65535).default(3000),
  LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warn', 'error']).default('info'),
  APP_VERSION: z.string().default('unknown'),
  APP_URL: z.string().url(),

  // ── Database ─────────────────────────────────────────────
  DATABASE_URL: z
    .string()
    .url('DATABASE_URL must be a valid connection string')
    .refine(
      url => url.startsWith('postgresql://') || url.startsWith('postgres://'),
      'DATABASE_URL must be a PostgreSQL connection string'
    ),
  DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(100).default(10),

  // ── Redis ─────────────────────────────────────────────────
  REDIS_URL: z.string().url().optional(),
  REDIS_HOST: z.string().default('localhost'),
  REDIS_PORT: z.coerce.number().int().default(6379),
  REDIS_PASSWORD: z.string().optional(),

  // ── Auth ──────────────────────────────────────────────────
  JWT_PRIVATE_KEY: z.string().min(1),
  JWT_PUBLIC_KEY:  z.string().min(1),
  JWT_REFRESH_SECRET: z.string().min(32, 'JWT_REFRESH_SECRET must be at least 32 characters'),

  // ── AWS ───────────────────────────────────────────────────
  AWS_REGION: z.string().default('us-east-1'),
  S3_BUCKET:  z.string().optional(),
  AWS_ACCESS_KEY_ID:     z.string().optional(),
  AWS_SECRET_ACCESS_KEY: z.string().optional(),

  // ── Email ─────────────────────────────────────────────────
  RESEND_API_KEY: z.string().optional(),

  // ── Payments ──────────────────────────────────────────────
  STRIPE_SECRET_KEY:      z.string().optional(),
  STRIPE_WEBHOOK_SECRET:  z.string().optional(),

  // ── Observability ─────────────────────────────────────────
  SENTRY_DSN: z.string().url().optional(),
});

// Validate immediately — crash at startup if config is invalid
const result = EnvSchema.safeParse(process.env);

if (!result.success) {
  console.error('\n❌ Invalid environment configuration:\n');
  const errors = result.error.flatten().fieldErrors;
  for (const [field, messages] of Object.entries(errors)) {
    console.error(`  ${field}: ${messages?.join(', ')}`);
  }
  console.error('\nCheck your .env file against .env.example\n');
  process.exit(1);
}

export const env = result.data;

// Type-safe access everywhere — no more process.env.PORT as string
// env.PORT is number, env.DATABASE_URL is guaranteed non-null


Step 2 — The .env.example File

The .env.example file is your documentation. It is committed to git, contains no real values, and shows every variable the app needs with a comment explaining what it is for.

# .env.example — copy to .env and fill in real values
# DO NOT commit .env — it is in .gitignore

# ── Server ──────────────────────────────────────────────────
NODE_ENV=development
PORT=3000
LOG_LEVEL=info
APP_URL=http://localhost:3000

# ── Database ────────────────────────────────────────────────
# PostgreSQL connection string
# Format: postgresql://USER:PASSWORD@HOST:PORT/DATABASE
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/myapp_dev
DATABASE_POOL_SIZE=10

# ── Redis ───────────────────────────────────────────────────
REDIS_HOST=localhost
REDIS_PORT=6379
# REDIS_PASSWORD=  # Not required in local dev

# ── Auth ────────────────────────────────────────────────────
# Generate with: openssl genrsa -out private.pem 2048 && openssl rsa -in private.pem -pubout -out public.pem
JWT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n..."
JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n..."
# Generate with: openssl rand -hex 64
JWT_REFRESH_SECRET=generate_with_openssl_rand_hex_64

# ── AWS ─────────────────────────────────────────────────────
AWS_REGION=us-east-1
# S3_BUCKET=your-bucket-name        # Only needed for file uploads
# AWS_ACCESS_KEY_ID=                # Use IAM roles in production instead
# AWS_SECRET_ACCESS_KEY=

# ── Email ────────────────────────────────────────────────────
# Get from resend.com
# RESEND_API_KEY=re_...

# ── Payments ─────────────────────────────────────────────────
# Get from Stripe dashboard
# STRIPE_SECRET_KEY=sk_test_...
# STRIPE_WEBHOOK_SECRET=whsec_...    # From: stripe listen --print-secret


Step 3 — Environment-Specific Config Objects

Some config is not secret — it is just different per environment. Build rates, feature defaults, timeouts. Put these in code, not in environment variables:

// src/config/index.ts
import { env } from './env';

const configs = {
  development: {
    rateLimits: {
      loginAttempts: 100,    // Relaxed for development
      apiRequests:   10000,
    },
    email: {
      sendReal: false,       // Log emails instead of sending in dev
    },
    cache: {
      ttl: 10,               // Short TTL for development iteration
    },
  },

  test: {
    rateLimits: {
      loginAttempts: 1000,   // High limit so tests don't hit rate limits
      apiRequests:   100000,
    },
    email: {
      sendReal: false,
    },
    cache: {
      ttl: 1,
    },
  },

  staging: {
    rateLimits: {
      loginAttempts: 10,
      apiRequests:   500,
    },
    email: {
      sendReal: true,        // Send real emails in staging
    },
    cache: {
      ttl: 60,
    },
  },

  production: {
    rateLimits: {
      loginAttempts: 5,
      apiRequests:   200,
    },
    email: {
      sendReal: true,
    },
    cache: {
      ttl: 300,
    },
  },
};

export const config = {
  env:    env.NODE_ENV,
  port:   env.PORT,
  isDev:  env.NODE_ENV === 'development',
  isTest: env.NODE_ENV === 'test',
  isProd: env.NODE_ENV === 'production',
  ...configs[env.NODE_ENV],
};


Step 4 — Secrets That Never Touch Your Codebase

For a VPS deployment, secrets belong on the server — not in CI environment variables, not in your .env.example, not in Slack.

Generating secrets correctly:

# JWT RSA key pair
openssl genrsa -out /opt/app/secrets/jwt_private.pem 2048
openssl rsa -in /opt/app/secrets/jwt_private.pem \
  -pubout -out /opt/app/secrets/jwt_public.pem

# Random secrets
openssl rand -hex 64 > /opt/app/secrets/jwt_refresh_secret
openssl rand -hex 32 > /opt/app/secrets/session_secret

# Set permissions — readable only by the app user
chmod 600 /opt/app/secrets/*
chown deploy:deploy /opt/app/secrets/*

The production .env file — set once via SSH, never synced through CI:

# On the VPS — set manually or via an encrypted secret store
cat > /opt/app/.env.production << 'EOF'
NODE_ENV=production
PORT=3000
APP_URL=https://yourapp.com
DATABASE_URL=postgresql://appuser:$(cat /opt/app/secrets/db_password)@localhost:5432/appdb
JWT_PRIVATE_KEY="$(cat /opt/app/secrets/jwt_private.pem | tr '\n' '\n')"
JWT_PUBLIC_KEY="$(cat /opt/app/secrets/jwt_public.pem | tr '\n' '\n')"
JWT_REFRESH_SECRET=$(cat /opt/app/secrets/jwt_refresh_secret)
RESEND_API_KEY=$(cat /opt/app/secrets/resend_api_key)
STRIPE_SECRET_KEY=$(cat /opt/app/secrets/stripe_secret_key)
EOF

chmod 600 /opt/app/.env.production
chown deploy:deploy /opt/app/.env.production


Step 5 — Config Access Patterns

With the validated env and config objects, accessing configuration is consistent everywhere:

import { env } from '../config/env';
import { config } from '../config';

// Environment variables — all typed and validated
const db = new Pool({
  connectionString: env.DATABASE_URL,
  max:              env.DATABASE_POOL_SIZE,
});

// Derived config — environment-appropriate values
const rateLimiter = new RateLimiter({
  maxRequests: config.rateLimits.apiRequests,
});

// Guard against features that need optional config
if (env.STRIPE_SECRET_KEY) {
  initializeStripe(env.STRIPE_SECRET_KEY);
} else if (config.isProd) {
  throw new Error('STRIPE_SECRET_KEY is required in production');
}


Step 6 — CI Config

In GitHub Actions, secrets go in repository secrets (Settings → Secrets), not in env: blocks directly in the YAML file where they appear in logs.

# .github/workflows/deploy.yml
jobs:
  deploy:
    steps:
      - name: Deploy to VPS
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: |
            # Reload app — env file is already on the server
            cd /opt/app
            docker compose pull
            docker compose up -d

Notice what is not passed via CI: DATABASE_URL, JWT keys, API keys. These live on the server in /opt/app/.env.production. CI only needs SSH access.


The Config Validation Script

Add a script that developers run after cloning the repo to verify their .env is complete:

// scripts/check-env.ts
import { EnvSchema } from '../src/config/env';
import * as dotenv from 'dotenv';

dotenv.config({ path: '.env' });

const result = EnvSchema.safeParse(process.env);

if (result.success) {
  console.log('✅ Environment configuration is valid');
} else {
  console.error('❌ Missing or invalid environment variables:\n');
  const errors = result.error.flatten().fieldErrors;
  for (const [field, messages] of Object.entries(errors)) {
    console.error(`  ${field}: ${messages?.join(', ')}`);
  }
  console.error('\nCopy .env.example to .env and fill in the required values.');
  process.exit(1);
}

// package.json
{
  "scripts": {
    "check:env": "tsx scripts/check-env.ts"
  }
}

Add it to the README setup steps. A new developer runs pnpm check:env and immediately knows exactly which variables they are missing.


The Rules That Prevent Config Incidents

 Every variable in the app is in .env.example  no undocumented variables
 Zod schema validates all variables at startup  no silent undefined falls
 .env is in .gitignore  never committed
 Secrets generated with openssl  not typed by hand
 Production secrets set on the server via SSH  never through CI env vars
 Different config objects per environment  not ternary chains in code
 check:env script runs on new developer setup
 Secrets rotated by updating the file on the server, not redeploying


Originally published on ZyVOP

💡 For more articles like this, subscribe to the ZyVOP newsletter!