The Complete Secure Vibe Coding Guide: Ship Fast Without Getting Hacked

Quick Answer

45% of AI-generated code fails security tests. To vibe code safely: 1) Use secure prompts with explicit security requirements, 2) Set up security rules files in your AI tool, 3) Review code with the 5-minute checklist, 4) Run automated scanners.

The Vibe Coding Security Problem

Why AI Code Isn't Secure by Default

AI coding tools have transformed how we build software. But there's a problem: 45% of AI-generated code fails security tests according to Veracode's 2025 analysis of 100+ LLMs across 80 tasks. For Java specifically, 72% of generated code contained vulnerabilities.

This isn't an isolated finding. Pearce et al.'s research (ACM CCS 2023) found that 40% of 1,689 programs generated by Copilot contained security vulnerabilities. Stanford researchers discovered that developers using AI assistants write significantly MORE insecure code than those without - and are more likely to believe their code is secure.

Why does this happen? AI optimizes for "code that works," not "code that's secure." Training data includes millions of Stack Overflow answers and GitHub repos - much of it containing vulnerabilities. AI doesn't distinguish between trusted internal data and untrusted user input. When you ask for a login form, you get a login form. Authentication, rate limiting, and secure error handling? Only if you ask for them.

The Five Security Sins of AI Code

These vulnerabilities appear consistently across all AI coding tools:

  1. Hardcoded Secrets - API keys, passwords, and tokens directly in code. AI generates example values that get committed.
  2. Missing Authentication - Routes and endpoints that work but have no auth checks. "Create an API" doesn't imply "protect it."
  3. Injection Vulnerabilities (SQL, Command) - User input concatenated directly into queries and commands.
  4. Excessive Permissions - origin: '*' in CORS, admin access by default, overly permissive policies.
  5. Trusting the Client - Validation only on the frontend, no server-side checks, assuming input is safe.

You're Still the Developer

The OpenSSF Security Guide puts it simply: "AI is the assistant, you're the developer." Every line of code that ships is your responsibility - whether you wrote it or AI generated it. AI doesn't replace security knowledge; it increases the need for it.

The good news: you don't need to become a security expert. You need to follow a systematic process. This guide gives you that process.

Secure Prompting (Shift Left)

Why Prompts Matter for Security

Your prompt is more than a request - it's a design artifact. It defines requirements, technical approach, and constraints. If you don't mention security, AI won't add it. Research shows that enhanced security prompts can reduce vulnerabilities by up to 56%.

The Stanford user study found that developers who prompted more carefully produced fewer vulnerabilities. This is your first line of defense: get secure code from the start.

The Secure Prompt Formula

Structure every significant prompt with these four components:

WHATFunctional requirement - what the code should do
HOWTechnical approach - frameworks, patterns to use
SECURESecurity requirements - explicit protections needed
AVOIDCWEs and patterns to prevent
INSECURE PROMPT
Create a login form that checks the database for the user
SECURE PROMPT
Create a secure login form for a Next.js app with these requirements:

FUNCTIONAL:
- Accept email and password
- Check against PostgreSQL database
- Return JWT token on success

SECURITY:
- Use bcrypt for password comparison (never store plain passwords)
- Parameterized queries only (prevent SQL injection)
- Rate limit to 5 attempts per minute per IP
- Generic error messages ("Invalid credentials" not "User not found")
- Set secure, httpOnly, sameSite cookies

AVOID: CWE-89 (SQL injection), CWE-307 (brute force), CWE-209 (info disclosure)

Security Phrases to Include in Every Prompt

These phrases trigger secure patterns in AI output:

  • "Use parameterized queries"
  • "Validate and sanitize all input"
  • "Use environment variables for secrets"
  • "Add authentication check"
  • "Verify user owns this resource"
  • "Return generic error messages"
  • "Use HTTPS only"
  • "Set secure cookie flags"
  • "Add rate limiting"
  • "Escape output for [HTML/SQL/shell]"

Tool-Specific Secure Prompting

  • Cursor: Use .cursorrules for persistent security context across all sessions
  • Copilot: Add security comments before code blocks to guide generation
  • Claude Code: CLAUDE.md can include project-wide security rules
  • Bolt: Add "with security" to every generation request

Security Rules Files (Automated Guardrails)

What Are Rules Files?

Rules files are configuration that tells AI how to behave. They persist across sessions, providing consistent security context without repeating requirements in every prompt. Think of them as a security-focused senior developer reviewing every suggestion.

The Cloud Security Alliance and Wiz both recommend rules files as a critical security control for vibe coding.

The vibeship Security Rules (Copy-Paste Ready)

vibeship security rules for AI Tools
# Security Rules for AI Code Generation ## CRITICAL: Never Do These - NEVER hardcode API keys, passwords, secrets, or credentials - NEVER use eval(), exec(), or Function() with user input - NEVER build SQL queries with string concatenation - NEVER trust client-side validation alone - NEVER expose stack traces or detailed errors to users - NEVER use `origin: '*'` with credentials in CORS - NEVER store passwords in plain text ## ALWAYS Do These - ALWAYS use parameterized queries for database access - ALWAYS validate and sanitize ALL user input on the server - ALWAYS use environment variables for secrets - ALWAYS check authentication before protected operations - ALWAYS verify the user owns the resource (authorization) - ALWAYS use HTTPS in production - ALWAYS set secure, httpOnly, sameSite flags on cookies - ALWAYS return generic error messages to clients - ALWAYS escape output based on context (HTML, SQL, shell) ## Framework-Specific Rules ### Next.js - Use Server Actions or API routes for sensitive operations - Never expose NEXT_PUBLIC_ variables containing secrets - Use middleware for authentication checks - Validate Server Action inputs with Zod ### Express - Use helmet() for security headers - Use express-rate-limit for rate limiting - Use express-validator for input validation - Never use res.send(error.message) in production ### Supabase - ALWAYS enable RLS on tables with user data - Use getUser() not getSession() on the server - Never expose service_role key to client - Create policies for SELECT, INSERT, UPDATE, DELETE ### Database - Use ORM (Prisma, Drizzle) or parameterized queries - Never use $queryRaw or raw SQL with user input - Apply principle of least privilege to database users - Encrypt sensitive fields at rest ## When Generating Code 1. Assume all user input is malicious 2. Fail securely (deny by default) 3. Log security events (failed auth, validation errors) 4. Consider the OWASP Top 10 for every feature

Installing Security Rules

Cursor

# Create .cursor/rules/security.mdc in project root
mkdir -p .cursor/rules
# Paste the rules above into security.mdc

Claude Code

# Add to CLAUDE.md in project root
# Create the file and paste security rules section

GitHub Copilot

# Create .github/copilot-instructions.md
# Paste security rules

Windsurf

# Create .windsurfrules in project root
Warning: Rules files can be compromised. Research has shown hidden Unicode characters can inject malicious instructions. Always review rules files from external sources, store them in version control, and don't auto-run commands from untrusted rules.

Code Review & Scanning (Catch What Slipped Through)

Why Review Matters More with AI Code

AI generates code faster than humans can review. Volume increases but review time stays the same. The key insight: AI makes consistent mistakes. Once you know the patterns, you know what to look for.

The 5-Minute Security Review

Run through this checklist for every AI-generated file:

Authentication & Authorization

  • Is there an auth check before sensitive operations?
  • Does it verify the user owns the resource (IDOR prevention)?
  • Are routes protected that should be?

Input Handling

  • Is all user input validated on the server?
  • Are database queries parameterized (SQL injection)?
  • Is output escaped for its context (XSS)?

Secrets & Config

Error Handling

  • Are errors logged server-side?
  • Are error messages generic to clients (no stack traces)?

Quick Security Grep Commands

# Find potential hardcoded secrets
grep -r "api_key\|apikey\|secret\|password" --include="*.ts" --include="*.js"

# Find potential SQL injection
grep -r "\`SELECT\|'SELECT" --include="*.ts" --include="*.js"

# Find dangerous functions
grep -r "eval\|exec\|Function(" --include="*.ts" --include="*.js"

# Find console.log (remove before production)
grep -r "console.log" --include="*.ts" --include="*.js"

Automated Security Scanning

Free tools that catch what manual review misses:

ToolWhat It CatchesIntegration
GitleaksHardcoded secretsPre-commit, CI
SemgrepOWASP Top 10, custom rulesIDE, CI
npm auditVulnerable dependenciesCLI, CI
ESLint securityJS/TS security issuesIDE, CI
TrivyContainer/dependency vulnsCI

Setup Commands

# Gitleaks (secrets)
brew install gitleaks  # or download from GitHub
gitleaks detect --source .

# Semgrep (SAST)
pip install semgrep
semgrep --config=p/owasp-top-ten .

# npm audit (dependencies)
npm audit

# ESLint security
npm install eslint-plugin-security --save-dev

The AI Security Review Prompt

Use this with Claude, ChatGPT, or your AI tool for a second opinion:

AI Security Review Prompt
Review this code for security vulnerabilities. Check for: 1. **Injection flaws**: SQL injection, command injection, XSS 2. **Authentication issues**: Missing auth checks, weak session handling 3. **Authorization issues**: IDOR, missing ownership verification 4. **Data exposure**: Hardcoded secrets, verbose errors, excessive data in responses 5. **Configuration issues**: Insecure CORS, missing security headers For each issue found: - Describe the vulnerability - Show the vulnerable code - Explain the attack scenario - Provide the fixed code Code to review: [PASTE CODE HERE]

Automate Your Security Reviews: vibeship scanner automatically analyzes AI-generated code for vulnerabilities and provides fix suggestions.

Try vibeship scanner

Secure Deployment (Don't Undo Your Work)

Pre-Deployment Checklist

Before shipping your vibe coded app, verify these items. Use our complete pre-launch checklist for the full list.

Environment & Secrets

  • All secrets in environment variables (not code)
  • .env files in .gitignore
  • Different secrets for dev/staging/production
  • Service keys restricted to server-side only

Authentication

  • Auth required on all protected routes
  • Session/token expiration configured
  • Password reset flow secure
  • MFA available for admin accounts

Database

  • RLS enabled (if using Supabase)
  • Database user has minimum required permissions
  • Connection strings not exposed
  • Backups configured and tested

Network

  • HTTPS enforced (redirect HTTP)
  • Security headers configured (CSP, HSTS)
  • CORS configured for specific origins (not *)
  • Rate limiting on public endpoints

Security Headers Setup

// next.config.js
const securityHeaders = [
  { key: 'X-DNS-Prefetch-Control', value: 'on' },
  { key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
  { key: 'X-Frame-Options', value: 'SAMEORIGIN' },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'Referrer-Policy', value: 'origin-when-cross-origin' }
]

module.exports = {
  async headers() {
    return [{ source: '/(.*)', headers: securityHeaders }]
  },
}

Post-Deployment Monitoring

  • Set up error tracking (Sentry, LogRocket)
  • Monitor for leaked secrets (GitGuardian)
  • Regular dependency updates
  • Security scan in CI/CD pipeline
  • Periodic penetration testing for critical apps

Tool-Specific Security Guides

Each AI coding tool has unique patterns and vulnerabilities. Our detailed guides cover specific risks and mitigations:

Vulnerability Quick Reference

Every vulnerability AI tools commonly generate, with severity and fix guides. Bookmark this table.

VulnerabilitySeverityWhat HappensGuide
SQL InjectionCriticalAttackers steal your databaseFix
Hardcoded SecretsCriticalAPI keys exposed in codeFix
Missing AuthCriticalAnyone can access protected dataFix
Command InjectionCriticalAttackers run system commandsFix
Insecure DeserializationCriticalRemote code executionFix
XSSHighAttackers run scripts on usersFix
IDORHighUsers access each other's dataFix
CSRFHighAttackers trick users into actionsFix
SSRFHighServer fetches malicious URLsFix
Path TraversalHighAttackers access system filesFix
Sensitive Data ExposureHighStack traces leak to usersFix
JWT VulnerabilitiesHighToken bypass/forgeryFix
Mass AssignmentHighUsers modify forbidden fieldsFix
Open RedirectMediumPhishing via your domainFix
Missing Rate LimitingMediumBrute force attacks succeedFix
Insecure CORSMediumCross-origin attacks allowedFix

Stack-Specific Guides

Security guidance for popular vibe coding stacks:

Frequently Asked Questions

Is vibe coding safe?

Vibe coding can be safe if you follow security practices. Research shows AI-generated code frequently contains vulnerabilities - Veracode (2025) found 45% failed security tests, Pearce et al. found 40% contained flaws. These rates can be dramatically reduced with secure prompting, rules files, and code review. The key is treating AI as an assistant, not a replacement for security awareness.

What's the biggest security risk with AI coding tools?

Hardcoded secrets and missing authentication are the most common issues. AI tools generate functional code quickly, but they don't automatically add authentication checks or secure secret management unless you explicitly request it.

Do I need to be a security expert to vibe code safely?

No, but you need to follow a checklist. This guide provides everything you need: secure prompts, rules files, and review checklists. Use them consistently and you'll catch most issues. Security expertise helps, but systematic processes matter more.

Should I use Cursor rules for security?

Yes, absolutely. Rules files provide persistent security context so you don't have to repeat security requirements in every prompt. They act like a security-focused senior developer reviewing every AI suggestion. See Cursor Security Patterns for specific guidance.

How do I review AI-generated code for security?

Use the 5-minute security review checklist in this guide. Check for authentication, input validation, secrets exposure, and error handling. Then run automated tools like Semgrep and Gitleaks for additional coverage. Consider using our vibeship scanner for comprehensive analysis.

What percentage of AI-generated code has vulnerabilities?

Studies show significant vulnerability rates in AI-generated code. Veracode's 2025 testing found 45% of samples failed security tests. Pearce et al. found 40% of Copilot programs contained vulnerabilities. This is why review and scanning are essential.

Are there free security tools for vibe coding?

Yes! Gitleaks (secrets), Semgrep (SAST), npm audit (dependencies), and ESLint security plugin are all free and effective. Start with these before considering paid tools. Our vibeship scanner also offers a free tier.

How do I write secure prompts for AI coding?

Include explicit security requirements in every prompt. Use the formula: WHAT (function) + HOW (approach) + SECURE (requirements) + AVOID (CWEs). The more specific you are about security, the better the output. Research shows enhanced prompts can reduce vulnerabilities by up to 56%.

Start Vibe Coding Securely Today

You now have everything you need: secure prompts, rules files, review checklists, and vulnerability guides.

Try vibeship scanner

External References