← All posts
AI-generated codevibe codingsecurityweb app securityNext.js

How to Secure AI-Generated Code: A Vibe-Coded App Security Guide

O

OverMCP Team

Quick answer

Securing AI-generated code in vibe-coded apps requires a proactive approach: treat every AI output as untrusted, run automated security scans, and manually review critical paths. Most vulnerabilities come from AI models copying insecure patterns, not from malice. Start by scanning for exposed secrets, checking dependencies, and validating inputs.

What to check first

Before you deep-dive into fixes, run this checklist on your AI-built app:

  • Secret leaks: Use a secret leak scanner to find API keys, tokens, and credentials committed to your repo.
  • Security headers: Verify your app sends proper headers like CSP, HSTS, X-Frame-Options using a security headers checker.
  • SSL/TLS: Ensure your domain has a valid SSL certificate with an SSL certificate checker.
  • Dependencies: Run npm audit or similar to spot known vulnerabilities in your packages.
  • Input validation: Check that all user inputs are sanitized and validated.
  • Authentication and authorization: Confirm that every API route and page enforces proper access controls.
  • Error handling: Ensure error messages don't leak stack traces or sensitive info.
  • Step-by-step fix

    1. Scan for leaked secrets

    AI coding tools often hardcode keys or leave .env files exposed. Run a secret scan on your repository. If you find any, rotate the keys immediately, remove them from history, and add .env to .gitignore.

    2. Add security headers

    Use middleware to set security headers. In Next.js, you can add them in next.config.js:

    // next.config.js
    const securityHeaders = [
      { key: 'X-Frame-Options', value: 'DENY' },
      { key: 'X-Content-Type-Options', value: 'nosniff' },
      { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
      { key: 'Content-Security-Policy', value: "default-src 'self'; script-src 'self'" },
      { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
    ];
    
    module.exports = {
      async headers() {
        return [{ source: '/(.*)', headers: securityHeaders }];
      },
    };

    3. Validate and sanitize inputs

    AI-generated forms often skip validation. Use libraries like zod or joi to validate data server-side. For SQL, use parameterized queries or an ORM.

    // Example with zod
    const schema = z.object({
      email: z.string().email(),
      password: z.string().min(8),
    });

    4. Fix authentication and authorization

    Review every API route. Ensure you check the user's role or session before returning data. Use middleware like withAuth in Next.js.

    5. Monitor continuously

    After fixes, set up continuous security monitoring to catch new issues as you iterate.

    Common mistakes

  • Trusting AI output: AI models generate code that looks correct but may have hidden flaws. Always review.
  • Hardcoding secrets: You'll find API keys in source code because AI copied them from tutorials.
  • Ignoring dependency warnings: npm audit flags high-severity CVEs, but many devs skip fixing them.
  • Missing rate limiting: AI-generated APIs often have no rate limiting, making them easy to abuse.
  • No input validation: Forms and endpoints accept anything, leading to injection attacks.
  • Overly permissive CORS: Setting Access-Control-Allow-Origin: * is common and dangerous.
  • Skipping security headers: Without CSP, your app is vulnerable to XSS.
  • How to build security into your vibe-coding workflow

    Use security-aware prompts

    When asking AI to generate code, include security requirements: "Use parameterized queries, validate input, and add rate limiting."

    Review AI-generated code with a security lens

    Don't just skim for syntax. Look for:

  • Direct SQL string concatenation
  • eval() or exec() calls
  • Missing httpOnly cookies
  • Insecure random number generation
  • Automate security scanning

    Use tools like OverMCP's free AI app security scanner to scan your codebase for vulnerabilities before each deploy.

    Keep dependencies updated

    AI tools often install outdated packages. Regularly run npm update and npm audit fix.

    Real-world example: fixing a leaked API key

    I once built a demo app with Cursor that used a Stripe secret key. The AI put it directly in a component file. I later pushed to a public GitHub repo. Within hours, someone scraped the key and made fraudulent charges. The fix: revoke the key, scrub the git history, and use environment variables. I now run a secret leak scanner before every push.

    FAQ

    How can I secure AI-generated code without slowing down?

    Use automated scans that integrate into your CI/CD pipeline. Tools like OverMCP can run on every commit, catching issues instantly.

    What are the most common vulnerabilities in AI-built apps?

    Exposed secrets, missing security headers, and broken access control are top issues. Also, weak input validation leads to injection attacks.

    Does OverMCP work with any AI coding tool?

    Yes, OverMCP scans code from Cursor, Bolt.new, v0, Lovable, and more. It integrates with your Vercel deployment for continuous checks.

    Final thoughts

    Securing AI-generated code isn't optional—it's part of being a responsible developer. By following these steps, you can ship fast without shipping insecure. Start with a free scan today and make security a habit.

    ---

    Note: This guide is based on common patterns observed in vibe-coded apps. Always test your own code thoroughly.

    Is your app secure?

    Free scan in 30 seconds. No signup needed.

    Scan My App Free