← All posts
environment variable validationvibe codingsecurityNext.jsAI apps

Fix Missing Environment Variable Validation in Vibe-Coded Apps

O

OverMCP Team

Quick answer

Missing environment variable validation is one of the most common security gaps in vibe-coded apps. Fix it by adding a centralized validation function that checks all required variables at app startup, using a library like envalid or a custom utility. This prevents runtime crashes and secret leaks when variables are missing in production.

What is environment variable validation vibe coding?

When you build apps quickly with AI tools like Cursor, Bolt.new, or v0, environment variables are often defined in .env files but never validated before use. This means your app might silently fall back to undefined values, crash in production, or expose sensitive data. Environment variable validation vibe coding is the practice of automatically checking that all required environment variables are set and correctly formatted at startup, catching misconfigurations before they cause damage.

Why vibe-coded apps skip validation

AI coding tools generate code that works on your local machine, where .env files are typically complete. But when you deploy to production, variables can be missing due to:

  • Manual deployment errors: Forgetting to set a variable in Vercel or Netlify.
  • Team mismatches: Different developers have different .env files.
  • CI/CD pipeline gaps: Environment variables not passed correctly.
  • Without validation, your app might start successfully but fail later with cryptic errors like Cannot read property of undefined or, worse, leak sensitive data via default values.

    What to check first

    Before adding validation, audit your current app for potential issues:

  • [ ] List all environment variables used in your code (search for process.env or import.meta.env).
  • [ ] Identify which variables are required vs optional.
  • [ ] Check if any variable is used without a fallback or default.
  • [ ] Verify that your .env.example file is up to date and documented.
  • [ ] Test your app locally with a missing variable to see the error behavior.
  • [ ] Scan for leaked secrets using a secret leak scanner.
  • Step-by-step fix

    1. Install a validation library (optional)

    While you can write custom validation, libraries like envalid (Node.js) or zod (TypeScript) simplify the process. For this guide, we'll use a lightweight custom approach that works in any vibe-coded app.

    2. Create a configuration module

    Create a file called config.js or config.ts in your project root. This module will read all environment variables, validate them, and export a typed configuration object.

    // config.js
    function required(name) {
      const value = process.env[name];
      if (!value) {
        throw new Error(`Missing required environment variable: ${name}`);
      }
      return value;
    }
    
    function optional(name, defaultValue) {
      return process.env[name] || defaultValue;
    }
    
    export const config = {
      DATABASE_URL: required('DATABASE_URL'),
      JWT_SECRET: required('JWT_SECRET'),
      OPENAI_API_KEY: required('OPENAI_API_KEY'),
      PORT: optional('PORT', '3000'),
      NODE_ENV: optional('NODE_ENV', 'development'),
    };

    3. Validate at app startup

    In your main entry file (e.g., index.js, app.js, or server.js), import and validate the config before starting your server or framework.

    // server.js or index.js
    import { config } from './config.js';
    
    // If any required variable is missing, the app will crash immediately
    console.log('Configuration validated successfully');
    console.log(`App running in ${config.NODE_ENV} mode on port ${config.PORT}`);
    
    // Your app initialization code here

    4. For Next.js apps (App Router)

    Create a lib/config.js file and use it in your API routes or server components.

    // lib/config.js
    function required(name) {
      const value = process.env[name];
      if (!value) {
        throw new Error(`Missing required environment variable: ${name}`);
      }
      return value;
    }
    
    export const config = {
      SUPABASE_URL: required('NEXT_PUBLIC_SUPABASE_URL'),
      SUPABASE_ANON_KEY: required('NEXT_PUBLIC_SUPABASE_ANON_KEY'),
      STRIPE_SECRET_KEY: required('STRIPE_SECRET_KEY'),
    };

    Then, in your layout.js or middleware.js, call the config to validate at build time or on each request.

    // middleware.js
    import { config } from './lib/config.js';
    
    export function middleware() {
      // This will throw if variables are missing
      config;
      return NextResponse.next();
    }

    5. Add type safety (TypeScript)

    If you're using TypeScript, define a typed config object:

    // config.ts
    export interface AppConfig {
      DATABASE_URL: string;
      JWT_SECRET: string;
      OPENAI_API_KEY: string;
      PORT: string;
      NODE_ENV: 'development' | 'production' | 'test';
    }
    
    function required(name: string): string {
      const value = process.env[name];
      if (!value) {
        throw new Error(`Missing required environment variable: ${name}`);
      }
      return value;
    }
    
    export const config: AppConfig = {
      DATABASE_URL: required('DATABASE_URL'),
      JWT_SECRET: required('JWT_SECRET'),
      OPENAI_API_KEY: required('OPENAI_API_KEY'),
      PORT: process.env.PORT || '3000',
      NODE_ENV: (process.env.NODE_ENV as AppConfig['NODE_ENV']) || 'development',
    };

    6. Automate with OverMCP

    Use a free AI app security scanner to continuously monitor your deployed app for missing environment variables and other misconfigurations. OverMCP can alert you when a variable is missing in production, preventing silent failures.

    Common mistakes

    1. Relying on `.env.example` alone

    Many vibe-coded apps include a .env.example file but never check it against actual usage. The file quickly becomes outdated as new variables are added.

    2. Using default values for sensitive keys

    // Bad: exposes a default secret
    const JWT_SECRET = process.env.JWT_SECRET || 'my-default-secret';

    This makes your app vulnerable if the environment variable is missing. Always throw an error instead.

    3. Only validating in development

    Some developers add validation in their local environment but remove it or skip it in production, thinking production is more stable. In reality, production is where misconfigurations are most dangerous.

    4. Not validating formatting

    Environment variables like API keys often have specific formats (e.g., sk-... for OpenAI). Validate the format to catch typos.

    function validateApiKey(key) {
      if (!key.startsWith('sk-')) {
        throw new Error('Invalid API key format');
      }
      return key;
    }

    5. Forgetting `NEXT_PUBLIC_` prefix

    In Next.js, client-side variables must start with NEXT_PUBLIC_. Missing this prefix causes runtime errors in the browser. Validate both server and client variables separately.

    How OverMCP helps

    OverMCP automatically scans your vibe-coded app for missing environment variable validation, leaked secrets, and other security issues. Instead of manually checking each deployment, you can set up continuous security monitoring to catch problems before they reach users. It integrates with Vercel, Netlify, and GitHub, so you can validate environment variables directly in your deployment pipeline.

    FAQ

    What happens if I don't validate environment variables?

    Your app may crash with obscure errors, leak sensitive data through fallbacks, or behave unexpectedly in production. For example, a missing DATABASE_URL might cause your app to default to a local database, exposing user data.

    Can I validate environment variables in the browser?

    No, browser code cannot access process.env directly. Use server-side validation in API routes or server components. For client-side variables (prefixed with NEXT_PUBLIC_), validate them on the server before sending them to the client.

    Does OverMCP automatically fix missing environment variables?

    OverMCP detects missing variables and alerts you, but you must set them in your hosting provider (e.g., Vercel, Netlify) or CI/CD pipeline. Use the Vercel security scanner to check your production environment for missing variables.

    Is your app secure?

    Free scan in 30 seconds. No signup needed.

    Scan My App Free