IDOR Is Not a Bug You Patch, It's a Boundary You Design: Object-Level Authorization in Next.js
IDOR Is Not a Bug You Patch, It's a Boundary You Design
The short answer: An IDOR (Insecure Direct Object Reference) happens when an app exposes a real database identifier — an order ID, invoice number, or account ID — in a URL or request, then returns that record without checking whether the caller owns it. The fix is not to make IDs harder to guess; it is to move authorization into a fail-closed, server-side data-access boundary that every untrusted caller must pass through. In Next.js App Router, that means never calling an unscoped helper such asgetOrderById()from a page or a'use server'action. Expose only principal-scoped accessors likegetOrderForPublicView(id, key)andgetOrderForCustomer(id, customerId)instead.
It started with a number.
A checkout confirmation page, a "retry payment" screen, and a customer-facing status poller all accepted an integer from the URL, looked it up with a privileged server-side credential, and rendered the result. The integer was an order ID. It incremented by one for every purchase.
Within an afternoon, anyone could walk that integer backward and forward and read other people's orders in full: names, street addresses, email addresses, phone numbers, order totals — and, on one especially careless page, the payment URL that carried the very secret used to protect every other order page.
Nobody had "hacked" anything. There was no broken login, no stolen session, no injection payload. Every request was well-formed and every query succeeded. The application simply answered a question it was never supposed to answer: "show me record N."
That is an Insecure Direct Object Reference (IDOR), and it is the most common serious vulnerability in modern web apps — because it is rarely a bug in a line of code. It is a missing boundary.
What is an IDOR? (And why "BOLA" is the same bug)
An Insecure Direct Object Reference (IDOR) is an authorization flaw in which an application uses a client-supplied identifier to look up a record and returns it without verifying that the requester is entitled to that specific object. The reference is "direct" because it is the real primary key, not an opaque token that was validated first.
The OWASP API Security Top 10 calls the same class of flaw Broken Object Level Authorization (BOLA) and ranks it as the number one API risk. MITRE catalogs it as CWE-639: Authorization Bypass Through User-Controlled Key. The names differ; the root cause is identical: the server trusted an object reference it should have verified.
In its most dangerous form, the vulnerable path is three lines long:
// 1. A reusable, privileged data-layer helper — correct for trusted internal tooling
export async function getOrderById(id: number) {
return db.query('SELECT * FROM orders WHERE id = ?', [id]);
}
// 2. A public page passes a client-controlled id straight into it
const order = await getOrderById(Number(params.id));
// 3. A "private-looking" server action does the same
'use server';
export async function fetchOrderAction(orderId: number) {
return getOrderById(orderId);
}1. The three lines that caused it
The shape of the failure is almost always the same. Somewhere there is an accessor that knows how to fetch a record by ID, and it is a good, reusable accessor. The database helper above is not wrong — it is the right primitive for a trusted admin context. The mistake is using a privileged, unscoped primitive at a trust boundary and assuming every caller is benign.
Put those three calls together and you have built a self-service PII export, paginated by an integer you can enumerate with a for loop. The page and the server action are the trust boundaries; the helper itself is just a tool being used in the wrong place.
2. Why "just check that the user is logged in" is not the fix
The first instinct is to add a session check: if there is a cookie, render the page. That closes one door and leaves the real one wide open.
Authentication answers "who is calling?" Authorization answers "is this caller allowed to touch this specific object?" Those are different questions. A logged-in customer is authenticated, but that does not entitle them to order #1042 just because they guessed the number. Being signed in is not the same as being the owner.
Two more tempting shortcuts fail for the same reason:
- Client-side checks. Hiding a button or gating a component in the browser is cosmetic. The network request is the real interface, and an attacker does not use your UI.
- Opaque IDs. Swapping integers for UUIDs is defense in depth, not a fix. It raises the cost of enumeration; it does not establish a boundary. A leaked or predicted identifier is still a bypass.
The only durable fix is server-side, object-level authorization at the data-access choke point.
3. The anatomy of a correct boundary
A principal engineer does not ask "how do I stop this one request?" They design an accessor that makes the unsafe call structurally impossible. Four properties matter.
Property 1: Fail closed, and fail uniformly
The public accessor must return the same result for a missing order, a missing key, and a wrong key. If a wrong key produced a different response than a missing order, an attacker could use that difference to enumerate which IDs exist — even without reading them. Indistinguishability is a security property, not an ergonomics nicety.
export async function getOrderForPublicView(id, providedKey) {
if (!Number.isFinite(id) || id <= 0) return null;
if (!providedKey) return null;
const order = await getOrderById(id);
if (!order) return null; // same `null` as a wrong key
if (!keysMatch(order.orderKey, providedKey)) return null;
return order;
}Every early exit returns null. The caller cannot learn whether the record exists, which key was wrong, or whether the input was malformed.
Property 2: Compare secrets in constant time
Order IDs are sequential, so an attacker can guess them cheaply — which makes them exactly the attacker who can afford a timing oracle. A naive === on a secret short-circuits at the first mismatched byte, so response time leaks how much of the prefix was correct.
import { timingSafeEqual } from 'node:crypto';
function keysMatch(a, b) {
if (!a || !b) return false;
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length !== bufB.length) return false; // timingSafeEqual throws here
return timingSafeEqual(bufA, bufB);
}Fixed-length secrets mean the length check itself reveals nothing useful.
Property 3: Return the smallest possible projection
The status poller needed exactly one field: the order's status. The old server action returned the entire order — billing address, email, phone. A boundary should return the least data that satisfies the caller:
'use server';
export async function fetchOrderStatusAction(id, key) {
const order = await getOrderForPublicView(id, key);
return order ? { status: order.status } : null;
}Even a perfectly authorized caller should not receive fields it did not ask for. Least privilege applies to response shapes, not just to endpoints.
Property 4: Name the accessor by the principal, not the table
createOrder, getOrderById, updateOrder are data-layer names; they describe mechanics. The names that protect you describe trust: getOrderForPublicView(id, key) and getOrderForCustomer(id, customerId). When the only functions a page can import are the principal-scoped ones, the unguarded primitive stops being reachable from untrusted code by construction — keep it exported only to the scoped wrappers built on top of it.
4. Server actions are public endpoints
This surprises people. A 'use server' function is compiled into an endpoint whose action ID ships in the client bundle. Anyone who can load your page can obtain that ID and invoke the action directly with arbitrary arguments. A server action is not a private function call; it is a POST route with a friendly API.
Treat every server action as unauthenticated until proven otherwise, and authorize inside it, against the object, on the server. Never let the client supply the identity or the authorization result — supply only the claimed object and the claimed secret, and verify both server-side.
5. Guests, owners, and the customer_id: 0 trap
There are two legitimate ways to reach an order, and they need different checks:
- Guest checkout: no account exists. Access is granted by the high-entropy key embedded in the confirmation link. Pair it with the order ID and check it in constant time.
- Registered customer: access is granted by ownership — the authenticated account's ID must match the order's customer ID.
Do not collapse these into one check. Guest orders typically carry a sentinel customer ID (often 0) that must never satisfy an ownership comparison. A single accessor that rejects non-positive customer IDs handles this cleanly:
if (Number(order.customerId) !== Number(customerId)) return null;A signed-in user reading their own order is the happy path. A signed-in user reading someone else's order is the same vulnerability as the guest case, just with a valid session attached.
6. Make stale callers fail loudly
When replacing an unsafe action, resist the urge to keep the old name and signature. If fetchOrderAction(id) keeps existing and quietly starts returning null, every caller that was not updated keeps compiling and keeps believing it works — you have converted a security bug into a silent functional bug.
Rename it to fetchOrderStatusAction(id, key). Now any caller still using the old argument list fails the build. A deliberate breaking change at a trust boundary is a feature: it forces an audit of every call site. In security-critical refactors, a compiler error is cheap; a silent null is not.
7. Defense in depth: the full picture
| Layer | Unguarded Accessor | Hardened Boundary |
|---|---|---|
| Identifier | Sequential, enumerable ID | ID paired with a high-entropy key |
| Comparison | === on the secret | Constant-time timingSafeEqual |
| Failure mode | Distinct errors per case | Uniform null; no existence oracle |
| Return value | Full order + PII + payment URL | Least-privilege projection (status only) |
| Server action | 'use server' treated as private | Authorized inside, against the object |
| Guest vs owner | One ambiguous check | Separate key and ownership accessors |
| Refactor safety | Same signature, silent null | Rename; stale callers fail the build |
The database helper stays useful for trusted internal tooling. What changes is that untrusted code can no longer reach it.
How to eliminate IDOR in Next.js: a 5-step checklist
- Inventory your trust boundaries. List every page, route handler, and
'use server'action that accepts a client-supplied identifier. Flag any that pass it into an unscoped data-layer helper. - Consolidate behind principal-scoped accessors. Replace direct
getOrderById(id)calls withgetOrderForPublicView(id, key)for unauthenticated viewers andgetOrderForCustomer(id, customerId)for signed-in ones. Keep the raw helper reachable only from those wrappers. - Fail closed and uniformly. Return the same
nullfor every rejection path. Never let a response reveal whether an object exists. - Compare secrets in constant time. Use
timingSafeEqualfor order keys and any other bearer secret, especially when object IDs are enumerable. - Project the minimum and rename the old action. Return only the fields the caller needs, and rename the unsafe action so stale call sites fail the build instead of silently returning
null.
Frequently asked questions
Is changing IDs to UUIDs enough to stop IDOR? No. UUIDs only make enumeration harder; they authorize nothing. If a leaked or guessed identifier is still accepted without an ownership check, the vulnerability remains.
Are Next.js server actions private? No. They compile to endpoints whose action IDs are present in the client bundle. Authorize inside every action, against the object.
Does requiring a login fix IDOR? No. Authentication is not authorization. A logged-in user must still be checked as the owner of the specific object they request.
Why does constant-time comparison matter? Because a plain === leaks prefix information through response timing. With sequential, guessable IDs, that small leak is enough for an attacker to reconstruct a secret byte by byte.
What is the difference between IDOR and BOLA? They are the same flaw. IDOR is the classic web term; BOLA is the OWASP API Security Top 10 term (ranked #1). MITRE calls it CWE-639.
Key takeaways
- IDOR is a boundary problem, not a single bad line — fix the design, not just the request.
- Authorization happens on the server, against the object, never in the browser.
- Fail closed and uniformly so "not found" and "not allowed" are indistinguishable.
- Compare secrets in constant time when IDs are enumerable.
- Return the smallest projection that satisfies the caller.
- Treat server actions as public endpoints.
- Separate guest-by-key from owner-by-identity, and never let a sentinel ID satisfy ownership.
- Rename unsafe actions so stale callers fail loudly.
Summary
Ship the boundary and the entire class of bug disappears — not just the one request that triggered the ticket. When the only data-access functions untrusted code can import are the ones named for the principal it is acting as, an unguarded read of someone else's record stops being merely discouraged and becomes structurally impossible.
References
- OWASP API Security Top 10 — API1: Broken Object Level Authorization (BOLA).
- MITRE CWE-639 — Authorization Bypass Through User-Controlled Key.
- Node.js
node:cryptodocumentation —timingSafeEqual. - Next.js documentation — Server Actions and Server Components security model.