Skip to main content
Home/Engineering Blog/The Vibe Coding Trap: 6 Flaws ...
AI SECURITY // FIELD GUIDE

The Vibe Coding Trap: 6 Flaws Hiding in Almost Every AI-Built MVP (and How to Find Them Yourself)

AI got you to a working product in days. Then every fix breaks something else, and nobody's sure what's safe to ship. Here's why that happens, a 15-minute self-audit you can run today, and the six flaws we find in nearly every AI-generated codebase we review.

THE PATTERNHappy Path OnlyWorks for honest users, breaks for curious ones
MOST COMMONClient TrustServer believes whatever the browser sends
SNEAKIESTSlopsquattingInstalling packages the AI invented
THE FIXOwn the BoundariesHumans review auth, data and money
HawkInspect Pro Engineering
•16 min read

You built a full SaaS product in a weekend with Cursor, v0, Bolt or Lovable. The UI is polished, sign-up works, payments go through. For the first time, the idea in your head is something people can actually click. That's genuinely remarkable, and we're not here to tell you AI coding was a mistake.

But we review a lot of AI-built codebases, and the same pattern shows up almost every time: the app works perfectly for honest users and falls apart for anyone who pokes at it. The flaws are rarely exotic. They're the same handful of mistakes, repeated, because the tools that wrote them optimise for code that runs, not code that holds.

Velocity without review is just a faster way to ship the same bugs. The good news: you can find most of them yourself in an afternoon.

1.Why It Works in the Demo and Breaks in Production

AI models are trained to produce the most plausible next piece of code for the request in front of them. "Make an endpoint that returns the user's invoices" gets you an endpoint that returns invoices. What it doesn't naturally ask is the question every security review starts with: what happens when someone sends a request I didn't expect?

  • No adversarial instinct. The code assumes the browser is honest: whatever user ID, price or role it sends is taken as true.
  • A narrow view. The model sees the file you're in, not the whole system. It doesn't know the other endpoint that skips the check, or that two requests can arrive at once.
  • Demo-shaped testing. You test by clicking through the app as yourself. Every flaw in this article is invisible from that position.

One large 2025 study by Veracode tested code from more than 100 language models and found that roughly 45% of the generated samples introduced a security flaw. That matches what we see in practice: not occasional mistakes, but a predictable blind spot.


2.The "Fix One Bug, Three More Appear" Loop

If you've been stuck for weeks on the last 10%, this is probably why. You describe a bug, the AI patches it, and something else breaks. You ask it to fix that, and the first bug quietly comes back. It isn't bad luck. It's structural:

  • Each fix is local. The model patches the code you showed it, unaware of the three other places that depend on the old behaviour.
  • Code only accumulates. AI tools add code far more readily than they remove it. After a few months there are often three slightly different versions of the same function, and a fix lands in only one.
  • Nothing tells you what broke. Without automated tests, the only signal is a user hitting the bug later. So every change is a gamble.
How to break the loop

Before asking for more fixes, pin down what "working" means: a handful of end-to-end tests for sign-up, login, checkout and your core feature. Then every AI change has a safety net, and you'll know within minutes whether it broke something. It's the single highest-leverage hour you can spend on an AI-built codebase.


3.The 15-Minute Self-Audit

You don't need to read every file to find the worst problems. Run these from your project folder. Each hit isn't automatically a bug, but each one is worth a careful look, and the sections below explain what to look for.

Read-only
self-audit.sh
# 1. Auth that decodes tokens without verifying them (section 5)
grep -rn "jwt.decode(" --include=*.ts --include=*.tsx --include=*.js .

# 2. Secrets shipped to every visitor's browser (section 7)
grep -rnE "(NEXT_PUBLIC|VITE|EXPO_PUBLIC)_[A-Z_]*(SECRET|PRIVATE|SERVICE_ROLE|OPENAI|ANTHROPIC)" .env* src app

# 3. Endpoints that take the user's identity from the request body (section 4)
grep -rnE "(userId|user_id|ownerId|role)" app/api src/app/api pages/api 2>/dev/null | grep -E "json\(\)|req\.body"

# 4. Writing the whole request body straight into the database (section 8)
grep -rnE "data: *(body|req\.body|input|values|payload)\b" --include=*.ts --include=*.js .

# 5. Known-vulnerable dependencies (section 9)
npm audit --omit=dev

Publishable keys meant for the browser (like Stripe's pk_… or Supabase's anon key) are fine in public variables; the anon key is only safe if your database rules are, which is section 6.


4.Flaw #1: Believing Whoever the Browser Says You Are

This is the flaw we find most often. The frontend sends the logged-in user's ID along with the request, and the server uses it:

Any user's data
app/api/invoices/route.ts
export async function POST(req: Request) {
  const { userId } = await req.json();       // whoever the browser claims to be
  const invoices = await prisma.invoice.findMany({ where: { userId } });
  return Response.json(invoices);
}

Open dev tools, change userId to someone else's, and you're reading their invoices. The same goes for /api/invoices/[id] routes that fetch by ID without checking the invoice belongs to the caller. Security people call it IDOR (insecure direct object reference); founders call it "the day a customer saw another customer's data".

Fixed
app/api/invoices/route.ts
export async function GET() {
  const session = await auth();                         // identity comes from the server session
  if (!session?.user) return new Response('Unauthorized', { status: 401 });

  const invoices = await prisma.invoice.findMany({
    where: { userId: session.user.id },                 // never from the request
  });
  return Response.json(invoices);
}
Server Actions are public endpoints too

In Next.js, every Server Action can be called directly with a POST request, whether or not the button that uses it is visible. Hiding the "Delete project" button from non-admins protects nothing. Each action needs its own session and permission check at the top.


5.Flaw #2: Auth That Doesn't Verify Anything

A classic AI-generated middleware that looks completely reasonable:

Broken authentication
middleware/auth.ts
export const verifyToken = (req, res, next) => {
  const token = req.headers.authorization;
  if (!token) return res.status(401).end();

  const decoded = jwt.decode(token);   // reads the token, never checks the signature
  if (decoded) {
    req.user = decoded;                // { id: 'any-id', role: 'admin' } works fine
    return next();
  }
  res.status(401).end();
};

jwt.decode just reads the token's contents. Anyone can write a token that says role: "admin", and this code believes it. Verification needs the secret and an explicit algorithm:

Fixed
middleware/auth.ts
const token = req.headers.authorization?.replace(/^Bearer /, '');
if (!token) return res.status(401).end();

try {
  req.user = jwt.verify(token, process.env.JWT_SECRET!, { algorithms: ['HS256'] });
  return next();
} catch {
  return res.status(401).end();          // bad signature, expired or malformed
}

The related mistake is frontend-only protection: a page that redirects to /login when there's no user, while the API routes behind it accept anyone. Redirects are a user-experience feature. Authorisation has to happen on the server, on every request.


6.Flaw #3: A Database Anyone Can Read

Supabase and Firebase let the browser talk to the database directly, which is exactly why AI builders love them. The safety of that design rests entirely on your security rules. With Supabase, a table without Row Level Security can be read (and often written) by anyone holding your public anon key, which is in your frontend for everyone to see. Several AI-built apps exposed user data exactly this way in 2025.

Test it yourself in ten seconds, using the URL and anon key from your own frontend:

Run on your project
check-rls.sh
# If this returns rows from a private table, anyone on the internet can read it
curl "https://YOUR-PROJECT.supabase.co/rest/v1/invoices?select=*" \
  -H "apikey: YOUR_ANON_KEY"
Fixed
rls.sql
-- 1. Turn RLS on for every table the browser can reach
alter table public.invoices enable row level security;

-- 2. Then allow only what each user should see
create policy "users read their own invoices"
  on public.invoices for select
  using (auth.uid() = user_id);

Supabase's Security Advisor in the dashboard flags tables without RLS. On Firebase, look for rules like allow read, write: if true;, a common "temporary" setting that never gets removed. And never put the Supabase service_role key in frontend code: it bypasses every rule.


7.Flaw #4: Secrets in the Bundle, Endpoints With No Limits

To make a feature work quickly, AI tools often call OpenAI (or Stripe, or an email API) straight from the browser, using a variable like NEXT_PUBLIC_OPENAI_API_KEY. Anything with that prefix is compiled into JavaScript every visitor downloads. Bots scrape public sites for exactly these keys, and a leaked AI key can run up a large bill before you notice.

Moving the call to a server route fixes the leak, but not the cost. An unauthenticated /api/generate endpoint with no limits is just a free AI proxy for the internet. Put expensive endpoints behind login and a per-user rate limit:

Rate limited
app/api/generate/route.ts
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, '1 m'),   // 10 generations per user per minute
});

export async function POST(req: Request) {
  const session = await auth();
  if (!session?.user) return new Response('Unauthorized', { status: 401 });

  const { success } = await ratelimit.limit(session.user.id);
  if (!success) return new Response('Too many requests', { status: 429 });

  // ...call the AI provider with a server-only key
}

Also set a hard monthly budget and usage alerts in every provider's dashboard. Rate limits catch abuse; budget caps catch everything else. If a key has ever been public, rotate it: deleting it from the code doesn't remove it from git history.


8.Flaw #5: "Save Whatever the User Sent"

Ask for a profile-update endpoint and you'll often get this:

Self-promotion to admin
app/api/profile/route.ts
const body = await req.json();
await prisma.user.update({
  where: { id: session.user.id },   // correct user...
  data: body,                       // ...but ANY field: { "role": "admin", "credits": 999999 }
});

The form only shows name and avatar, but the database happily accepts any column the request includes. This is called mass assignment, and it's how users quietly upgrade their own plan or role. Validate input with an explicit allow-list:

Fixed
app/api/profile/route.ts
import { z } from 'zod';

const ProfileUpdate = z.object({
  name: z.string().min(1).max(80),
  avatarUrl: z.string().url().optional(),
}).strict();                          // unknown fields like "role" are rejected

const data = ProfileUpdate.parse(await req.json());
await prisma.user.update({ where: { id: session.user.id }, data });

9.Flaw #6: Installing Packages That Don't Exist (Yet)

Language models sometimes recommend npm or PyPI packages that don't exist: a plausible name for a library that "should" exist. Researchers found these invented names are often repeated across prompts, which makes them predictable. Attackers register the predictable ones and fill them with malicious code. It's known as slopsquatting.

Because npm packages can run scripts during installation, simply running npm install on the wrong name can execute an attacker's code on your machine or in your CI, right where your environment variables and keys live.

Before installing anything an AI suggested

  • Check it's real and established: npm view <package> time.created repository.url. A package created last week, with no repository and few downloads, is a red flag.
  • Prefer packages you've heard of, or that the official docs of your framework recommend.
  • Commit your lockfile and review dependency changes in pull requests like any other code.
  • Run npm audit in CI, and consider --ignore-scripts when trying out an unfamiliar package.
The rest of the iceberg

The six flaws above are about trust. AI-built apps also tend to share deeper architectural problems that only show up under real traffic: unsigned payment webhooks (7 Stripe webhook mistakes), race conditions that double-sell (why Node.js apps double-sell) and database connections that collapse on serverless (Prisma on serverless).


10.Keep the Speed, Lose the Risk

None of this means you should stop using AI. It means being deliberate about which parts it owns. The teams we see shipping fast and safely follow a simple split:

A workflow that holds up

  • Let AI own the bulk: UI, boilerplate, CRUD screens, tests, refactors.
  • Have a human own the boundaries: authentication, who can see which data, anything that moves money, and infrastructure. Review every change that touches them.
  • Tests before more fixes: lock down critical flows first, then let AI iterate inside that safety net.
  • Ask the attacker's question: after generating an endpoint, prompt "how could a malicious user abuse this?" Models are surprisingly good at answering when asked directly.
  • Automate the boring checks: type-checking, linting, npm audit and secret scanning (for example gitleaks) on every pull request.

What an investor's CTO will check

If you're raising, technical due diligence will look at exactly these things. Better you find them first:

  • Every API route and server action checks the session and the user's permission on the server.
  • Customers' data is isolated: no endpoint returns another user's records, and database rules enforce it.
  • No secrets in the frontend bundle or in git history; leaked keys rotated.
  • Expensive endpoints are authenticated, rate limited and budget-capped.
  • Input is validated against an allow-list before it reaches the database.
  • Dependencies are real, maintained and audited; the lockfile is committed.
  • Payments, webhooks and concurrency are handled correctly (see the articles linked above).
  • Critical flows have automated tests, and production has backups and error monitoring.

AI got you to a product people can use, and that's the hard part done. Hardening it is a well-understood, finite job: usually days or weeks, not a rewrite. If you've been stuck in the fix-one-break-three loop, or due diligence is on the calendar, a senior review is the fastest way out.

Note on Organization Security:We never require full GitHub/GitLab organization admin access. A read-only invite to the specific repository and branch being audited is all that is required, keeping your broader infrastructure completely isolated.

Not sure which methodology fits your application?

We'll analyze your stack, endpoints, and repo requirements in a quick 10-minute triage.