Menu

Authorisation and the Data Access Layer

Lesson 3: Authorisation and the Data Access Layer

Where should permission checks live?

Pages, Server Actions, and Route Handlers are all separate entry points. A check in one does not protect the others.

Layer Role Enough on its own?
proxy.ts Quick redirect for signed-out users No: optimistic only
Layout Shared UI No: layouts do not re-run on every navigation
Page Hide or show UI No: actions and APIs bypass pages
Data access layer Check before every read and write Yes: the reliable place

Example

// lib/dal.ts
import 'server-only';
import { cache } from 'react';
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { auth } from '@/lib/auth';

export const verifySession = cache(async () => {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) redirect('/login');
  return { userId: session.user.id, role: session.user.role as 'student' | 'instructor' | 'admin' };
});

export async function getMyEnrolments() {
  const { userId } = await verifySession();
  return db.enrolment.findMany({
    where: { userId },
    select: { id: true, course: { select: { title: true, slug: true } }, progress: true },
  });
}
// app/courses/[slug]/actions.ts
'use server';
import { verifySession } from '@/lib/dal';

export async function deleteReview(reviewId: string) {
  const { userId, role } = await verifySession();
  const review = await db.review.findUnique({ where: { id: reviewId } });

  if (!review) return { error: 'Review not found' };
  if (review.userId !== userId && role !== 'admin') {
    return { error: 'You can only delete your own reviews' };
  }

  await db.review.delete({ where: { id: reviewId } });
  updateTag(`course-${review.courseId}`);
}

How it works

  • verifySession is wrapped in cache(), so calling it in many places costs one lookup per request.
  • Every data function starts with a check. If someone calls an action directly, the check still runs.
  • Ownership checks ("is this your review?") are as important as role checks.
  • select returns a DTO (data transfer object) containing only the fields the UI needs.

Common mistakes

Mistake Effect Fix
Checking roles only on the page Actions can be called directly Check inside every action and data function
Trusting an ID sent from the client (userId in form data) Users act as someone else Always use the user ID from the session
Returning full user records to Client Components Leaks emails, hashes, internal flags Return DTOs with selected fields
Relying on proxy.ts alone Bypassed by other entry points Treat proxy as a convenience, not a guard

Key takeaways

  • Put authorisation in a server-only data access layer and call it from every entry point.
  • Check identity, role, and ownership before every read and write.

Try it: Create lib/dal.ts with verifySession, then protect the delete-review action so only the author or an admin can use it.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details