How to Stop AI from Vibe-Coding Your Next.js App into a Mess
AI coding tools write working code fast. Left alone, they also build an app nobody can safely change a few months later.
The tests pass and the features ship. The mess shows up later: a small change breaks three screens, and each fix costs more than the last.
This is not about AI being bad at code. It is very good at code, and it does not care about structure unless you tell it to.
A real case: what one audit found
I audited O Sequencer, an outreach app built fast with AI help. It had 73 route files: the parts of the server that answer the screens. The audit found 11 kinds of structural problem. In plain words:
- Business rules buried in the request code. The rules about what the app does sat inside the code that answers web requests, tied to sign-in and payments. They could not be reused, and testing them was expensive.
- One feature, three ways in. The same data was reached three different ways, so permission checks were repeated and drifted apart.
- No single way to check input. Only 18 of the 73 route files used the shared error helper. 49 read the raw request and checked fields by hand. Different errors, different answers.
- Screens that knew too much. Pages knew server addresses and request details, so a server change rippled into many screens.
- A hidden superuser, and a safety check that switched itself off. One setting created a hidden all-access user. Rate limiting turned itself off when one service was missing: open, not closed.
- Very few tests. Core code called the payment, AI and sign-in services directly, so tests were expensive to write, and few existed.
None of it came from one bad decision. Each shortcut made sense on its own. Nobody was watching the whole.
What changed: rules the AI reads on every task
Docs and README notes sit outside the coding loop. The AI reads the code around it, plus its instructions file: CLAUDE.md for Claude Code, a rules file for Cursor. So I wrote 15 short rules into that file. The AI follows them on every task, and a review can cite “rule 12” by number.
Some rules still drifted when they were only written down: code kept reaching past a module’s front door. So the important ones are now enforced by tests. One test reads every import in the app and fails on any shortcut.
A job-alert app I built runs under these rules. At its last full run, 1,987 tests passed, and about 1,600 quick ones run in about 12 seconds before every push. A full weekly review still found four real problems, like a payment change that could get lost if the payment provider sent it twice, and admin pages that did not check who was looking. The next day, 17 fixes shipped, 13 with a new test.
Rules don’t replace review. They give the review a list to check against. How I do that review: How I review AI-written code and The weekly review skill.
The 15 rules, in plain words
- Keep it simple (rules 1–3). Save what happened, not guesses. Use as few statuses as you can. No one-off special cases.
- Keep the layers apart (rules 4–9). The database, the business rules and the screens each keep their own shapes. Every input is checked. The code that answers requests only passes work along. Each feature has one way in.
- Make risky things safe (rules 10–13). No hidden shortcuts. If a safety check is down, refuse. Every change to data checks it belongs to the person making it. Two requests at once can’t both spend the same credit.
- One front door per part of the app (rules 14–15). Other code goes through one door, and the door runs the checks before anything is saved.
The code example for each rule is in the Technical tab.
What to ask a developer who uses AI tools
- Where are your rules written, so the AI reads them on every task? “In my head” or “in a doc” means the AI never sees them.
- Which rules does a test enforce? A written rule drifts. A test fails.
- How do you make sure one customer can never change another customer’s data?
- If a safety service is down, does the app refuse, or let everything through?
- What did your last review find, and what changed after?
You don’t need to read the code or learn the rules. Before building starts, I write the rules for your project into the AI’s instructions, and tests check the important ones on every push. Read the development approach.
The short version
AI tools write working code, not a tidy app. Write your rules where the AI reads them on every task, enforce the important ones with tests, and review against them.
What rules does the AI in your project follow today?
Stack: Next.js App Router, TypeScript, Postgres, Zod, Claude Code.
The audit, in developer terms
The post-mortem covered 73 route files. Its findings:
No application layer. Route handlers and page layouts owned all workflow orchestration. Business rules were coupled directly to NextRequest, NextResponse, Clerk, and Stripe — making reuse impossible and testing expensive.
Mixed data-access boundaries. The same feature was reached through raw SQL in one place, query helpers in another, and internal fetch() calls from client components in a third. No consistent boundary meant duplicated permission checks and diverging behavior between server and client.
Raw SQL bucket, not a repository layer. Query modules returned SELECT * results directly as domain types. Schema changes cascaded everywhere because persistence types, API types, and UI models were all the same thing.
Centralized but unprotected types. One massive src/types/index.ts spread across DB, API, and UI layers. The query layer relied on sql<T> and as unknown as for “type safety” — which is trust, not verification.
Inconsistent validation. 18 of 73 route files used the shared API error helper. 49 read request.json() directly and hand-validated fields. Different status codes, different error shapes, no contract.
UI coupled to transport. Client pages knew endpoint URLs, request shapes, and validation details. Backend changes rippled into many components.
Giant page shells. Route-local pages bundled UI rendering, state orchestration, and feature-specific business logic together in the same file.
No injectable ports. Core logic imported openai, Stripe, and Redis directly. Every unit test required framework mocking. The repo had minimal coverage for a large production app.
Security shortcuts. A MASTER_USER_ID env var created hidden superuser behavior. Rate limiting silently disabled itself when Redis was unavailable — fail-open, not fail-closed.
N+1 queries in request paths. Serial external API loops inside handlers. Latency that scaled linearly with dataset size.
Hardcoded product defaults. Onboarding campaigns and experiment defaults lived inside repository functions — policy welded to DB write paths.
Type erasure at every boundary. as unknown as, sql.json(... as never), bare sql calls cast with as number — the TypeScript was cosmetic.
What Goes in the Skill: 15 Rules With Teeth
The first version of this list had 14 rules, written from the audit’s findings. More projects shrank it to 13. Some rules merged into wider ones. Two new ones came from bugs the audit never caught: writes that skip the ownership check, and read-then-write races. A third came later, from code that kept reaching past a module’s front door into its private files. A fourth followed, from front doors that handed out saves without running the module’s checks.
These aren’t suggestions. They’re constraints the AI must satisfy before it calls a task done.
Rules 1–3: Model the Problem Simply
These go into CLAUDE.md as short written rules:
- 1. Store facts, not assumptions. Save what happened (
sent_at,replied_at), then work out the rest when you read it. A stored guess likestatus = 'follow_up_due'goes stale the moment the world changes. - 2. Prefer fewer states and simpler workflows. Every extra status is another branch to test and another way for rows to get stuck. If two states behave the same, merge them.
- 3. Delete special cases when the general model covers them. A hardcoded onboarding campaign inside a query function is a special case. Put defaults in config and let the normal path run them.
4. Keep Persistence, Domain, and API Shapes Separate
// REQUIRED — three distinct shapes with explicit mappers
type ContactRow = { id: string; email: string; created_at: string };
type Contact = { id: string; email: string; createdAt: Date };
type ContactResponse = { id: string; email: string; createdAt: string };
const toContact = (row: ContactRow): Contact => ({
id: row.id,
email: row.email,
createdAt: new Date(row.created_at),
});
// VIOLATION — returning raw DB row as API response
const contacts = await sql<Contact[]>`SELECT * FROM contacts`;
return NextResponse.json(contacts);
Rule encoded: Never return raw rows as domain types. Always map Row → Domain → ResponseDTO, one mapper per step.
5. Validate at Every Boundary
// REQUIRED — parse JSONB before use, even though the driver decoded it
const tagsSchema = z.array(z.string().min(1));
const tags = tagsSchema.parse(row.tags);
// VIOLATION — trusting decoded JSONB because it parsed
const tags = row.tags as string[];
Rule encoded: Request bodies, provider responses, and JSON columns all go through Zod. “It parsed” is not “it’s valid.”
6. Type Query Results Explicitly
// REQUIRED
type DashboardStatsRow = { active_contacts: number; pending_sends: number };
const [stats] = await sql<DashboardStatsRow[]>`
SELECT COUNT(*)::int AS active_contacts, SUM(pending)::int AS pending_sends
FROM contacts
`;
return { activeContacts: stats.active_contacts };
// VIOLATION — type erasure on scalar result
const [stats] = await sql`SELECT COUNT(*) ...`;
return { activeContacts: stats.active_contacts as number };
Rule encoded: Every query gets a named row type. No SELECT *, no as unknown as, no as number on a bare count.
7. Routes Only Coordinate
// REQUIRED pattern — route handlers do exactly this:
export async function POST(req: NextRequest) {
const input = contactSchema.parse(await req.json());
const result = await createContact(input);
return NextResponse.json(result);
}
// VIOLATION — never do this in a route:
export async function POST(req: NextRequest) {
const body = await req.json();
const existing = await db.query("SELECT * FROM contacts WHERE email = $1", [body.email]);
if (existing.length) return NextResponse.json({ error: "exists" }, { status: 409 });
await db.query("INSERT INTO contacts ...");
return NextResponse.json({ ok: true });
}
Rule encoded: No business logic or SQL in route handlers or layouts. Always: validate input → authorize → call a service → map result to HTTP.
8. Domain Logic Must Not Depend on Framework Singletons
// REQUIRED — inject interfaces
type Ports = {
clock: () => Date;
ai: { generate(prompt: string): Promise<string> };
payments: { charge(amount: number): Promise<string> };
};
export async function processOrder(ports: Ports, input: OrderInput) {
const now = ports.clock();
const chargeId = await ports.payments.charge(input.amount);
return { chargeId, processedAt: now };
}
// VIOLATION — SDK singleton imported directly in domain logic
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
Rule encoded: Domain logic never imports Clerk, Stripe, OpenAI, Redis, time, or randomness directly. Inject ports so core logic is unit-testable.
9. Use One Path per Feature
// REQUIRED — pick one boundary per feature
const contacts = await getContacts(); // direct server call
// VIOLATION — mixing fetch and direct DB for the same feature
const contacts = await fetch("/api/contacts").then(r => r.json());
const more = await db.query("SELECT * FROM contacts");
Rule encoded: One feature, one way in. Two paths mean two permission checks that drift apart.
10. Make Risky Behavior Explicit and Bounded
// REQUIRED — fail closed, cap the blast radius
if (!rateLimiterAvailable) {
return NextResponse.json({ error: "Service unavailable" }, { status: 503 });
}
const batch = pending.slice(0, MAX_SENDS_PER_RUN);
// VIOLATION — hidden superuser, silent fail-open, no cap
const userId = process.env.MASTER_USER_ID ?? session.userId;
if (!redis) return handler(); // silently skips rate limiting
for (const job of pending) await send(job);
Rule encoded: No env-var shortcuts for auth or safety. If a guard is down, reject. Anything that sends, spends, or deletes gets a hard limit.
11. Use One Validation and Error Style Everywhere
// REQUIRED
const parsed = contactSchema.safeParse(await req.json());
if (!parsed.success) {
return NextResponse.json(
{ error: "Invalid input", issues: parsed.error.issues },
{ status: 400 }
);
}
// VIOLATION
const body = await req.json();
if (!body.email || !body.name) {
return new Response("missing fields", { status: 400 });
}
Rule encoded: Always parse with Zod. Always return the same error shape: { error: string, issues?: ... }.
12. Every UPDATE and DELETE Carries an Ownership Predicate
// REQUIRED — ownership checked in the write itself
const result = await sql`
DELETE FROM contacts
WHERE id = ${contactId} AND user_id = ${userId}
`;
if (result.count === 0) throw new NotFoundError();
// VIOLATION — ownership checked earlier, write trusts the id
const contact = await getContact(contactId, userId);
await sql`DELETE FROM contacts WHERE id = ${contact.id}`;
Rule encoded: No mutation without re-checking ownership at the point of write. A check three calls up is not a check.
13. Read-Then-Write Runs in a Transaction With FOR UPDATE
// REQUIRED — lock the row, then decide
await sql.begin(async (tx) => {
const [credits] = await tx<CreditsRow[]>`
SELECT balance FROM credits WHERE user_id = ${userId} FOR UPDATE
`;
if (credits.balance < cost) throw new InsufficientCreditsError();
await tx`UPDATE credits SET balance = balance - ${cost} WHERE user_id = ${userId}`;
});
// VIOLATION — two requests both pass the check, both spend
const [credits] = await sql`SELECT balance FROM credits WHERE user_id = ${userId}`;
if (credits.balance >= cost) {
await sql`UPDATE credits SET balance = balance - ${cost} WHERE user_id = ${userId}`;
}
Rule encoded: No check-then-act outside a lock.
14. Other Code Reaches a Module Only Through Its Front Door
// REQUIRED — call the module's front door, its workflow file
import { listContacts } from "@/lib/modules/contacts/contacts.workflow";
const contacts = await listContacts(userId);
// VIOLATION — a page reaching straight into the module's database file
import { selectContacts } from "@/lib/modules/contacts/contacts.queries";
const contacts = await selectContacts(userId);
Rule encoded: Each module has one public door: its workflow file. Queries, rules and adapters stay private to the module. Type-only imports are fine, since they vanish at build. Rule 9 says one path per feature; this rule says which path.
Browser screens are the one catch. A workflow pulls in database code, so a screen can’t use it. Plain values and checks that both the screen and the server need, like a list of plan names or a max title length, live in a lib/shared/ folder that imports no module code.
Written down, this rule drifted: code kept reaching past the door. So it is now enforced by a test that reads every import and fails on any shortcut.
15. The Front Door Runs the Checks Before It Saves
// REQUIRED — the door runs the module's rules, then saves
export async function renameContact(userId: string, contactId: string, name: string) {
const cleanName = checkContactName(name); // from contacts.rules
return updateContactName(userId, contactId, cleanName); // from contacts.queries
}
// VIOLATION — the door hands out the raw save, so callers skip the rules
export { updateContactName } from "./contacts.queries";
Rule encoded: A workflow file never hands out a save (insert, update or delete) straight from its queries file. Each save goes through a door function that runs the module’s rules first. Reads may pass through. Rule 14 says everyone uses the door; this rule says the door checks before anything is saved.
How to Wire This Into Claude Code
The minimum viable version is a CLAUDE.md at your project root that lists these rules. Claude Code reads this file at the start of every session and applies the rules to every generation.
The section looks like this. Short lines, numbered, so a review can cite “rule 12” by number:
## Architecture Rules
1. Store facts, not assumptions.
2. Prefer fewer states and simpler workflows.
3. Delete special cases when the general model covers them.
4. Keep persistence, domain, and API shapes separate.
5. Validate at every boundary.
6. Type query results explicitly.
7. Routes only coordinate.
8. Domain logic must not depend on framework singletons.
9. Use one path per feature.
10. Make risky behavior explicit and bounded.
11. Use one validation and error style everywhere.
12. Every UPDATE/DELETE must include a user_id ownership predicate.
No mutation without re-validating ownership at the point of write.
13. Read-then-write sequences require a transaction with FOR UPDATE.
No check-then-act outside a lock.
14. Other code reaches a module only through its front door.
The front door is the module's workflow file.
15. The front door runs the checks before it saves.
A more robust version uses Claude Code’s skill system: a dedicated nextjs-arch-guard skill that runs as a pre-commit check against staged files. If any staged file contains a route-level DB import, a SELECT * return, or a raw request.json() without Zod — the skill fails before the code enters the codebase.
The key difference between documentation and a skill: documentation requires a human to remember it. A skill requires the AI to satisfy it before it calls anything done.
You can also add enforcement hooks in your project’s .claude/settings.json to run the arch-guard check automatically before every commit. The AI writes the code; the skill audits it; bad patterns never land.
More Posts
All posts
November 25, 2026
Why Your App Went Offline on Vercel's Free Plan (and How to Stay Under the Limits)
Vercel's free plan pauses every site on the account when one monthly limit runs out. What the limits mean in plain words, what uses them up, and the fixes, from a real case.
November 24, 2026
Why Your Project Starts With a Small Paid Step: Requirements and an Estimate Before the Build
A price given before the work is measured is a guess, and someone pays for it later. What a small paid first step gets you: written decisions, a cost range and a time range, and the choice to stop there.