React: From Components to Production · Routing with React Router

Loaders, Actions and Protected Routes

Load data before rendering and guard routes behind authentication.

In data mode, a route loader fetches data before the route renders (in parallel for nested routes, avoiding waterfalls), and an action handles form submissions. Read results with useLoaderData(). Protect routes by checking auth in a loader or a guard layout and redirecting with redirect() or <Navigate>. Server-side checks remain the real security boundary.

import { redirect, useLoaderData, type LoaderFunctionArgs } from "react-router";

async function requireUser() {
  const user = await getCurrentUser();          // e.g. from /api/me
  if (!user) throw redirect(`/login?next=${encodeURIComponent(location.pathname)}`);
  return user;
}

export async function orderLoader({ params }: LoaderFunctionArgs) {
  await requireUser();
  const res = await fetch(`/api/orders/${params.id}`);
  if (res.status === 404) throw new Response("Not found", { status: 404 });
  return res.json() as Promise<Order>;
}

export function OrderDetail() {
  const order = useLoaderData() as Order;
  return <h1>Order #{order.number}</h1>;
}

// { path: "orders/:id", loader: orderLoader, element: <OrderDetail />, errorElement: <RouteError /> }

Common pitfalls

  • Thinking client-side route guards secure data — APIs must enforce auth.
  • Not handling loader errors with errorElement.
  • Fetching again in components what the loader already loaded.

Key points

  • Loaders fetch before render, in parallel
  • Redirect unauthenticated users
  • APIs remain the security boundary

Further reading: React Router: data loading

Practice questions

Why do loaders help avoid request waterfalls?

Answer

The router knows all matched routes for a URL and runs their loaders in parallel before rendering, instead of each component fetching after its parent renders.

Is a client-side protected route enough to secure data?

Answer

No. It only hides UI; anyone can call the API directly. The server must authenticate and authorize every request.

Open in the app to mark lessons complete, take notes and track your progress.