Security
Hardcoded Secrets in TypeScript: How to Manage Them Safely
TypeScript projects — especially Next.js and Express apps — are frequently pushed to GitHub with hardcoded API keys. Secret scanning bots detect these within minutes.
❌ Hardcoded Secrets
const stripeClient = new Stripe(
'sk_live_51H4XXXXXXXXXXXXXXXX', // Real key exposed!
{ apiVersion: '2023-10-16' }
);
const jwtSecret = 'mysupersecretkey';✅ Environment Variables with Validation
const requiredEnvVars = ['STRIPE_SECRET_KEY', 'JWT_SECRET', 'DATABASE_URL'] as const;
for (const key of requiredEnvVars) {
if (!process.env[key]) throw new Error(`Missing: ${key}`);
}
export const env = {
stripeKey: process.env.STRIPE_SECRET_KEY!,
jwtSecret: process.env.JWT_SECRET!,
} as const;💡
Pro tip: Use @t3-oss/env-nextjs or Zod to define a typed schema for env vars with validation. Missing variables fail at build time with a clear error.
Paste this code into LearnCodeGuide
Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.
Analyze TypeScript Code →