Skip to main content
Tutorials

Users should only see their own data: how to do it with Next.js 16, Prisma and Better Auth

Being logged in doesn't tell you which rows you can read. Check the session on the server, scope every Prisma query by userId, and test with two accounts.

Israel Palma Sebastià

This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included

In November, Crissy Field, a security consultancy based in Hamburg, published an analysis with Handelsblatt of 159,041 projects built with Lovable between December 2025 and September 2026. Of the 34,545 that used Supabase, 24,664 sent database records as soon as the page loaded, with nobody logged in. In 7,403 of those sites there were tables containing email addresses.

They ask you to read that number carefully: some of the data may be public on purpose, and the percentage measures exposure without confirming leaks. Still, what they found includes passport numbers, invoices, chat messages and, in one case, 280,000 sent emails. And their own summary applies to any stack: access control mistakes happen in any application, whether a person or an AI wrote it.

If you're building your SaaS on Next.js, not using Lovable doesn't protect you. The underlying bug is the same everywhere, and it has a name: treating authentication as if it were authorization.

  • Authentication: who you are. Better Auth handles it: email and password, OAuth, 2FA, a session cookie.
  • Authorization: what you're allowed to see and change. No login library can do that for you, because it depends on your data model.

Being logged in tells you there's a user. It doesn't tell you whether invoice cm4x9… belongs to them. Broken Access Control sits at number one in the OWASP Top 10 2025, and this gap is usually how it gets in.

The classic bug: change the id in the URL

You have a /dashboard/projects/[id] page and a server action that deletes a project. The first instinct, and what an assistant will often write if it has no context, is this:

// ❌ Fetch by id, check later (or never)
const project = await db.project.findUnique({ where: { id } });
if (!project) notFound();
return project;

Any logged-in user who edits the id in the URL sees someone else's project. It's called IDOR (Insecure Direct Object Reference), and it takes no skill at all: an id copied from a shared link, an email or an API response is enough.

The most common "fix" isn't great either:

// ⚠️ Works, as long as nobody forgets the if
const project = await db.project.findUnique({ where: { id } });
if (!project || project.userId !== session.user.id) notFound();

It holds until someone copies the query somewhere else and drops the if. And you've already read a row you shouldn't have.

The rule: userId goes inside the query

// ✅ The database can only return rows owned by the session user
const project = await db.project.findFirst({
  where: { id, userId: session.user.id },
});
if (!project) notFound();

If the project isn't theirs, as far as your code is concerned it doesn't exist. Return a 404 rather than a 403, so you don't confirm the id is real.

For writes and deletes, same idea with updateMany / deleteMany, which accept any filter and tell you how many rows they touched:

const { count } = await db.project.deleteMany({
  where: { id, userId: session.user.id },
});
if (count === 0) notFound();

That's exactly how the CREA.MBA boilerplate marks a notification as read:

// src/lib/notifications/service.ts
export async function markAsRead(notificationId: string, userId: string) {
  return db.notification.updateMany({
    where: { id: notificationId, userId },
    data: { read: true },
  });
}

Send someone else's notification id and count is 0. Nothing happens.

Where userId comes from: the session, read on the server

The other half is where that userId comes from. Never from the client: not the body, not a query param, not a hidden form field. Always from the session, and the session is read on the server.

With Better Auth on Next.js 16:

import { headers } from 'next/headers';
import { auth } from '@/lib/auth/server';

const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect('/login');
// session.user.id is the only userId you can trust

This goes in every server entry point:

  • Server actions. The Next.js 16 docs are blunt about it: a server action is a POST that anyone can send, even if no button in your UI calls it. "Treat every action as an untrusted entry point."
  • Route handlers (app/api/**/route.ts), treated like any public API.
  • Pages and server components that read data.

Client-side useSession() is for showing the avatar or redirecting when there's no session. It improves the experience, but anyone can make the request by hand.

Rather than repeating those lines in every endpoint, the boilerplate has two wrappers: createAuthenticatedApiHandler for route handlers and createAuthenticatedAction for server actions. Both read the session with auth.api.getSession, return UNAUTHORIZED if there isn't one, and hand the resolved user to your handler:

// src/app/api/notifications/route.ts
export const POST = createAuthenticatedApiHandler({
  schema: markReadSchema,
  handler: async (input, _req, user) => {
    await markAsRead(input.notificationId, user.id);
    return { success: true };
  },
});

The client sends notificationId and nothing else. The server supplies the userId. The whole dashboard works this way: the credits hook calls /api/credits/balance with no parameters, and the endpoint runs paymentService.getCreditBalance(user.id) with the session user.

Why proxy isn't enough

In Next.js 16, middleware.ts is now proxy.ts (the old name is deprecated). It's tempting to add "no cookie, go to /login" there and call it done. Three reasons not to:

  1. Next.js says so. The v16 authentication guide is explicit: proxy is for optimistic checks (read the cookie, redirect), but it "should not be your only line of defense in protecting your data". Real checks belong as close to the data as possible.
  2. Better Auth says so. Its proxy helper, getSessionCookie, only checks that the cookie exists; it doesn't validate it. The docs warn that anyone can craft a cookie by hand.
  3. It has already failed. In March 2025, CVE-2025-29927 (CVSS 9.1) showed that a single header could skip middleware entirely on Next.js 12 to 15. Apps that only checked there were wide open. Apps that also checked in the handler weren't.

And even a flawless proxy only knows whether there's a session, not who owns each row. The IDOR above walks right past it.

That's why the boilerplate's proxy.ts doesn't look at the session. It does per-route rate limiting, validates Origin on non-GET API requests and handles locale routing. Authorization lives in the handlers.

The same goes for layouts. The Next.js 16 guide warns that they don't re-render on navigation, and that a layout doesn't stop the pages inside it from running. The check belongs in the page or, better, in the function that reads the data.

The pattern nobody forgets: a data access layer

If every page and every action has to remember to read the session and add the userId, sooner or later one won't, especially when an agent is writing the code. Next.js recommends a data access layer (DAL): one place where database reads happen, with authorization built in.

// src/lib/dal/projects.ts
import 'server-only';

import { cache } from 'react';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';

import { auth } from '@/lib/auth/server';
import { db } from '@/lib/db/client';

export const requireUser = cache(async () => {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) redirect('/login');
  return session.user;
});

export async function getProject(id: string) {
  const user = await requireUser();
  return db.project.findFirst({
    where: { id, userId: user.id },
    select: { id: true, name: true, createdAt: true },
  });
}

export async function deleteProject(id: string) {
  const user = await requireUser();
  const { count } = await db.project.deleteMany({ where: { id, userId: user.id } });
  return count > 0;
}

Three details:

  • import 'server-only' (bun add server-only) makes the build fail if a client component imports this file. A compile error beats a production leak.
  • React's cache avoids reading the session several times in the same render. Note that server actions and route handlers aren't a render pass, so there it runs on every call (the docs say so).
  • select returns only the fields the view needs. If the object ever reaches a client component, nothing extra travels with it.

DAL functions don't take userId as a parameter; they get it themselves. There's no way to call them with the wrong one.

The page:

// src/app/[locale]/dashboard/projects/[id]/page.tsx
import { notFound } from 'next/navigation';
import { getProject } from '@/lib/dal/projects';

export default async function ProjectPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const project = await getProject(id);
  if (!project) notFound();
  return <h1>{project.name}</h1>;
}

The action:

'use server';
import { notFound } from 'next/navigation';
import { deleteProject } from '@/lib/dal/projects';

export async function deleteProjectAction(id: string) {
  if (!(await deleteProject(id))) notFound();
}

To be upfront: the CREA.MBA boilerplate doesn't ship a dal/ folder or use server-only today. It centralizes through the wrappers above and through services that receive the already-resolved user, like markAsRead(id, user.id). It works, but passing user.id is still the caller's job. For the models you add yourself (projects, documents, whatever your product is), a DAL with server-only is the hardest version to break.

The two-account test (ten minutes)

No code review replaces trying it. Before any deploy that touches user data:

  1. Create two accounts, A and B: one in your normal browser, one in a private window.
  2. As A, create a resource (a project, an invoice) and copy its id from the URL or the network tab.
  3. As B, open A's URL: /dashboard/projects/. You should get a 404.
  4. Repeat against the API. Copy B's session cookie from DevTools (Better Auth calls it better-auth.session_token, with a __Secure- prefix over HTTPS) and send the request with A's id:
curl -X POST http://localhost:3000/api/notifications \
  -H "Origin: http://localhost:3000" \
  -H "Content-Type: application/json" \
  -H "Cookie: better-auth.session_token=" \
  -d '{"notificationId":""}'

(The Origin header has to match your app's URL. In production the boilerplate's proxy rejects API POSTs that carry neither Origin nor Referer; locally it lets them through, but sending it keeps the test identical to production.)

  1. Check the database: A's resource must be unchanged. A 200 response proves nothing on its own, either way.

If you do this often, turn it into a Playwright test with two browser contexts, one per account. Few tests are this cheap to write for what they save you.

Takeaways

  • Authentication tells you who it is. Authorization is yours to write, in every query.
  • userId comes from the session read on the server, never from what the client sends.
  • where: { id, userId } inside the query, not an if afterwards.
  • Proxy redirects; data is protected next to the data.
  • Two accounts and ten minutes before you deploy.

CREA.MBA ships the boring part done: Better Auth configured, the session checked on the server in the API and server action wrappers, and the dashboard endpoints (notifications, credits, payments, subscriptions) scoped to the session user. Your product's own models are yours to write, and the rule is the same there.

Have you ever opened your app with another account's session to see what it shows?

Next.jsPrismaBetter AuthSecurityAuthorization

Enjoyed this article?

Subscribe for more tutorials and tips on building products with AI