IDOR: When Changing an ID in the URL Shows Someone Else's Data
IDOR (insecure direct object reference) is when your server looks up a record by the ID in the request and returns it without checking that it belongs to the caller. The user is logged in, so the auth check passes. They just ask for invoice 1042 instead of their own 1041. The fix is to put the owner into every query: where id = ? and user_id = ?.
On this page
This is the bug behind many "anyone could download any customer's documents" headlines. It needs no tools and no skill. It is also the access bug AI coding tools produce most reliably, because the generated code does what the prompt asked: "fetch the invoice by ID".
The vulnerable handler
// app/api/invoices/[id]/route.ts
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
const session = await auth();
if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });
const { id } = await params;
const invoice = await db.invoice.findUnique({ where: { id } });
return Response.json(invoice);
}
There is an auth check, so this passes a casual review. What is missing is the second question. Authentication answers "who are you?". Authorisation answers "is this yours?". The handler never asks.
Where it hides
GET /api/invoices/1042, the obvious one.PATCHandDELETEon the same path. Reads get tested; writes get forgotten.- IDs in the body or query string:
POST /api/export { "projectId": "..." }. - Nested resources:
/api/projects/7/members/3, where project 7 is checked and member 3 is not. - File downloads:
/api/files/abc/download. - Lists with a filter the client controls:
/api/orders?userId=55. - Server Actions and RPC functions that take an ID argument.
The two-account test
- Create users A and B. As B, create one of everything: a project, an invoice, an upload.
- Note B's IDs from the URL bar or network tab.
- Log in as A. Replay A's own requests with B's IDs:
curl -H "Cookie: $A_SESSION" https://yourapp.com/api/invoices/$B_INVOICE_ID
curl -X PATCH -H "Cookie: $A_SESSION" -H 'Content-Type: application/json' \
-d '{"status":"paid"}' https://yourapp.com/api/invoices/$B_INVOICE_ID
curl -X DELETE -H "Cookie: $A_SESSION" https://yourapp.com/api/invoices/$B_INVOICE_ID
Every one should fail. If any returns B's data or changes it, you have an IDOR.
The fix: ownership inside the query
const invoice = await db.invoice.findFirst({
where: { id, userId: session.user.id },
});
if (!invoice) {
return Response.json({ error: 'Not found' }, { status: 404 });
}
Putting the owner in the where clause is better than fetching first and comparing after. There is no window in which you hold a record you should not have, and no chance of forgetting the if.
Return 404, not 403. A 403 confirms the record exists, which lets someone map your ID space.
Updates and deletes use the same shape:
const result = await db.invoice.updateMany({
where: { id, userId: session.user.id },
data: { status },
});
if (result.count === 0) {
return Response.json({ error: 'Not found' }, { status: 404 });
}
For team-based apps the owner is an organisation, and the check goes through membership:
where: { id, org: { members: { some: { userId: session.user.id } } } }
UUIDs help less than you think
Switching from 1042 to 3f8a1c9e-... stops guessing. It does not stop IDOR. IDs leak through shared links, exported files, screenshots, referrer headers, logs and other API responses (a comment that includes its author's ID, for example). Random IDs are worth having. They are not an access check.
Make it hard to forget
One-off fixes get undone by the next feature. Three structural options, from lightest to strongest:
- Scoped helpers. No handler calls
db.invoicedirectly. They callinvoicesFor(session.user).find(id), which always adds the owner. - Tests. One test per resource: user A requests B's ID and expects 404. Run in CI.
- Database-level rules. With Postgres Row Level Security, the database refuses rows the caller does not own even when application code forgets. On Supabase this is the default model; see our post on Supabase RLS mistakes.
When you ask an AI assistant for a new endpoint, say it in the prompt: "scope every query to the current user and return 404 for records they do not own". It will follow the instruction. It rarely volunteers it.
Related: users who change fields instead of IDs, in the client sets the price, role or plan. IDOR is check 1 in our security checklist for vibe-coded apps. If you want the two-account test run across your whole API, with fixes, see our app rescue and security audit.
