TL;DR: Apps built quickly with AI tools such as Lovable, Bolt, v0, Cursor or Claude Code usually work well in the demo and fail in predictable ways in production. The common breaks are exposed API keys, databases readable by anyone, authorization checked only in the browser, no input validation, no tests, and no way to see errors. Most of these apps do not need a rewrite. They need a short, ordered hardening sprint: stop the leaks first, then lock down data access, then add validation, tests, monitoring and deployment discipline. This guide gives you the audit, the fixes with code, and the order to apply them.
Key takeaways
- "It works" is the start, not the finish. AI tools optimize for a working demo, not for hostile users, real data or scale.
- Security fails first. Leaked keys, open database tables and missing server-side checks are the most common serious problems.
- Fix in order of damage. Secrets and data exposure before features, tests before refactors.
- A rewrite is rarely the answer. Most vibe-coded apps can be hardened in one to three weeks of focused work.
- Keep the speed. The goal is to keep building with AI, with guardrails that catch its mistakes.
Why vibe-coded apps break in production
"Vibe coding" describes building software mostly by prompting an AI and accepting what it produces, often without reading every line. It is a genuinely powerful way to get from an idea to a working product. Founders build MVPs in a weekend that would have taken a team a month, and that is good for everyone.
The trouble is what the demo hides. A demo has one user, friendly input, a fresh database and no attacker. Production has many users at once, strange input, years of accumulated data, and people actively looking for weaknesses. AI coding tools generate code that satisfies the prompt in front of them. Unless you ask, they rarely add rate limits, row-level security, server-side authorization, input validation or error monitoring. Sometimes a later prompt quietly removes a check that an earlier prompt added.
Independent research backs this up. Security reviews of AI-generated code, including Veracode's research on generative AI code security, have found that a large share of generated samples contain known vulnerability patterns. Public incidents in 2025 and 2026 showed vibe-coded apps leaking user records and API keys because nobody reviewed the code before launch.
None of this means you should stop using AI tools. It means a vibe-coded app needs the same production review any other codebase needs, and that review tends to find the same handful of problems.
The prototype-to-production gap
It helps to name exactly what changes when an app goes live:
| Area | In the demo | In production |
|---|---|---|
| Users | You, one at a time | Many at once, some malicious |
| Input | Well-formed, expected | Empty, huge, malformed, hostile |
| Data | A few test rows | Real personal and payment data |
| Secrets | In the code or .env, works fine | Must never reach the browser or git history |
| Authorization | Hidden buttons look like security | Every request must be checked on the server |
| Errors | You see them in the console | Users see a blank page and leave |
| Changes | Prompt, accept, done | Must not break what already works |
| Cost | Free tier | API bills, database load, abuse |
Every row is a place where vibe-coded apps commonly fail. The rest of this guide walks through them in the order you should fix them.
Step 1: Run a quick production audit
Before changing anything, spend a day understanding what you have. You are looking for the problems that cause the most damage, not style issues. Work through these questions:
- Secrets: Are any API keys, database passwords or service tokens in the frontend code, the git history or public environment variables?
- Data access: Can a logged-out user, or a different logged-in user, read or change data they should not?
- Authorization: Are permission checks done on the server, or only by hiding buttons in the UI?
- Input: Is user input validated on the server before it reaches the database or an AI model?
- Abuse: Can someone call expensive endpoints, such as AI generation or email sending, thousands of times?
- Errors: Would you know if checkout broke at 2 a.m.?
- Tests: Is there any automated check that the core flow still works after a change?
- Deployment: Can you roll back a bad release in minutes?
Write down every finding with a severity. You will be tempted to fix things as you find them. Resist for one day, because the full picture changes your priorities.
Step 2: Stop leaking secrets
Exposed secrets are the most common and most urgent finding. AI tools often put an API key directly in a component because it is the shortest path to a working feature. In Next.js, any variable prefixed with NEXT_PUBLIC_ is bundled into the JavaScript every visitor downloads. In Vite apps, the same applies to VITE_ variables. If an OpenAI, Stripe secret or Supabase service role key sits there, anyone can copy it from the browser.
First, find them. Scan the code and the full git history, because deleting a key from the latest commit does not remove it from history:
# Scan the working tree and every commit for secrets
gitleaks detect --source . --log-opts="--all" --redact
# List environment variables that are exposed to the browser bundle
grep -rnE "NEXT_PUBLIC_|VITE_" --include=*.ts --include=*.tsx --include=*.js . \
| grep -viE "SITE_URL|APP_URL|SUPABASE_URL|SUPABASE_ANON_KEY|POSTHOG_KEY"
Then fix them in this order:
- Rotate every exposed key immediately, at the provider. Assume it has been copied.
- Move the call to the server, in an API route or server action, so the key never leaves the backend.
- Keep only truly public values public, such as your site URL or a Supabase anon key that is protected by row-level security.
- Add secret scanning to CI, so the next leak is caught before it merges.
Moving an AI call server-side looks like this in a Next.js route handler:
// app/api/summarise/route.ts: the key stays on the server
import { NextResponse } from 'next/server';
import OpenAI from 'openai';
import { z } from 'zod';
import { getSession } from '@/lib/auth';
import { rateLimit } from '@/lib/rate-limit';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // no NEXT_PUBLIC_ prefix
const Body = z.object({ text: z.string().min(1).max(8000) });
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: 'Sign in required' }, { status: 401 });
// Expensive endpoint: cap calls per user so one account cannot run up the bill.
const allowed = await rateLimit(`summarise:${session.userId}`, { limit: 20, windowSec: 3600 });
if (!allowed) return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
const parsed = Body.safeParse(await req.json());
if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 });
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: `Summarise:\n\n${parsed.data.text}` }],
max_tokens: 400,
});
return NextResponse.json({ summary: completion.choices[0]?.message.content ?? '' });
}
This one handler fixes four findings at once: the key is server-only, the user must be signed in, the endpoint is rate limited, and input size is bounded. For a longer treatment of key management, see our guide to eliminating secrets sprawl.
Step 3: Lock down database access
Many vibe-coded apps use Supabase or Firebase, where the browser talks to the database directly. That model is safe only if access rules are correct. When row-level security (RLS) is disabled, or a policy says "allow all", the public anon key that ships in your frontend can read and write every row in the table. This is the single most common cause of vibe-coded data leaks.
Check every table. In Supabase, enable RLS and write policies that tie rows to the signed-in user:
-- Turn on row-level security: with no policies, nobody can read or write.
alter table public.projects enable row level security;
-- Users can see only their own projects.
create policy "read own projects" on public.projects
for select using (auth.uid() = owner_id);
-- Users can create projects only for themselves.
create policy "insert own projects" on public.projects
for insert with check (auth.uid() = owner_id);
-- Users can update and delete only their own projects.
create policy "update own projects" on public.projects
for update using (auth.uid() = owner_id) with check (auth.uid() = owner_id);
create policy "delete own projects" on public.projects
for delete using (auth.uid() = owner_id);
Then test it the way an attacker would. Sign in as user A, copy a request from the browser's network panel, change the ID to one of user B's rows, and replay it. Try it again logged out. If anything comes back, the policy is wrong.
Two related rules matter just as much:
- Never ship the Supabase service role key or Firebase admin credentials to the browser. They bypass every rule.
- Do not trust IDs from the client. Derive the user from the session on the server, not from a
userIdfield the browser sends.
Step 4: Move authorization to the server
AI-generated UIs often "secure" features by hiding them. The admin button only renders for admins, the delete option only shows on your own items. That is good user experience and no security at all, because anyone can call the API directly.
Every API route, server action and database call must answer two questions on the server: who is this, and are they allowed to do this to this specific record? A small helper keeps the check consistent:
// lib/authz.ts: one place that decides ownership and roles
import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
export class ForbiddenError extends Error {}
export async function requireProjectAccess(projectId: string, need: 'read' | 'write') {
const session = await getSession();
if (!session) throw new ForbiddenError('Not signed in');
const membership = await db.projectMember.findUnique({
where: { projectId_userId: { projectId, userId: session.userId } },
});
if (!membership) throw new ForbiddenError('No access to this project');
if (need === 'write' && membership.role === 'viewer')
throw new ForbiddenError('Read-only access');
return { session, membership };
}
// In a server action or route: check first, then act.
export async function deleteTask(projectId: string, taskId: string) {
await requireProjectAccess(projectId, 'write');
await db.task.delete({ where: { id: taskId, projectId } }); // scope by project too
}
Notice the projectId in the delete query. Checking access to project A and then deleting a task by ID alone would let a user delete tasks in project B. Scoping every query by the parent resource closes that gap. Our secure multi-tenant API guide goes deeper on this pattern.
Step 5: Validate every input on the server
Browser-side validation helps users fill forms correctly. It does nothing against someone sending requests directly. Validate on the server with a schema, reject anything that does not match, and cap sizes:
- Types and formats: emails, IDs, dates and enums match what you expect.
- Lengths: text fields have maximums, so nobody stores a 50 MB string or sends a giant prompt to your AI bill.
- Allowed values: roles, statuses and plan names come from a fixed list, never free text.
- Files: check type and size on the server, store outside the web root, and never trust the file name.
Libraries such as Zod make this short, as the route handler in Step 2 showed. When AI features take user input, also treat the model's output as untrusted. Escape it before rendering, and never let it run database queries or shell commands without strict checks.
Step 6: Add the security basics AI tools skip
A handful of standard protections are missing from most vibe-coded apps because nobody prompted for them:
- Security headers: a content security policy,
X-Content-Type-Options, a frame policy and HSTS. - Rate limiting: on login, signup, password reset, contact forms and every endpoint that costs money.
- CSRF protection: for cookie-based sessions that accept form posts from other origins.
- Dependency hygiene: remove unused packages and run
npm auditor an equivalent in CI. - Bot protection: a challenge on public forms that send email or create accounts.
In Next.js, headers can be set in one place:
// next.config.ts: baseline security headers for every route
import type { NextConfig } from 'next';
const securityHeaders = [
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
];
const config: NextConfig = {
async headers() {
return [{ source: '/:path*', headers: securityHeaders }];
},
};
export default config;
Add a content security policy after you have listed the scripts and domains the app really uses, and test it in report-only mode first, because a strict policy can break third-party widgets. For API-side protections such as tiered rate limits, see securing Node.js APIs in production.
Step 7: Add tests where they protect the most
You do not need 90 percent coverage to ship safely. You need a few tests on the flows that make money or hold data, run on every change. Start with end-to-end smoke tests for signup, login, the core action and payment, then add tests that prove one user cannot access another's data.
// e2e/access.spec.ts: the test that catches the most dangerous regression
import { test, expect } from '@playwright/test';
test("a user cannot read another user's project", async ({ browser }) => {
const alice = await browser.newContext({ storageState: 'e2e/.auth/alice.json' });
const bob = await browser.newContext({ storageState: 'e2e/.auth/bob.json' });
const created = await alice.request.post('/api/projects', { data: { name: 'Private plan' } });
const { id } = await created.json();
const stolen = await bob.request.get(`/api/projects/${id}`);
expect([403, 404]).toContain(stolen.status());
});
test('signup to first project works end to end', async ({ page }) => {
await page.goto('/signup');
await page.getByLabel('Email').fill(`test+${Date.now()}@example.com`);
await page.getByLabel('Password').fill('a-long-test-password-123');
await page.getByRole('button', { name: 'Create account' }).click();
await page.getByRole('button', { name: 'New project' }).click();
await expect(page.getByText('Untitled project')).toBeVisible();
});
These tests matter even more when an AI keeps editing the code. They turn "the AI accidentally removed the ownership check" from a silent production leak into a failing build. Our testing and QA services can set up this safety net if your team has none.
Step 8: Make errors visible
Vibe-coded apps often fail silently. A promise rejects, the page goes blank, and the only signal is users leaving. Before launch, add:
- Error tracking in the browser and on the server, with alerts for new error types.
- Uptime checks on the homepage, login and the core API.
- Structured server logs with request IDs, but without passwords, tokens or full personal data.
- Basic product analytics on the core funnel, so you can see where people drop off.
- Cost alerts on AI, database and email providers, so abuse shows up as an alert rather than a bill.
Visibility also makes later fixes faster. When something breaks, you see which release introduced it and which users were affected.
Step 9: Deploy with a safety net
The last gap is how changes reach production. Prompting a fix and pushing straight to the live site works until a fix breaks something else. Set up:
- A staging environment with its own database, never a copy of production personal data.
- CI that runs on every pull request: type checks, lint, secret scanning, tests and a build.
- Preview deployments so you can click through a change before it goes live.
- Database migrations in code, reviewed like any other change, never edited by hand in the dashboard.
- One-click rollback to the previous release.
- Backups you have restored at least once, so you know they work.
Fix, refactor or rewrite?
Founders often ask whether they should throw the vibe-coded app away and start again. Usually, no. Use this table to decide:
| Situation | Recommendation |
|---|---|
| Works for users, but security and tests are missing | Harden in place: one to three week sprint |
| Core flows work, but some modules are tangled and slow to change | Harden first, then refactor the worst modules one at a time |
| Data model is wrong at the root (for example, no concept of teams in a team product) | Harden now, plan a staged migration of the data model |
| Nothing works reliably and there are no real users yet | A focused rebuild may be cheaper, reusing UI and copy |
| Stack cannot do what the business needs (for example, offline mobile on a web-only tool) | Rebuild the affected part on the right stack |
Rewrites feel clean but carry real risk: they take longer than planned, freeze feature work and introduce new bugs. Hardening keeps the product live and earning while it improves. Our MVP rescue blueprint covers the decision in more depth.
Common mistakes during hardening
- Fixing features before leaks. A new feature on an app with an exposed service key just adds more exposed data.
- Deleting a leaked key from code without rotating it. It is still in git history and possibly already copied.
- Turning on RLS without testing. A wrong policy can lock out real users or still leak data.
- Asking the AI to "make it secure". Vague prompts produce vague changes. Ask for specific fixes and review them.
- Big-bang refactors. Change one area at a time behind tests, so you can see what broke.
- Hiding errors with try and catch. Swallowing exceptions makes the app look stable while data quietly goes wrong.
- Skipping the boring parts. Backups, rollbacks and alerts feel optional until the first outage.
Keep building with AI, safely
Hardening is not the end of AI-assisted development. Once the guardrails exist, AI tools become safer and faster, because mistakes are caught automatically. A few habits help:
- Give the AI a project rules file describing your auth helper, validation library and folder structure, so new code follows the same patterns.
- Ask for small, reviewable changes rather than whole features in one prompt.
- Read every diff that touches auth, payments, data access or environment variables.
- Let CI, not your memory, decide whether a change is safe to merge.
Production checklist
- All exposed keys are rotated and moved server-side; secret scanning runs in CI.
- No service role or admin credentials exist in frontend code or public variables.
- Row-level security is enabled on every table, with policies tested by a second user.
- Every API route and server action checks the session and resource ownership on the server.
- All input is validated with a schema and size limits on the server.
- Expensive and sensitive endpoints are rate limited.
- Security headers are set; a content security policy is tested in report-only mode first.
- End-to-end tests cover signup, login, the core action, payment and cross-user access.
- Error tracking, uptime checks and cost alerts are live with named owners.
- Staging, CI, preview deployments, migrations in code and one-click rollback are in place.
- Backups are scheduled and a restore has been tested.
Conclusion and next steps
Vibe coding gets products to market faster than ever, and that is worth keeping. What it does not do on its own is prepare an app for real users, real data and real attackers. The good news is that the gaps are predictable, and most of them close in a short, ordered sprint: stop the leaks, lock down data, check authorization on the server, validate input, then add tests, monitoring and safe deployment.
Start with the audit in Step 1 today. If it turns up exposed keys or open tables, fix those before anything else, even before your next feature.
If you would rather have experienced engineers do it, our project rescue and takeover team hardens AI-built apps without stopping your roadmap, and our software audit service gives you a prioritised findings report first. Send us your app and we will tell you honestly whether it needs a hardening sprint, a refactor or a rebuild.
Sources
- Veracode: GenAI Code Security Report
- Supabase Docs: Row Level Security
- Next.js Docs: Environment variables
- OWASP Top 10
- Gitleaks on GitHub
- Redwerk: Vibe code audit, 10 critical checks before you launch
Frequently Asked Questions
Is a vibe-coded app safe to launch?
It can be, after a production review. Out of the box, AI-built apps often have exposed keys, open database rules and missing server-side checks. Audit secrets, data access, authorization and input validation before real users and real data arrive.
What is the most common security problem in vibe-coded apps?
Data exposure: either secret keys shipped to the browser, or databases such as Supabase and Firebase with row-level security disabled or overly permissive rules, which lets anyone read or change other users' data.
Do I need to rewrite my Lovable or Bolt app?
Usually not. If the app works for users, a hardening sprint of one to three weeks typically fixes the security, testing and deployment gaps. Rewrites make sense mainly when the data model is fundamentally wrong or the stack cannot meet the requirements.
How long does it take to make a vibe-coded app production ready?
For a typical MVP, the critical fixes for secrets, data access and authorization take a few days. Adding validation, tests, monitoring and a safe deployment pipeline brings the total to one to three weeks, depending on size.
Can I keep using AI tools after hardening?
Yes, and they become safer to use. With tests, secret scanning and CI in place, mistakes the AI introduces are caught before they reach production. Review every change that touches authentication, payments or data access.
How do I check if my Supabase database is exposed?
Sign in as one user, copy an API request from the browser network panel, change the record ID to another user's, and replay it, then try again while logged out. If any data comes back, row-level security is missing or a policy is too broad.
