Row-level data privacy

Ensure every customer sees only their own rows. Enforce ownership checks on the server, handle staff exceptions safely, and verify with two accounts.

What row-level data privacy actually means

Sign-in proves who is visiting, and roles prove what tier they hold (Member, Staff, or Admin). Neither stops Customer A from opening Customer B's invoice, booking, or intake form.

Row-level data privacy closes that gap. Before returning, editing, or deleting any record, your server verifies the signed-in caller owns that specific row — or holds an explicit staff, workspace, or admin exception.

Every production table should default to deny:

  • No rule means no access. Unless an endpoint proves the caller may see a row, the server returns zero bytes.
  • Browser filtering is cosmetic. Hiding other customers' rows in UI code still leaks their JSON in browser DevTools.
  • Session identity is authoritative. Always read session.user.id from the verified HTTP-only session cookie — never from a client-supplied user_id.

The four row-access models every app uses

Almost every table in a real business app fits cleanly into one of four row-access models. Naming the exact model per table when prompting ExaSpark eliminates ambiguous rules across routes.

Access modelWho can read rowsWho can create or edit rowsTypical tables
Public read, Admin writeAnyone (strictly published rows and public columns only)Admin onlyproducts, classes, blog_posts, public_reviews
Owner-only (Personal scope)Only the user where row.user_id === session.user.idSigned-in user (server stamps user_id = session.user.id)bookings, orders, saved_addresses, invoices, profiles
Workspace / Team scopeActive members of row.workspace_id verified via workspace_membersWorkspace members with permitted workspace role (admin, editor, member)projects, tasks, client_files, team_notes
Role-elevated exceptionRow owner, plus assigned Staff or global AdminOwner (within allowed states/fields) or Adminappointments, support_tickets, subscriptions, payouts

Why column projection matters alongside row privacy

Even when a row is legitimately public — such as a product review or community profile — not every column on that row or its linked users record should be public.

Always select explicit safe columns (display_name, avatar_url, rating, comment) on public queries so sensitive columns like email, phone, home_address, stripe_customer_id, or internal_staff_notes never leak in API responses.

How server-enforced rules work on every operation

Row-level privacy is not a single toggle — it must hold consistently across all five operations (LIST, READ ONE, CREATE, UPDATE, DELETE) plus exports and private file downloads. Missing even one route creates a hole.

text
TABLE: bookings (user_id, service_id, starts_at, status, price_cents, staff_notes)

OPERATION      SERVER POLICY RULE
-------------------------------------------------------------------------------------
LIST           If role == 'admin': allow all (paginated)
               If role == 'staff': filter WHERE assigned_staff_id = session.user.id
               If role == 'member': filter WHERE user_id = session.user.id

READ ONE       Fetch booking by :id; require owner OR assigned staff OR admin.
               Return 404 Not Found if unauthorized so callers cannot probe valid IDs.
               Strip `staff_notes` unless role IN ('staff', 'admin').

CREATE         Require signed-in user. Ignore any `user_id` or `price_cents` from body.
               Stamp user_id = session.user.id and compute price_cents from `services`.

UPDATE         Require owner OR admin. Whitelist editable fields by role:
               Member may only edit `customer_notes` or cancel >24h before `starts_at`.
               Never let Member overwrite `user_id`, `price_cents`, `status = 'paid'`,
               or `staff_notes`.

DELETE         Admin only (prefer setting status = 'canceled' or archived_at).

Notice two subtle production details in that blueprint:

  • Returning `404` on unauthorized single-row reads. Returning 403 Forbidden confirms that a guessed record ID exists, whereas returning 404 Not Found gives an attacker zero information about other customers' IDs.
  • Field whitelisting on writes. Checking row ownership prevents User A from editing User B's order, while whitelisting editable fields prevents User A from marking their own unpaid order as status = "paid" or setting price_cents = 0.

Five real-world leakage mistakes (and how to stop them)

When security audits uncover data leaks in newly launched apps, the cause is almost always one of these five patterns.

  • Securing the list endpoint, forgetting the detail endpoint (IDOR). /api/bookings filters by session.user.id, yet /api/bookings/:id fetches strictly by :id. Anyone who swaps an ID in the URL reads another customer's appointment.
  • Trusting a client-supplied `workspace_id` or `user_id`. Reading GET /api/projects?workspace_id=ws_other without checking workspace_members for (ws_other, session.user.id) exposes another company's projects immediately.
  • Unprotected CSV exports or PDF invoice links. Securing /account/invoices in the app while leaving /api/invoices/:id/pdf checking only "is the user signed in?" lets any member download another buyer's receipt.
  • Over-broad Staff or Admin exceptions. Granting Staff full access to billing settings, password logs, or unrelated locations instead of scoping Staff strictly to assigned rosters or queues widens the blast radius of any compromised staff login.
  • Stale access after removing a teammate. Deleting a user from workspace_members must block their access on the very next API request. Always check live membership rows on the server instead of caching permanent workspace lists inside long-lived tokens.

Testing row isolation with two Preview accounts

Never assume privacy rules work just because the happy path looks right. Use Preview — whose database and user accounts are completely isolated from Live — to run a five-minute adversarial check with two separate accounts.

  1. Create three accounts in Preview

    Register alice@example.com (Member), bob@example.com (Member), and one Admin account promoted in Cloud → Preview.

  2. Generate private records as Alice

    Sign in as Alice and create a booking, upload a private attachment, and open the booking detail URL. Copy the exact record ID and detail URL.

  3. Attack Alice's URLs while signed in as Bob

    Open an incognito window, sign in as Bob, and paste Alice's detail URL, PDF receipt URL, and edit/cancel routes directly into the address bar or DevTools console.

  4. Verify strict server rejection and zero leaks

    Confirm Bob receives 404 or 403, never sees Alice's name, email, or notes in Network responses, and cannot modify Alice's record.

  5. Confirm Staff and Admin exceptions explicitly

    Sign in as Admin (and Staff if used), confirm they see strictly their authorized scope, and confirm Member accounts remain blocked from /admin endpoints.

Starter prompt · App

Audit and enforce strict server-side row-level data privacy across every API route and database query. Use default-deny rules: Members may only list, view, or update records where `user_id === session.user.id` (returning 404 on unauthorized detail lookups), while workspace routes must verify active membership in `workspace_members` on every request. Never accept `user_id`, `role`, or `price_cents` from client payloads, whitelist editable fields on every PATCH route, strip private fields like `email`, `phone`, and `staff_notes` from public or non-staff responses, and apply the same ownership checks to private file download and PDF receipt routes.

Row privacy troubleshooting table

Use this diagnosis table if testing reveals either an unintended leak or an overly strict rule blocking legitimate users.

SymptomRoot causeFix
Bob can view Alice's booking by pasting her URLDetail route GET /api/bookings/:id lacked AND user_id = session.user.id (IDOR)Enforce ownership or Staff/Admin check on every :id route and return 404 on mismatch
Admin dashboard went blank after tightening ownership rulesQuery filtered unconditionally by user_id = session.user.id without an admin branchAdd explicit server-side role exception (role === 'admin') only on verified admin routes
Public reviews page exposes customer email addressesEndpoint returned SELECT * from joined users rows instead of explicit display columnsProject only display_name, avatar_url, and review fields on public routes
Removed team member still views workspace projectsServer read workspace IDs from a stale cached session claim instead of workspace_membersQuery live workspace_members status on every workspace-scoped API request
Private PDF receipt fails for the legitimate ownerStorage download route checked role === 'admin' only instead of owner OR adminAllow download when invoice.user_id === session.user.id or session.user.role === 'admin'

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog