← All guides

How to Prevent IDOR in Next.js and Supabase Apps (Users Seeing Other Users' Data)

Updated 2026-11-05

Short answer: IDOR (insecure direct object reference) happens when your app loads or changes a record by an ID from the request, such as /api/invoices/123, without checking that the signed-in user owns it. Anyone can change the ID and read or edit someone else's data. Fix it by taking the user's identity from the server session (never from the request body or URL), scoping every query with that user ID (where id = ? and user_id = ?), returning 404 when nothing matches, and, on Supabase, enforcing ownership with Row Level Security so a missed check in code can't leak data.

IDOR is one of the most common bugs in AI-built apps because the code looks correct. The page only shows a user their own links, so it feels safe. But the API behind it will happily return any record you ask for. Attackers don't use your UI; they call your API with curl and count upward through IDs.

What an IDOR bug looks like

Here's a typical Next.js route handler generated by an AI tool:

// app/api/invoices/[id]/route.ts  (VULNERABLE)
import { db } from "@/lib/db";

export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const invoice = await db.invoice.findUnique({ where: { id } });
  if (!invoice) return Response.json({ error: "Not found" }, { status: 404 });
  return Response.json(invoice);
}

There's no authentication at all here, but adding a login check alone doesn't fix it:

// Still vulnerable: checks that someone is logged in, not that they own the invoice
const session = await auth();
if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });
const invoice = await db.invoice.findUnique({ where: { id } });

Any logged-in user can still read every invoice. Authentication answers "who are you?". IDOR is about authorization: "are you allowed to touch this specific record?"

The fix: scope every query to the current user

Put the owner check inside the query itself, using the user ID from the session:

// app/api/invoices/[id]/route.ts  (FIXED)
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";

export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await auth();
  if (!session?.user?.id) return Response.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const invoice = await db.invoice.findFirst({
    where: { id, userId: session.user.id },
  });

  // Same response whether it doesn't exist or belongs to someone else
  if (!invoice) return Response.json({ error: "Not found" }, { status: 404 });
  return Response.json(invoice);
}

Three details matter:

  1. The user ID comes from the session, not from req.json(), a query string or a header. If the client can send userId, the client can lie about it.
  2. The check is part of the query, not a separate if (invoice.userId !== session.user.id) that someone later deletes or forgets on the next route. Both work, but query scoping is harder to get wrong.
  3. Return 404, not 403, for records the user can't access. A 403 confirms the record exists, which helps someone enumerating IDs.

Don't forget updates and deletes

Read endpoints get reviewed. Write endpoints often don't, and they're worse, because an attacker can modify or delete other people's data:

// VULNERABLE: deletes any project by ID
await db.project.delete({ where: { id } });

// FIXED: only deletes if the current user owns it
const result = await db.project.deleteMany({
  where: { id, ownerId: session.user.id },
});
if (result.count === 0) return Response.json({ error: "Not found" }, { status: 404 });

The same goes for updates. Also watch for "mass assignment": if you pass the whole request body into an update, a user can send { "ownerId": "someone-else" } and move a record into another account. Pick the allowed fields explicitly:

const body = await req.json();
await db.project.updateMany({
  where: { id, ownerId: session.user.id },
  data: { name: String(body.name ?? "").slice(0, 200) }, // only fields users may change
});

Server actions have the same problem

Next.js server actions are public HTTP endpoints. Anyone can call them with any arguments, not just the ones your form sends. This is a common IDOR:

"use server";
// VULNERABLE: trusts the id argument
export async function archiveNote(noteId: string) {
  await db.note.update({ where: { id: noteId }, data: { archived: true } });
}

Fix it the same way, by loading the session inside the action and scoping the write:

"use server";
export async function archiveNote(noteId: string) {
  const session = await auth();
  if (!session?.user?.id) throw new Error("Unauthorized");
  await db.note.updateMany({
    where: { id: noteId, userId: session.user.id },
    data: { archived: true },
  });
}

More on this in Next.js server actions security.

On Supabase, enforce ownership with RLS

If your app talks to Supabase from the browser (most Lovable and Bolt apps do), there's no API route to add a check to. The browser queries the database directly with the anon key, so the only thing preventing IDOR is Row Level Security.

Without RLS, this works for anyone who opens dev tools:

// Any visitor can run this with your public anon key
const { data } = await supabase.from("invoices").select("*");

Turn on RLS and add policies that tie rows to auth.uid():

alter table public.invoices enable row level security;

create policy "Users read own invoices"
  on public.invoices for select
  to authenticated
  using ( (select auth.uid()) = user_id );

create policy "Users update own invoices"
  on public.invoices for update
  to authenticated
  using ( (select auth.uid()) = user_id )
  with check ( (select auth.uid()) = user_id );

create policy "Users delete own invoices"
  on public.invoices for delete
  to authenticated
  using ( (select auth.uid()) = user_id );

The with check clause on update is what stops a user from changing user_id to move a row into someone else's account. For a full walkthrough, see the Supabase RLS checklist. If inserts start failing after you enable RLS, see fixing "new row violates row-level security policy".

Two Supabase specific traps:

Storage has the same issue. A file path like invoices/123.pdf in a public or loosely scoped bucket is an IDOR waiting to happen. See Supabase Storage bucket security.

Teams and shared records

Not every record has a single owner. For workspaces or teams, check membership instead of ownership:

create policy "Members read team documents"
  on public.documents for select
  to authenticated
  using (
    exists (
      select 1 from public.team_members m
      where m.team_id = documents.team_id
        and m.user_id = (select auth.uid())
    )
  );

In application code, the equivalent is joining through the membership table in the same query, rather than trusting a teamId the client sends.

Random IDs are not a fix

Switching from 1, 2, 3 to UUIDs makes guessing harder, but IDs leak all the time: in URLs people share, in logs, in browser history, in API responses that list related records, and in emails. Treat UUIDs as a nice extra, never as access control. The ownership check is the fix.

How to test your app for IDOR

You don't need special tools. Do this before launch:

  1. Create two accounts, A and B, in two different browsers.
  2. As A, create a record and note its ID from the URL or network tab.
  3. As B, request that ID directly: open the URL, or replay the API request in dev tools or with curl using B's cookie.
  4. Try it for every method: GET, PATCH or PUT, DELETE, and every server action.
  5. Try it logged out, too.

Every one of those should return 404 or 401, never A's data. Then search your code for queries that filter only by id, such as findUnique({ where: { id } }), .eq("id", id) with a service role client, or WHERE id = $1 with no user condition. Each one needs a second condition or an RLS policy behind it.

Related guides

Get an automated check

PreflightPR reviews AI-built apps for missing ownership checks, unprotected API routes and server actions, missing Supabase RLS, leaked keys and other launch blockers. Run a free scan on a public repo for a launch score and a prioritized fix list, or install the PreflightPR GitHub App to catch new IDOR bugs in every pull request before they merge.

Check your repo in about a minute

Paste a public GitHub URL and get a free launch score.

Run a free scan

More guides