Back to Security Academy
AI CODE SMELLSBEGINNER5 min readCWE-798ZX-SECRETS-001

Preventing Exposed API Keys & Secrets in AI-Generated Frontend Bundles

Understanding why environment variables with NEXT_PUBLIC_ or VITE_ are baked into client JS, and how to establish strict secret isolation.

Why AI coding tools introduce this vulnerability

When an AI prompt mentions "Connect to OpenAI API in the React frontend", the AI often outputs process.env.NEXT_PUBLIC_OPENAI_API_KEY. The developer assumes .env is safe, unaware that Next.js and Vite inline all NEXT_PUBLIC_ and VITE_ prefixed variables directly into the browser bundle.

Technical Vulnerability Analysis

Any credential compiled into client-side JavaScript can be extracted by scraping web scrapers, automated botnets, and curious users in seconds. Leaked database URLs, Stripe secret keys, AWS access keys, and OpenAI tokens lead to massive financial damage and database compromise.

VULNERABLE IMPLEMENTATION (DO NOT USE)
// .env.local (DANGEROUS)
NEXT_PUBLIC_DATABASE_URL="postgres://postgres:pass@db.example.com/prod"
NEXT_PUBLIC_OPENAI_SECRET="sk-proj-xyz123..."

// Client Component:
import { OpenAI } from 'openai';
const client = new OpenAI({ apiKey: process.env.NEXT_PUBLIC_OPENAI_SECRET });
Exposes database credentials and LLM billing keys to anyone opening browser DevTools.

Remediation Playbook & Code Fixes

SECURE HARDENED PATCH (.env.local)
# Correct Server-Only Secrets (NO NEXT_PUBLIC_ PREFIX)
DATABASE_URL="postgres://postgres:pass@db.example.com/prod"
OPENAI_API_KEY="sk-proj-xyz123..."

# Only Non-Sensitive Configuration for Client:
NEXT_PUBLIC_APP_URL="https://zerivex.tech"

Why this fix works: Remove NEXT_PUBLIC_ prefixes from all secrets. Secrets are only accessible on the server.

Local CLI Verification Commands

Scan production HTML markup and asset manifests for token regexes.
curl -s https://example.com | grep -oE '(sk_live_[0-9a-zA-Z]{24}|ghp_[0-9a-zA-Z]{36})'
Expected result: (empty response - zero API key tokens found)

Pre-Deployment Self-Audit Checklist

Knowledge Check: Verify Your Understanding

What is the primary architectural cause of preventing exposed api keys & secrets in ai-generated frontend bundles?

Test your website for ZX-SECRETS-001

Run our 14 deterministic engines to inspect your live deployment.

Launch scan for this flaw