Thuta Learning
AdvancedWeb Developmentintermediate

Authentication and Authorization

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Tell authentication and authorization apart
  • Check permissions in Server Actions and the data layer
  • Never treat hiding UI as real security

Hiding a delete button isn't security. Users can still send the request directly themselves, so the server needs to check both “who is this person” and “are they allowed to delete this note.”

The mental model

Authentication confirms a user's identity from a session; authorization checks resource ownership or role. Redirecting in a layout is useful for user experience, but checking inside data access functions and Server Actions is what actually protects you. Set the session cookie's httpOnly, secure, and sameSite policy appropriately, and it's better to use a well-tested auth library for things like password hashing and CSRF protection.

Let's build it together

typescript
"use server";

export async function deleteNote(noteId: string) {
  const session = await getSession();
  if (!session?.user) throw new Error("Unauthorized");

  const note = await db.note.findUnique({ where: { id: noteId } });
  if (!note) throw new Error("Not found");
  if (note.ownerId !== session.user.id) throw new Error("Forbidden");

  await db.note.delete({ where: { id: noteId } });
}

How the code works

deleteNote throws an unauthorized error if there's no session, and compares note.ownerId with the current user's id. Even if the button is hidden, this check protects against a direct request.

You should see
Only a logged-in user who owns the note can delete it.

5-Minute Try-It

Write a permission check that allows updates only for an Editor role or the note's owner.

Next.js — AuthenticationNext.js

Easy traps

  • Treating a hidden button as authorization
  • Assuming that checking the session in one layout secures every data function

Exercise

Write a permission check that allows updates only for an Editor role or the note's owner.

You'll know it worked when: Only a logged-in user who owns the note can delete it.

Authentication and Authorization | Thuta Learning