Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 50 ยท Production Concerns

Authentication with Loaders and Actions

Protect routes with loaders that redirect, sign in and out with actions, keep sessions in HttpOnly cookies, and learn why guards alone never protect your data.

In Protected Routes and Auth Redirects you guarded pages with a component that read a user from React context. That works for hiding screens, but it has two weaknesses. The page flashes before the redirect, and the guard lives in the browser, where anyone can change it. A data router gives you a better place for the check: the loader that runs before the page renders, and the action that handles the login form.

This lesson shows the whole loop with loaders and actions: visit a protected URL, get redirected to a login page, sign in, return to where you were going, and sign out. Along the way you will meet the one rule that matters most for real security: the server decides, the router only reacts. You should be comfortable with Loaders: Data Before Render and Actions and Form.

Where the login state lives

A single-page app needs to answer "who is signed in?" without trusting JavaScript. The standard answer is a session cookie set by the server:

  • The server creates the cookie when the password is correct and marks it HttpOnly, so scripts (including an attacker's injected script) cannot read it.
  • The browser sends it automatically with every request to that site.
  • The server reads it on each request, and answers 401 when it is missing or invalid.

The router never sees the cookie. Instead, your loaders ask the server: "who am I?" and "give me my notes". When you keep tokens in localStorage instead, any cross-site scripting bug can steal them, so prefer HttpOnly cookies for browser apps.

A guard loader that redirects

In data mode (a client-side app talking to your API), a guard is a function you call at the top of a loader. If there is no user, it throws a redirect(), and React Router navigates instead of rendering. Real code, read-only:

JSX
// auth.js - React Router, data mode (read-only)
import { redirect } from 'react-router';

export async function requireUser(request) {
  const response = await fetch('/api/me', { credentials: 'include' });
  const { user } = await response.json();

  if (!user) {
    const url = new URL(request.url);
    const from = url.pathname + url.search;
    throw redirect(`/login?from=${encodeURIComponent(from)}`);
  }
  return user;
}

// routes.jsx
const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />,
    loader: rootLoader,
    children: [
      { index: true, element: <Home /> },
      { path: 'login', element: <Login />, loader: loginLoader, action: loginAction },
      { path: 'logout', action: logoutAction },
      {
        element: <Outlet />,
        loader: ({ request }) => requireUser(request),
        children: [
          { path: 'notes', element: <Notes />, loader: notesLoader },
          { path: 'account', element: <Account /> },
        ],
      },
    ],
  },
]);

The route without a path is a pathless layout route (see Layout Routes and Pathless Routes). It exists only to hold the guard for everything below it. The from value in the query string remembers where the visitor was heading, and the login action will use it to send them back.

A layout guard does not protect its children's data. React Router runs the loaders of all matched routes in parallel, to avoid waterfalls. When /notes is requested, the guard loader and notesLoader start at the same moment. The guard's redirect wins in the browser, but notesLoader has already sent its request. If your API answers that request without checking the session, the data is exposed. Always enforce access in the API (or in every loader and action that touches private data).

sequenceDiagram
    participant B as Browser
    participant R as Router loaders
    participant S as Server API
    B->>R: Visit /notes while signed out
    R->>S: GET /me and GET /notes (in parallel)
    S-->>R: user is null, and 401 for notes
    R-->>B: redirect to /login?from=/notes
    B->>S: POST /login (the action)
    S-->>B: Set-Cookie session, then redirect to /notes
    B->>R: Loaders run again
    R->>S: GET /me and GET /notes with the cookie
    S-->>R: the user and the notes
    R-->>B: render Notes

The 401 for the notes request is the real protection. The redirect only improves the experience.

Real library or stand-in? The code above is the real API. The live examples use a small hand-written data router built on React and location.hash: loaders run in parallel when the URL changes, a thrown redirect() navigates, forms call actions, and every successful action re-runs the loaders. The "server" is a plain JavaScript object with a fake session variable standing in for the cookie, and each API call is written to a log you can read below the page. Real loaders are async functions that run before rendering, as here, but the real router also tracks pending states, error boundaries and history entries. The routing basics come from Client-Side Routing.

Try the guard

Click "Notes" while signed out. Watch the log: all the loaders fire together, and /notes answers 401 even though the browser ends up on the login page.

A guard loader and the parallel request

Click "Notes" while signed out and look for three calls in a row: GET /me, GET /me, GET /notes -> 401 (a further GET /me comes from loading the login page). The 401 is the guard working at the server. Sign in as Ada, and you land on /notes (the from value), where the list loads with a 200.

Login and logout as actions

A login is a form submission, so it belongs in an action. The action reads the form data, asks the server to check the password, and either returns an error for the form to show or returns a redirect(), which sends the user on and makes the router re-run every loader (so the layout instantly shows the signed-in user). Real code for a client-side app:

JSX
// auth-actions.js - React Router, data mode (read-only)
import { redirect } from 'react-router';

export async function loginAction({ request }) {
  const form = await request.formData();
  const from = String(form.get('from') ?? '/');

  const response = await fetch('/api/login', {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      username: form.get('username'),
      password: form.get('password'),
    }),
  });

  if (!response.ok) {
    const { error } = await response.json();
    return { error };
  }
  return redirect(safeRedirect(from));
}

export async function logoutAction() {
  await fetch('/api/logout', { method: 'POST', credentials: 'include' });
  return redirect('/login');
}

function safeRedirect(to) {
  return to.startsWith('/') && !to.startsWith('//') ? to : '/';
}

Three details are easy to miss:

  1. Validate from. It comes from the URL, so anyone can craft /login?from=https://evil.example. Only accept paths that start with a single /. This is the same open-redirect rule used for ?return= on this site.
  2. Log out with a form, not a link. Signing out changes state, so it must be a POST: <Form method="post" action="/logout">. A plain link (a GET) can be triggered from another site by an image tag.
  3. Return errors, do not throw them. A wrong password is an expected outcome. Return { error } and read it with useActionData(); keep throw for redirects and for real failures.

The login page itself can also be a guard in reverse: its loader sends already-signed-in users away, so they never see the form.

Login form, error message and sign out

Open "Profile" while signed out: you land on /login?from=/profile. Press "Sign in" with empty fields and you get an error from the action. Try ada with a wrong password, then the right one (secret): you are redirected back to the profile page. Sign out, and the logout action sends you to the login page. Finally, while signed in, click "Login": the login loader redirects you away.

Sessions in framework mode

In framework mode your loaders and actions run on the server, so the cookie can be read and written directly. React Router provides session helpers; this is the shape of the real code (read-only; see Server Loaders, Client Loaders and Actions):

TypeScript
// app/sessions.server.ts (read-only)
import { createCookieSessionStorage } from 'react-router';

type SessionData = { userId: string };

export const { getSession, commitSession, destroySession } =
  createCookieSessionStorage<SessionData>({
    cookie: {
      name: '__session',
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      path: '/',
      maxAge: 60 * 60 * 24 * 7,
      secrets: [process.env.SESSION_SECRET!],
    },
  });
TypeScript
// app/routes/login.tsx (read-only)
import { data, redirect } from 'react-router';
import { getSession, commitSession } from '~/sessions.server';

export async function action({ request }: Route.ActionArgs) {
  const form = await request.formData();
  const user = await verifyCredentials(String(form.get('email')), String(form.get('password')));

  if (!user) {
    return data({ error: 'Wrong email or password' }, { status: 401 });
  }

  const session = await getSession(request.headers.get('Cookie'));
  session.set('userId', user.id);
  return redirect(safeRedirect(String(form.get('from') ?? '/')), {
    headers: { 'Set-Cookie': await commitSession(session) },
  });
}
TypeScript
// app/auth.server.ts (read-only)
import { redirect } from 'react-router';
import { getSession } from '~/sessions.server';

export async function requireUserId(request: Request): Promise<string> {
  const session = await getSession(request.headers.get('Cookie'));
  const userId = session.get('userId');
  if (!userId) {
    const url = new URL(request.url);
    throw redirect(`/login?from=${encodeURIComponent(url.pathname + url.search)}`);
  }
  return userId;
}

Every protected loader and action starts with const userId = await requireUserId(request). That repetition is deliberate: it is what keeps the data safe, whatever the parent routes do. This cookie session stores its data inside the cookie, signed but not encrypted, so keep only an id there and never secrets. Larger apps use createSessionStorage with a database or Redis, where the cookie only holds a random session id.

Security notes

  • CSRF. A cookie is sent automatically, even when another site makes your browser send a request. React Router does not add CSRF protection for you. SameSite=Lax (the default in modern browsers, and set explicitly above) stops cross-site POST requests with your cookie in most cases. For sensitive actions also check the Origin header or use a CSRF token, and never change state on a GET.
  • Actions are public endpoints. Anyone can send a POST to an action's URL without ever loading your pages, so check authentication and permission inside every action.
  • Roles are checked on the server. Hiding an "Admin" link is a convenience. The loader or API must verify the role before returning data.
  • Open redirects. Validate from as shown, and prefer a list of known paths for anything sensitive.
  • Cookies. Use HttpOnly, Secure in production and a reasonable maxAge, and rotate the session value after login.
  • Rate limiting. Limit login attempts on the server; the router cannot do that for you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A pathless layout route has a loader that redirects signed-out users. Its child route notes has a loader that fetches /api/notes. What is true when a signed-out visitor requests /notes?

    Loaders of all matched routes run in parallel. The redirect decides what the visitor sees, but it does not stop the child's request, so the server must answer 401.
  2. 2. Why should the login page return { error } for a wrong password instead of throwing it?

    Actions can return data that useActionData() exposes to the form. Throwing sends the user to an error boundary, which is the wrong experience for a typo in a password.
  3. 3. What makes a session cookie safer against script injection?

    HttpOnly cookies are sent with requests but hidden from document.cookie, so an injected script cannot steal them the way it can read localStorage.
  4. 4. Why must sign out be a POST action rather than a link?

    GET requests are meant to be safe and repeatable. Using a form with method post (and an action) keeps state changes out of links, images and prefetching.
  5. 5. The login action receives a from value from the query string. What must you do before redirecting to it?

    An attacker can craft a login link with a from value pointing to another site. Accepting only local paths prevents an open redirect.

Summary

  • The server owns the truth: a signed HttpOnly session cookie, and 401 or 403 answers for private data.
  • A guard loader (or a helper such as requireUser) throws redirect('/login?from=...') when there is no user.
  • Loaders of matched routes run in parallel, so a layout guard does not protect child loaders; check authentication in every loader and action that touches private data.
  • Login and logout are actions: return errors for the form, return redirect() on success, and let the router re-run loaders.
  • Validate from, sign out with a POST, and add CSRF measures such as SameSite cookies and origin checks.
  • In framework mode, createCookieSessionStorage and requireUserId(request) on the server replace the client-side API calls.

Next: Performance and Common Pitfalls