Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Sessions and Authentication

Protecting Routes and Authorization

Guard routes in Remix and React Router with requireUser helpers, layout loaders, redirects with a return path, role checks and ownership checks in loaders and actions.

Once users can sign in, you need to decide who may see what. Two words keep the thinking clear. Authentication answers "who are you?" and authorization answers "are you allowed to do this?" Both checks must happen on the server, in loaders and actions. Hiding a link in the interface is a convenience for honest users, not security, because anyone can type a URL or send a request by hand.

This lesson builds a small set of guard helpers, shows where to place them in the route tree so they run once for a whole section, and finishes with ownership checks that stop one user from touching another user's data.

A requireUser helper

Put the check in one function and call it from every protected loader and action:

TypeScript
// app/auth.server.ts (React Router framework mode, read-only)
import { redirect } from "react-router";
import { getSession } from "./sessions.server";

export async function getUserId(request: Request) {
  const session = await getSession(request.headers.get("Cookie"));
  return session.get("userId") ?? null;
}

export async function requireUserId(request: Request) {
  const userId = await getUserId(request);
  if (!userId) {
    const url = new URL(request.url);
    const returnTo = encodeURIComponent(url.pathname + url.search);
    throw redirect(`/login?return=${returnTo}`);
  }
  return userId;
}

Why throw redirect(...)? A redirect is a response, and throwing a response stops the loader immediately. Code after await requireUserId(request) can assume a user exists. The return path means the login action can send the visitor back to where they were going (validate it first: only accept paths that start with a single /, or you create an open redirect).

Guard at the layout

A parent route's loader runs in parallel with its children's loaders, not before them. That detail changes how you protect a section: a child loader may start fetching data before the parent decides to redirect. The safe rule is that every loader and action that returns private data does its own check. You can still add a layout guard for the page shell:

TSX
// app/routes/dashboard.tsx - layout for /dashboard/* (read-only)
export async function loader({ request }: Route.LoaderArgs) {
  const userId = await requireUserId(request);
  const user = await db.user.find(userId);
  return { user };
}

export default function DashboardLayout({ loaderData }: Route.ComponentProps) {
  return (
    <div>
      <header>Signed in as {loaderData.user.name}</header>
      <Outlet />
    </div>
  );
}
TSX
// app/routes/dashboard.reports.tsx (read-only)
export async function loader({ request }: Route.LoaderArgs) {
  const userId = await requireUserId(request); // check again, never rely on the parent
  return { reports: await db.report.forUser(userId) };
}

Calling requireUserId twice costs a cheap cookie read. Forgetting it once can expose data.

Node.js Stand-in: requireUserId with a return path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Roles and permissions

Authorization usually starts with a role stored on the user (admin, editor, member). Wrap the check so the intent is obvious and the failure is a proper 403:

TypeScript
export async function requireRole(request: Request, allowed: string[]) {
  const userId = await requireUserId(request);
  const user = await db.user.find(userId);
  if (!user || !allowed.includes(user.role)) {
    throw data("You do not have access to this page.", { status: 403 });
  }
  return user;
}

Use 401/redirect for "not signed in" and 403 for "signed in but not allowed". The boundary renders a suitable page for the 403.

Ownership checks

The most common real-world bug is not a missing login; it is a missing ownership check. A signed-in user changes /notes/17 to /notes/18 and reads someone else's note. Always scope queries by the current user:

TypeScript
export async function loader({ request, params }: Route.LoaderArgs) {
  const userId = await requireUserId(request);
  const note = await db.note.findFirst({ where: { id: params.id, ownerId: userId } });
  if (!note) throw data("Not found", { status: 404 }); // 404, not 403: do not confirm it exists
  return { note };
}

Returning 404 instead of 403 avoids confirming that the record exists. Do the same inside actions: a delete action must also check ownerId, because anybody can post a form by hand.

Node.js Stand-in: scoped queries stop cross-user access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Showing the right interface

The loader can also return flags such as canEdit, so the component shows or hides buttons without repeating the rules. Treat these flags as presentation only; the action must verify again. Keep the permission rules in one server module and test them (see Testing Loaders and Actions).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must a child route loader check authentication itself even when its layout already does?

    Loaders for a matched URL run in parallel. Each loader or action returning private data must do its own check.
  2. 2. A signed-in user opens another user's note by changing the ID in the URL. Which check prevents this?

    Ownership checks on the server are the fix. 404 avoids confirming the record exists.
  3. 3. Which status fits a signed-in user without the admin role visiting /admin?

    403 means the server knows who you are and refuses. Unauthenticated visitors are redirected to login.
  4. 4. What must you validate before redirecting to a return path from the query string?

    An attacker could craft a login link that sends users to another site after signing in.

Summary

  • Authentication and authorization checks belong on the server, in loaders and actions.
  • Wrap them in requireUserId and requireRole; throw a redirect or a 403.
  • Parent and child loaders run in parallel, so every private loader checks again.
  • Scope queries by owner and return 404 for records the user cannot see.
  • Validate return paths to avoid open redirects.

Next: CSRF and Security