Menu

Post image 1
Post image 2
1 / 2
0

Managing Environment Variables in Node.js: The Complete Guide

DEV Community·Alex Chen·17 days ago
#kAXuKu7t
Reading 0:00
15s threshold

Managing Environment Variables in Node.js: The Complete Guide Stop hardcoding secrets. Here's how to do it right. The Problem // ❌ NEVER do this const DB_PASSWORD = ' SuperSecret123! ' ; const API_KEY = ' sk-live-abc123def456 ' ; const STRIPE_SECRET = ' sk_test_... ' ; Enter fullscreen mode Exit fullscreen mode Solution 1: .env Files (The Standard) # .env file (NEVER commit this!) DB_HOST = localhost DB_PORT = 5432 DB_NAME = myapp DB_USER = admin DB_PASSWORD = secret123 API_URL = https://api.example.com API_KEY = abc123 NODE_ENV = development PORT = 3000 Enter fullscreen mode Exit fullscreen mode // Load .env (at the very top of your app, before anything else) import ' dotenv/config ' ; // or: require('dotenv').config(); // Access variables const dbHost = process . env . DB_HOST ; const port = process . env . PORT || 3000 ; Enter fullscreen mode Exit fullscreen mode Solution 2: Validation with Zod // config.js — Validate all env vars at startup import { z } from ' zod ' ; const envSchema = z .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More