Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 50 ยท Framework Mode

Server Loaders, Client Loaders and Actions

Learn how framework-mode loaders run on the server, when to use clientLoader, how to keep secrets out of the browser, set cookies and sessions, and export meta, links and headers.

In data mode every loader runs in the browser. That is simple, but it means your data code ships to every visitor, the first paint waits for JavaScript and an API call, and anything a loader touches has to be reachable from the browser. Framework mode adds a second place to run that code: the server. A route module can export a loader that runs only on the server, a clientLoader that runs only in the browser, or both together.

This lesson explains who runs what, how the data reaches the page, how to keep private code private, and how the same route module also controls cookies, response headers, the document title and stylesheets. It builds on Framework Mode Overview and Route Config and File Routes. Everything marked read-only is real React Router 7 code that the live editor cannot run. The runnable examples use plain React functions that imitate the idea, and each one says so.

A route module is a bundle of exports

In framework mode a route file is a route module. Its default export is the component, and named exports tell the framework how to handle the route:

Export Runs Purpose
loader server only read data for a GET request
clientLoader browser only read data in the browser, or wrap the server loader
action server only handle a non-GET form submission
clientAction browser only handle a submission in the browser
meta both document title and meta tags
links both stylesheets, preloads, icons
headers server only HTTP response headers for the document
HydrateFallback both what to show while a clientLoader runs during hydration

Here is a typical server loader, using the generated types from +types:

TSX
// app/routes/product.tsx - React Router framework mode (read-only)
import { data } from "react-router";
import type { Route } from "./+types/product";
import { db } from "~/db.server";

export async function loader({ params }: Route.LoaderArgs) {
  const product = await db.product.find(params.id);
  if (!product) {
    throw data("No such product", { status: 404 });
  }
  return { id: product.id, name: product.name, price: product.price };
}

export default function Product({ loaderData }: Route.ComponentProps) {
  return (
    <h1>
      {loaderData.name}: ${loaderData.price}
    </h1>
  );
}

The component receives the return value as loaderData. You can also read it anywhere below the route with useLoaderData. Notice that the loader returns a plain object, with no json() wrapper. React Router serializes the value itself, and the format can carry dates, Map, Set, BigInt and even unawaited promises, which is how streaming works.

What happens on each kind of request

There are two situations and the loader runs on the server in both:

  1. Document request. The user types the URL or follows a link from another site. The server runs the loaders of every matched route in parallel, renders the HTML with that data and sends it. The browser then hydrates: React attaches to the HTML, and the data is already embedded in the page, so the loaders do not run again.
  2. Client navigation. The user clicks a Link. The router, already running in the browser, asks the server for the loader data of the routes that are new or need revalidation (one request, called a single fetch), then renders the new screen in the browser.
sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: GET /products/2 (document request)
    S->>S: run loaders in parallel
    S-->>B: HTML plus embedded loader data
    B->>B: hydrate, no loader call
    B->>S: click Link, request data for /products/3
    S->>S: run loader for the changed route
    S-->>B: data only, no HTML
    B->>B: render the new screen

A server loader is the only data source in both cases. The browser never runs it, it only receives its result.

Server-only code stays on the server

The most important property of a server loader is that its code is removed from the browser bundle. The build compiles each route module twice. In the client build the loader, action and headers exports and the imports used only by them are deleted. You can therefore query a database, read the file system, call a private API with a secret key and import heavy libraries, and none of it reaches the visitor.

Two rules keep this reliable:

  • Name modules that must never be bundled for the client something.server.ts (or put them in a .server folder). If client code imports one, the build fails instead of leaking it.
  • Whatever you return from a loader is public. It is serialized into the HTML and into data responses. Select the fields the page needs. Never return a whole database row because it "might be useful".

The first runnable example shows the difference. The "server" block holds a row with private fields. Pick a loader and read the exact text that would cross the network. This is a hand-written stand-in: it uses JSON.stringify where real React Router uses its own serializer.

What crosses the wire

Switch to the leaky loader and the private cost and e-mail appear in the payload. Product 9 does not exist, so you get the status the loader chose. In the real API you signal that with throw data(..., { status: 404 }), and the framework renders the nearest error boundary with that status.

clientLoader: running in the browser

A clientLoader runs only in the browser, on client navigations. Use it when the data lives in the browser (IndexedDB, an in-memory cache), when the browser can call a public API directly and you want to skip a hop through your server, or when you want to wrap the server loader to add caching.

Inside a clientLoader the function serverLoader() calls your server loader (a network request) and returns its data:

TSX
// app/routes/product.tsx - React Router framework mode (read-only)
const cache = new Map<string, { id: string; name: string; price: number }>();

export async function loader({ params }: Route.LoaderArgs) {
  return db.product.find(params.id);
}

export async function clientLoader({ params, serverLoader }: Route.ClientLoaderArgs) {
  const cached = cache.get(params.id);
  if (cached) {
    return cached;
  }
  const fresh = await serverLoader();
  cache.set(params.id, fresh);
  return fresh;
}

The rules for when each one runs:

  • On the initial document request the server loader supplies the data and the clientLoader is skipped, because the page already has everything.
  • Set clientLoader.hydrate = true to make the clientLoader run once during hydration too. The server then cannot know the final data, so it renders the route's HydrateFallback component instead of the page, and the browser swaps in the real UI when the loader finishes.
  • On client navigations the clientLoader runs instead of a direct server request. It decides whether to call serverLoader().
  • A route with only a clientLoader never runs on the server, so the server also renders HydrateFallback for it.
flowchart TD
    A["Link click: need data for /products/3"] --> B{"route exports clientLoader?"}
    B -- no --> C["router fetches loader data from the server"]
    B -- yes --> D["run clientLoader in the browser"]
    D --> E{"calls serverLoader()?"}
    E -- yes --> C
    E -- no --> F["return data from the browser (cache, IndexedDB, public API)"]
    C --> G["render the route"]
    F --> G

A clientLoader is a gate in front of the server request: it can answer alone or ask the server.

The next example imitates that gate with a request counter. serverLoader is a function that logs each "network request". The wrapper with a cache avoids repeating them. It is a stand-in: the real clientLoader receives serverLoader from the router.

A clientLoader that caches the server loader

Click product 1, then 2, then 1 again. With the cache on, the second visit to product 1 logs a cache hit and no request. Untick the box (which also resets the log) and every click is a request. The trade-off is real: a cached clientLoader is fast but can show stale data, so pair it with revalidation rules when the data changes.

Cookies and sessions

Because loaders and actions receive a standard Request, reading cookies is plain Web API code, and returning headers is how you set them. React Router ships helpers that build sessions on top of this. A cookie-based session stores the (signed) session data inside the cookie itself:

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

export const { getSession, commitSession, destroySession } = createCookieSessionStorage({
  cookie: {
    name: "__session",
    httpOnly: true,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 7,
    secrets: [process.env.SESSION_SECRET!],
    secure: process.env.NODE_ENV === "production",
  },
});
TSX
// app/routes/login.tsx - React Router framework mode (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 checkPassword(form.get("email"), form.get("password"));
  const session = await getSession(request.headers.get("Cookie"));
  if (!user) {
    session.flash("error", "Wrong e-mail or password");
    return data({ error: "Wrong e-mail or password" }, { status: 401 });
  }
  session.set("userId", user.id);
  return redirect("/dashboard", {
    headers: { "Set-Cookie": await commitSession(session) },
  });
}

The pattern is always the same: read the Cookie request header into a session, change the session, then commit it into a Set-Cookie response header. Forgetting the header means the change is silently lost. httpOnly keeps JavaScript from reading the cookie and secrets signs it so users cannot edit it (the contents are signed, not encrypted, so never store secrets in it). Full login flows, CSRF and protecting data are covered in Authentication with Loaders and Actions.

The stand-in below plays both sides of that exchange. The "browser" keeps a cookie jar and sends it with each request, the "server" loader reads the session, counts the visit and returns a Set-Cookie header. Real sessions are signed; this one is only encoded, to keep the code short.

Cookies in, Set-Cookie out

Each request carries the cookie from the previous response, so the counter grows. After "Clear cookies" the server sees no cookie and starts at 1 again. That is the whole mechanism behind a login: the user's identity travels in a header, not in React state.

Actions on the server

A server action works like a loader for non-GET requests: it receives the Request, reads await request.formData(), writes to the database and returns data or a redirect. After it finishes, React Router automatically calls the loaders again, so the page shows fresh data without any manual refetching. The component receives the returned value as actionData. A clientAction is the browser-side version, and its serverAction() function calls the server action the same way serverLoader() does. The form and submission mechanics are the subject of Actions and Form.

Three more exports shape the document around the component.

headers sets HTTP headers on the document response. Headers from a loader do not automatically reach the page, so you forward them explicitly, usually to cache whole pages at a CDN:

TSX
// app/routes/article.tsx - React Router framework mode (read-only)
import { data } from "react-router";

export async function loader({ params }: Route.LoaderArgs) {
  const article = await db.article.find(params.slug);
  return data(article, { headers: { "Cache-Control": "public, max-age=300" } });
}

export function headers({ loaderHeaders }: Route.HeadersArgs) {
  return { "Cache-Control": loaderHeaders.get("Cache-Control") ?? "no-store" };
}

meta returns an array of descriptors for <title> and <meta> tags. It receives the loader data, so each product page can have its own title and description, which matters for search engines and link previews:

TSX
// app/routes/product.tsx - React Router framework mode (read-only)
export function meta({ data }: Route.MetaArgs) {
  return [
    { title: data ? data.name + " | Shop" : "Not found | Shop" },
    { name: "description", content: "Buy " + (data?.name ?? "products") + " online." },
  ];
}

When several matched routes export meta, the deepest route wins: its array replaces the parent's instead of being merged. To keep a parent's tags, read matches and spread them in yourself. The root route renders the result with <Meta /> in <head>.

links returns descriptors for <link> elements, mostly stylesheets, icons and preloads, and every matched route's links are combined and rendered by <Links />:

TSX
// app/routes/product.tsx - React Router framework mode (read-only)
import productStyles from "./product.css?url";

export const links: Route.LinksFunction = () => [
  { rel: "stylesheet", href: productStyles },
];

Because only the matched routes contribute, a page loads only the CSS it needs, and the links disappear when the user leaves the route.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A framework-mode route exports a loader. Where does it run on a client-side Link navigation?

    A route's loader export is server-only. On client navigations the router requests its data from the server and renders the result in the browser, so the loader code never ships to the client.
  2. 2. Your loader returns a full database row that includes a private supplier e-mail. What is the consequence?

    Everything a loader returns is sent to the browser. Server-only code stays on the server, but its return value does not. Select only the fields the page renders.
  3. 3. What does serverLoader() do inside a clientLoader?

    serverLoader is passed to the clientLoader by the router. Calling it fetches the server loader's data, so a clientLoader can add caching or post-processing around it.
  4. 4. You change a session in an action but the change is gone on the next request. What is the most likely mistake?

    A session is read from the Cookie request header and written back through a Set-Cookie response header. If you skip commitSession and the header, the browser never receives the new session.
  5. 5. A parent and a child route both export meta. Which tags end up in the document?

    The deepest matching route's meta result wins. To keep tags from a parent you read matches in the child and include them yourself.

Summary

  • A route module exports loader/action (server), clientLoader/clientAction (browser), a component and helpers such as meta, links, headers and HydrateFallback.
  • Server loaders run for document requests and for client navigations (single fetch); their code is removed from the browser bundle, but their return value is public.
  • A clientLoader can run alone or wrap serverLoader() for caching; clientLoader.hydrate = true also runs it during hydration and needs a HydrateFallback.
  • Sessions use the Cookie request header and a committed Set-Cookie response header; use httpOnly, signing secrets and .server modules.
  • headers forwards response headers, meta builds titles per page (deepest route wins) and links loads stylesheets only where needed.

Next: SSR, Streaming and Deployment