CodingNic

Authentication & Sessions

Protect Routes and API Resources

Authentication & Sessions 18 min read

Protect Routes and API Resources

Protect Routes and API Resources

Task

Make authentication useful by enforcing it at the application boundary.

Server Helper

Create a single helper that returns the current authenticated user or fails:

ts
export async function requireUser() {
  const session = await getCurrentSession();

  if (!session) {
    throw new Error("UNAUTHORIZED");
  }

  return session.user;
}

For route handlers, convert the failure into a 401 response.

For protected pages, redirect unauthenticated visitors to Login.

Ownership Rule

Authentication alone is not enough. When a route reads a Book, Bookmark, Highlight, Note, or ReadingProgress record, scope the query to the authenticated user.

For example:

ts
const book = await prisma.book.findFirst({
  where: {
    id: bookId,
    userId: user.id,
  },
});

Do not accept a user ID from the browser as proof of ownership.

Test

Try:

  • visiting a protected page while logged out
  • calling a protected endpoint while logged out
  • requesting another user’s book ID

The first two should fail with an authentication response. The last should behave as though the resource is not available to the current user.

Checkpoint

Readly now has a real authentication boundary and a user-ownership boundary.

Module Complete

Registration, login, logout, sessions, and protected resources are now real. Module 4 can build the Library on top of authenticated Book records.