Part 15 / Stage 4
React Router
Goal: Turn a single-screen app into a real multi-page app without leaving the browser - define routes and nested routes with layouts, read URL params and search params, navigate with
<Link>/<NavLink>/useNavigate, fetch a routed page's own data the exact same way Part 11 already taught (no router-owned loaders), build a catch-all 404, and guard a route behind a mock auth check. Time: ~5 hours ยท Level: comfortable with fetching inuseEffect(Part 11) and testing with Testing Library (Part 14)
What you will learn
<Routes>/<Route>mapping a URL path to an element, and<Link>changing the URL without a full page reload- Nested routes: a child
<Route>gets its parent's path as a prefix, and renders through the parent's<Outlet/>- the parent's own chrome stays mounted while only the Outlet's content swaps - Layout routes (a parent
<Route>with nopathof its own) for grouping children under shared UI without adding a URL segment useParamsreading a dynamic:segmentstraight from the current URL, not a propNavLink'sisActivefor highlighting the current nav tab, and whyendmatters on a route that would otherwise prefix-match everythinguseSearchParamskeeping filter/query state in the URL itself (shareable, survives a refresh) versus the same thing inuseState(gone on reload);useNavigatefor moving the user after an action completes, not as a substitute for a normal<Link>click- This course's one deliberate divergence from how most React Router tutorials teach routed data: a routed page fetches its own data in a
useEffectwithAbortController, Part 11's exact pattern, readinguseParams().orderIdinstead of a prop - no routerloaderfunction anywhere in this part - A catch-all
path="*"route for unmatched URLs, and a "protected route" built as a plain component (RequireAuth) that renders<Outlet/>when signed in or<Navigate/>to/login?next=...when not - not a special router feature, just a component placed as a parent route's element - This part's running examples: a Swiggy-style app shell, a restaurant owner's nested dashboard, an IRCTC-style order list/detail, a ticket app's nav bar, a Zomato-style cuisine filter + order confirmation flow, a routed order-status page that fetches its own data, and a signed-in/signed-out account page with a 404
A note on how this part is organised: same convention as every earlier part - every
examples/andsolutions/file here is wired into this repo's ownharness/and actually executed before being shown below.
Topics in this part
Practice
Every exercise below is a React component (or a Broken/Fixed pair) in its own .jsx file, paired with a .test.jsx that actually renders and interacts with it using Testing Library/Vitest, wrapped in a MemoryRouter the same way every example above is - the same verified-output rule as every exercise in this course. This part's Declarative-mode rule applies throughout: no router loader, no useLoaderData, no redirect() anywhere below - a routed page that needs data fetches it in a useEffect, Part 11's way.
Exercise 1: A first route pair - BookMyShow Lite
Scenario: A tiny movie-ticketing app shell needs a Home page and a Movies list page, reachable from a nav.
What to do: Write BookMyShowApp with a <nav> containing <Link to="/">Home</Link> and <Link to="/movies">Movies</Link>, and a <Routes> with <Route path="/" element={<Home />} /> and <Route path="/movies" element={<Movies />} />. Home renders an <h1>BookMyShow Lite</h1>; Movies renders an <h1>Now showing</h1>.
Sample output (really run):
initial render ("/") -> "BookMyShow Lite"
click "Movies" link -> "Now showing", "BookMyShow Lite" gone
๐ก Hint: this is examples/01_basic_routes_and_links.jsx's exact shape, renamed - two routes, a nav of Links, rendered inside a MemoryRouter by the test.
Exercise 2: Nested layout - an Ola Lite driver dashboard
Scenario: A driver dashboard needs a shared heading and nav that stays on screen across two sub-pages: a default "today's trips" view and a separate "earnings" view.
What to do: Write DriverLayout (an <h1>Driver dashboard</h1>, a nav with links to /driver and /driver/earnings, and an <Outlet/>), TodaysTrips (<p>3 trips today</p>), and Earnings (<p>โน1,240 so far today</p>), wired as <Route path="/driver" element={<DriverLayout />}> with <Route index element={<TodaysTrips />} /> and <Route path="earnings" element={<Earnings />} /> as children.
Sample output (really run, starting at /driver):
"/driver" -> "Driver dashboard", "3 trips today"
click "Earnings" -> "Driver dashboard" (still there), "โน1,240 so far today"
๐ก Hint: this is examples/02_nested_routes_and_layout.jsx's RestaurantLayout shape - one parent route with an Outlet, one index child, one named child.
Exercise 3: A NavLink that should (and shouldn't) stay active on a sub-page
Scenario: A support-ticket app's "Tickets" tab should stay highlighted while looking at one specific ticket - but a reviewer also wants an "Archived" tab that should switch off the moment you drill into a specific archived ticket, since that detail page has its own distinct back button and shouldn't look like part of the main Tickets flow.
<NavLink to="/tickets" className={({ isActive }) => (isActive ? "active" : "")}>
Tickets
</NavLink>
<NavLink to="/archived" className={({ isActive }) => (isActive ? "active" : "")}>
Archived
</NavLink>
As written, both tabs stay active on their own nested detail pages (/tickets/41, /archived/9) - correct for Tickets, wrong for Archived.
What to do: Write SupportNav, with end only on the Archived link (not Tickets), nested routes for /tickets โ /tickets/:ticketId and /archived โ /archived/:ticketId, and prove with toHaveClass/not.toHaveClass that visiting /tickets/41 leaves Tickets active, while visiting /archived/9 leaves Archived not active.
Sample output (really run):
"/tickets/41" -> Tickets tab: active (no end - nested routes keep it lit)
"/archived/9" -> Archived tab: not active (end - exact match only)
๐ก Hint: Section 4's NavBarDefault/NavBarWithEnd pair is this exact shape - one tab left without end on purpose, one with it, same nested-route structure, different intent for each.
Exercise 4: A size filter kept in the URL, plus a post-purchase redirect
Scenario: A Myntra-style product page needs a size filter that survives a refresh and a "Buy now" button that moves the user to a confirmation page once the purchase completes - with nobody clicking a link for that second part.
What to do: Write SizeFilter using useSearchParams (sizes "S", "M", "L"; default "M" when no ?size is present) showing stock for the selected size from a small hardcoded lookup, and BuyNowButton({ productId }) using useNavigate to go to /orders/${productId}/confirmation on click. Wire both into a small ProductApp with a confirmation route reading productId from useParams.
Sample output (really run):
land on "/product?size=L" -> shows L's stock, no click needed
click "Buy now" (product p9) -> "/orders/p9/confirmation", "Thanks for your order!"
๐ก Hint: this is examples/05_usenavigate_and_search_params.jsx's two halves combined on a new domain - replace the whole search-params object on each filter change, and reserve useNavigate for the post-click action, not the filter clicks themselves.
Exercise 5: A routed train-status page, fetching its own data - no loader
Scenario: An IRCTC-style app needs /trains/:trainId/status to show a train's live running status, fetched from the network - using this course's Part 11 pattern, not a router loader, and cancelling a stale request the same way Part 11 did.
What to do: Write useTrainStatus(trainId) (loading/error/success modeled as one state value, AbortController passed to fetch, aborted from the effect's cleanup) and TrainStatusPage, reading trainId from useParams and calling the hook with it. Mount it at /trains/:trainId/status inside a MemoryRouter, and in the test: stub fetch to resolve a status for one id, assert the loading text appears first and the resolved status after; stub a failing response for a second id and assert the error branch; and prove the previous request is aborted by changing the route's trainId param mid-test (rerender with a new initialEntries or a route change) and checking the abort happened, the same technique examples/06_fetching_in_a_routed_page.test.jsx and Part 11 Section 3 both use.
Sample output (really run):
land on "/trains/12952/status" -> "Loading train 12952..." then "12952: Running on time"
land on "/trains/00000/status" -> error alert, "train 00000 not found"
๐ก Hint: examples/06_fetching_in_a_routed_page.jsx is this exact shape on a different domain - the only thing that changes with the route is where the id comes from, never how the fetch itself is modeled.
Exercise 6: Find and fix an open-redirect bug in a protected admin route
Scenario: A teammate wrote a protected /admin route, but a security reviewer flagged the redirect as unsafe:
function RequireAdmin({ isAdmin }) {
const location = useLocation();
if (!isAdmin) {
// BUG: "next" is taken straight from the URL's own query string, unvalidated,
// and used as-is - whatever the visitor's link said, this redirects to.
const params = new URLSearchParams(location.search);
const next = params.get("next") ?? "/";
return <Navigate to={next} />;
}
return <Outlet />;
}
A crafted link to /admin?next=https://evil.example.com sends a signed-in visitor to an attacker's site immediately after this component ever redirects to that value (for example, after a later login step reads the same next).
What to do: Write RequireAdminBroken (the code above, unchanged) and RequireAdminFixed, which builds its own next from location.pathname the way examples/07_not_found_and_protected_route.jsx's RequireAuth does (never trusting an incoming next query param at all), redirects with replace, and only ever points next at a same-site path. Add a catch-all 404 route to the same app, and prove both: the 404 for an unmatched URL, and that RequireAdminFixed's redirect never produces an off-site URL even when the test renders it at a path containing a crafted ?next=https://evil.example.com.
Sample output (really run):
RequireAdminBroken: redirects to whatever "next" the URL claims, including an off-site one - the bug
RequireAdminFixed: always redirects to "/login?next=%2Fadmin", built from the real path, ignoring any incoming "next"
Unmatched URL: 404 - page not found
๐ก Hint: Section 7 names the rule directly - never build a post-login redirect from a value the visitor's own URL supplied; build next yourself from location.pathname, and validate anything you must accept from outside as a same-site path starting with a single /.
Show the solutions for Part 15 (12 files)
solutions/ex01_bookmyshow_routes.jsx
// Exercise 1 solution: same shape as examples/01_basic_routes_and_links.jsx -
// two routes, a nav of Links, nothing else.
import { Link, Route, Routes } from "react-router";
function Home() {
return <h1>BookMyShow Lite</h1>;
}
function Movies() {
return <h1>Now showing</h1>;
}
export function BookMyShowApp() {
return (
<div>
<nav>
<Link to="/">Home</Link>
<Link to="/movies">Movies</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/movies" element={<Movies />} />
</Routes>
</div>
);
}
solutions/ex01_bookmyshow_routes.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { MemoryRouter } from "react-router";
import { BookMyShowApp } from "./ex01_bookmyshow_routes.jsx";
describe("BookMyShowApp", () => {
it("really shows Home at / and switches to Movies after clicking the link", async () => {
const user = userEvent.setup();
render(
<MemoryRouter initialEntries={["/"]}>
<BookMyShowApp />
</MemoryRouter>,
);
expect(screen.getByRole("heading", { name: "BookMyShow Lite" })).toBeInTheDocument();
await user.click(screen.getByRole("link", { name: "Movies" }));
expect(screen.getByRole("heading", { name: "Now showing" })).toBeInTheDocument();
expect(screen.queryByRole("heading", { name: "BookMyShow Lite" })).not.toBeInTheDocument();
});
});
solutions/ex02_ola_driver_dashboard.jsx
// Exercise 2 solution: same shape as examples/02_nested_routes_and_layout.jsx -
// one layout route with an Outlet, one index child, one named child.
import { Link, Outlet, Route, Routes } from "react-router";
function DriverLayout() {
return (
<div>
<h1>Driver dashboard</h1>
<nav>
<Link to="/driver">Today's trips</Link>
<Link to="/driver/earnings">Earnings</Link>
</nav>
<Outlet />
</div>
);
}
function TodaysTrips() {
return <p>3 trips today</p>;
}
function Earnings() {
return <p>โน1,240 so far today</p>;
}
export function DriverApp() {
return (
<Routes>
<Route path="/driver" element={<DriverLayout />}>
<Route index element={<TodaysTrips />} />
<Route path="earnings" element={<Earnings />} />
</Route>
</Routes>
);
}
solutions/ex02_ola_driver_dashboard.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { MemoryRouter } from "react-router";
import { DriverApp } from "./ex02_ola_driver_dashboard.jsx";
describe("DriverApp's layout plus Outlet", () => {
it("really keeps the dashboard heading mounted while only the Outlet's content swaps", async () => {
const user = userEvent.setup();
render(
<MemoryRouter initialEntries={["/driver"]}>
<DriverApp />
</MemoryRouter>,
);
expect(screen.getByRole("heading", { name: "Driver dashboard" })).toBeInTheDocument();
expect(screen.getByText("3 trips today")).toBeInTheDocument();
await user.click(screen.getByRole("link", { name: "Earnings" }));
expect(screen.getByRole("heading", { name: "Driver dashboard" })).toBeInTheDocument();
expect(screen.getByText("โน1,240 so far today")).toBeInTheDocument();
expect(screen.queryByText("3 trips today")).not.toBeInTheDocument();
});
});
solutions/ex03_navlink_end_bug.jsx
// Exercise 3 solution: same shape as examples/04_navlink_active_state.jsx -
// Tickets has no `end`, so it stays active across its own nested detail
// route; Archived has `end`, so it switches off the moment the URL moves
// to one specific archived ticket's own page.
import { NavLink, Route, Routes } from "react-router";
function TicketsHome() {
return <h1>All tickets</h1>;
}
function TicketDetail() {
return <h1>Ticket #41</h1>;
}
function ArchivedHome() {
return <h1>Archived tickets</h1>;
}
function ArchivedDetail() {
return <h1>Archived ticket #9</h1>;
}
export function SupportNav() {
return (
<nav>
<NavLink to="/tickets" className={({ isActive }) => (isActive ? "active" : "")}>
Tickets
</NavLink>
<NavLink to="/archived" end className={({ isActive }) => (isActive ? "active" : "")}>
Archived
</NavLink>
</nav>
);
}
export function SupportApp() {
return (
<div>
<SupportNav />
<Routes>
<Route path="/tickets" element={<TicketsHome />} />
<Route path="/tickets/:ticketId" element={<TicketDetail />} />
<Route path="/archived" element={<ArchivedHome />} />
<Route path="/archived/:ticketId" element={<ArchivedDetail />} />
</Routes>
</div>
);
}
solutions/ex03_navlink_end_bug.test.jsx
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { MemoryRouter } from "react-router";
import { SupportApp } from "./ex03_navlink_end_bug.jsx";
describe("Tickets (no end) staying active on its own nested detail route", () => {
it("really leaves Tickets active while viewing one specific ticket", () => {
render(
<MemoryRouter initialEntries={["/tickets/41"]}>
<SupportApp />
</MemoryRouter>,
);
expect(screen.getByRole("heading", { name: "Ticket #41" })).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Tickets" })).toHaveClass("active");
});
});
describe("Archived (with end) switching off on its own nested detail route", () => {
it("really turns Archived off while viewing one specific archived ticket", () => {
render(
<MemoryRouter initialEntries={["/archived/9"]}>
<SupportApp />
</MemoryRouter>,
);
expect(screen.getByRole("heading", { name: "Archived ticket #9" })).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Archived" })).not.toHaveClass("active");
});
it("really still marks Archived active at its own exact URL", () => {
render(
<MemoryRouter initialEntries={["/archived"]}>
<SupportApp />
</MemoryRouter>,
);
expect(screen.getByRole("link", { name: "Archived" })).toHaveClass("active");
});
});
solutions/ex04_size_filter_and_buy_now.jsx
// Exercise 4 solution: the two halves of examples/05_usenavigate_and_search_params.jsx
// combined on a new domain - a filter kept in useSearchParams, and a
// post-click navigate() reserved for the action, not the filter clicks.
import { Route, Routes, useNavigate, useParams, useSearchParams } from "react-router";
const STOCK = { S: 2, M: 8, L: 0 };
export function SizeFilter() {
const [searchParams, setSearchParams] = useSearchParams();
const size = searchParams.get("size") ?? "M";
return (
<div>
<div role="group" aria-label="size filter">
{["S", "M", "L"].map((s) => (
<button key={s} onClick={() => setSearchParams({ size: s })}>
{s}
</button>
))}
</div>
<p>
Size {size}: {STOCK[size]} in stock
</p>
</div>
);
}
export function BuyNowButton({ productId }) {
const navigate = useNavigate();
return <button onClick={() => navigate(`/orders/${productId}/confirmation`)}>Buy now</button>;
}
function OrderConfirmation() {
const { productId } = useParams();
return <h1>Thanks for your order! ({productId})</h1>;
}
export function ProductApp() {
return (
<Routes>
<Route path="/product" element={<SizeFilter />} />
<Route path="/orders/:productId/confirmation" element={<OrderConfirmation />} />
</Routes>
);
}
export function ProductPageWithBuyButton({ productId }) {
return (
<Routes>
<Route path="/product" element={<BuyNowButton productId={productId} />} />
<Route path="/orders/:productId/confirmation" element={<OrderConfirmation />} />
</Routes>
);
}
solutions/ex04_size_filter_and_buy_now.test.jsx
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { MemoryRouter } from "react-router";
import { ProductApp, ProductPageWithBuyButton } from "./ex04_size_filter_and_buy_now.jsx";
import userEvent from "@testing-library/user-event";
describe("SizeFilter kept in useSearchParams", () => {
it("really pre-filters from a URL that already has ?size, with no click needed", () => {
render(
<MemoryRouter initialEntries={["/product?size=L"]}>
<ProductApp />
</MemoryRouter>,
);
expect(screen.getByText("Size L: 0 in stock")).toBeInTheDocument();
});
it("really defaults to M with no ?size in the URL at all", () => {
render(
<MemoryRouter initialEntries={["/product"]}>
<ProductApp />
</MemoryRouter>,
);
expect(screen.getByText("Size M: 8 in stock")).toBeInTheDocument();
});
});
describe("BuyNowButton's useNavigate, reserved for the post-click action", () => {
it("really lands on that product's confirmation route after Buy now", async () => {
const user = userEvent.setup();
render(
<MemoryRouter initialEntries={["/product"]}>
<ProductPageWithBuyButton productId="p9" />
</MemoryRouter>,
);
await user.click(screen.getByRole("button", { name: "Buy now" }));
expect(screen.getByRole("heading", { name: "Thanks for your order! (p9)" })).toBeInTheDocument();
});
});
solutions/ex05_train_status_page.jsx
// Exercise 5 solution: examples/06_fetching_in_a_routed_page.jsx's exact
// shape on a new domain - a routed page fetches its own data in a
// useEffect with AbortController, reading the id from useParams. No router
// loader anywhere here, same as every other fetch in this course.
import { useEffect, useState } from "react";
import { Link, Route, Routes, useParams } from "react-router";
export function useTrainStatus(trainId) {
const [state, setState] = useState({ phase: "loading" });
useEffect(() => {
const controller = new AbortController();
setState({ phase: "loading" });
fetch(`/api/trains/${trainId}/status`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`train ${trainId} not found`);
return res.json();
})
.then((train) => setState({ phase: "success", data: train }))
.catch((error) => {
if (error.name === "AbortError") return; // cancelled on purpose
setState({ phase: "error", message: error.message });
});
return () => controller.abort();
}, [trainId]);
return state;
}
export function TrainStatusPage() {
const { trainId } = useParams();
const state = useTrainStatus(trainId);
if (state.phase === "loading") return <p>Loading train {trainId}...</p>;
if (state.phase === "error") return <p role="alert">{state.message}</p>;
return (
<p>
{state.data.id}: {state.data.status}
</p>
);
}
// Used only to prove the abort-on-navigation behaviour: two links to two
// different trainIds, so clicking from one to the other unmounts/reruns
// TrainStatusPage's effect and aborts whichever request was still pending.
export function TrainStatusApp() {
return (
<div>
<nav>
<Link to="/trains/12952/status">12952</Link>
<Link to="/trains/12953/status">12953</Link>
</nav>
<Routes>
<Route path="/trains/:trainId/status" element={<TrainStatusPage />} />
</Routes>
</div>
);
}
solutions/ex05_train_status_page.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { MemoryRouter, Route, Routes } from "react-router";
import { TrainStatusApp, TrainStatusPage } from "./ex05_train_status_page.jsx";
afterEach(() => {
vi.unstubAllGlobals();
});
function renderAt(path) {
render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/trains/:trainId/status" element={<TrainStatusPage />} />
</Routes>
</MemoryRouter>,
);
}
describe("TrainStatusPage fetching its own data from useParams, no loader", () => {
it("really shows loading, then the fetched status, for the id in the URL", async () => {
vi.stubGlobal(
"fetch",
vi.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve({ id: "12952", status: "Running on time" }),
}),
),
);
renderAt("/trains/12952/status");
expect(screen.getByText("Loading train 12952...")).toBeInTheDocument();
expect(await screen.findByText("12952: Running on time")).toBeInTheDocument();
});
it("really shows the error branch for a train id the fetch rejects", async () => {
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve({ ok: false })));
renderAt("/trains/00000/status");
expect(await screen.findByRole("alert")).toHaveTextContent("train 00000 not found");
});
it("really aborts the previous train's request when navigating to a different trainId", async () => {
let firstSignal;
vi.stubGlobal(
"fetch",
vi.fn((url, options) => {
if (url.includes("12952")) {
firstSignal = options.signal;
return new Promise(() => {}); // never resolves - still "in flight"
}
return Promise.resolve({
ok: true,
json: () => Promise.resolve({ id: "12953", status: "Delayed by 20 min" }),
});
}),
);
const user = userEvent.setup();
render(
<MemoryRouter initialEntries={["/trains/12952/status"]}>
<TrainStatusApp />
</MemoryRouter>,
);
expect(screen.getByText("Loading train 12952...")).toBeInTheDocument();
expect(firstSignal.aborted).toBe(false);
await user.click(screen.getByRole("link", { name: "12953" }));
// The route change reruns the effect, whose cleanup aborts the stale
// 12952 request before the new 12953 one starts - the same guarantee
// examples/06_fetching_in_a_routed_page.jsx relies on.
expect(firstSignal.aborted).toBe(true);
expect(await screen.findByText("12953: Delayed by 20 min")).toBeInTheDocument();
});
});
solutions/ex06_admin_open_redirect_fix.jsx
// Exercise 6 solution: RequireAdminBroken is the teammate's code, unchanged -
// it trusts an incoming ?next query param completely. RequireAdminFixed
// never reads that param at all; it builds "next" itself from the real
// pathname, exactly like examples/07_not_found_and_protected_route.jsx's
// RequireAuth, so a crafted ?next= value in the URL can't influence anything.
import { Navigate, Outlet, Route, Routes, useLocation } from "react-router";
function AdminHome() {
return <h1>Admin tools</h1>;
}
function Login() {
const location = useLocation();
const next = new URLSearchParams(location.search).get("next");
return <p>Please sign in{next ? ` to continue to ${next}` : ""}</p>;
}
function NotFound() {
return <p role="alert">404 - page not found</p>;
}
export function RequireAdminBroken({ isAdmin }) {
const location = useLocation();
if (!isAdmin) {
const params = new URLSearchParams(location.search);
const next = params.get("next") ?? "/";
return <Navigate to={next} />;
}
return <Outlet />;
}
export function RequireAdminFixed({ isAdmin }) {
const location = useLocation();
if (!isAdmin) {
const next = encodeURIComponent(location.pathname);
return <Navigate to={`/login?next=${next}`} replace />;
}
return <Outlet />;
}
export function BrokenAdminApp({ isAdmin }) {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<RequireAdminBroken isAdmin={isAdmin} />}>
<Route path="/admin" element={<AdminHome />} />
</Route>
</Routes>
);
}
export function FixedAdminApp({ isAdmin }) {
return (
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<RequireAdminFixed isAdmin={isAdmin} />}>
<Route path="/admin" element={<AdminHome />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
);
}
solutions/ex06_admin_open_redirect_fix.test.jsx
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { MemoryRouter, Route, Routes } from "react-router";
import { FixedAdminApp, RequireAdminBroken } from "./ex06_admin_open_redirect_fix.jsx";
function AttackerPage() {
return <h1>You have been redirected here by an attacker-chosen link</h1>;
}
describe("RequireAdminBroken trusting an incoming ?next unvalidated - the bug", () => {
it("really redirects wherever a crafted ?next query param says, not a path it decided itself", () => {
// MemoryRouter can't perform a real cross-origin browser navigation (there
// is no real address bar in a test), but the bug is the same regardless
// of destination: the broken guard hands Navigate a path it never chose
// or validated itself. Routing a crafted ?next straight to an
// "attacker" page inside this same test app proves the guard has zero
// control over where a signed-out visitor actually lands.
render(
<MemoryRouter initialEntries={["/admin?next=/attacker-page"]}>
<Routes>
<Route path="/attacker-page" element={<AttackerPage />} />
<Route element={<RequireAdminBroken isAdmin={false} />}>
<Route path="/admin" element={<h1>Admin tools</h1>} />
</Route>
</Routes>
</MemoryRouter>,
);
expect(
screen.getByRole("heading", { name: "You have been redirected here by an attacker-chosen link" }),
).toBeInTheDocument();
});
});
describe("RequireAdminFixed building next itself, ignoring any incoming next", () => {
it("really redirects to /login?next=%2Fadmin regardless of a crafted ?next in the URL", () => {
render(
<MemoryRouter initialEntries={["/admin?next=/attacker-page"]}>
<FixedAdminApp isAdmin={false} />
</MemoryRouter>,
);
// The real path (/admin) is what ends up in "next" - the crafted query
// param on the original URL is never read by RequireAdminFixed at all.
expect(screen.getByText("Please sign in to continue to /admin")).toBeInTheDocument();
});
it("really renders the admin page for a signed-in admin, with no redirect", () => {
render(
<MemoryRouter initialEntries={["/admin"]}>
<FixedAdminApp isAdmin={true} />
</MemoryRouter>,
);
expect(screen.getByRole("heading", { name: "Admin tools" })).toBeInTheDocument();
});
it("really shows the 404 page for a URL no route matches", () => {
render(
<MemoryRouter initialEntries={["/does-not-exist"]}>
<FixedAdminApp isAdmin={false} />
</MemoryRouter>,
);
expect(screen.getByRole("alert")).toHaveTextContent("404 - page not found");
});
});
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Reaching for a router loader the first time a routed page needs data |
Introduces a second, different data-fetching pattern into a course that already taught one by hand in Part 11, for no reason beyond "this page happens to have a route" | Fetch in a useEffect with AbortController, reading the id from useParams instead of a prop - Section 6 |
Adding end to a parent-section NavLink and expecting the tab to stay lit while browsing one of its items |
end requires an exact match only - it switches a parent tab off the moment the URL moves to a nested detail page below it, which is usually the opposite of what a "section" tab should do |
Leave end off for a tab that should stay active across its own nested routes; add it only where "exactly this page, nothing nested" is the actual intent - Section 4 |
Keeping a filter/search choice in useState instead of useSearchParams |
The filter silently resets on every refresh, and the current result can't be shared as a link, because neither is encoded in the URL | Read and set it through useSearchParams instead - Section 5 |
Reaching for useNavigate to handle an ordinary link click |
Loses the free behavior a real <a>-backed <Link> gives for keyboard, right-click-to-open-in-new-tab, and accessibility |
Use <Link>/<NavLink> for anything the user actually clicks; reserve useNavigate for moving them after something else finished - Section 5 |
Treating a client-side RequireAuth redirect as real access control |
Any check running in the user's own browser can be bypassed by whoever controls that browser - it only ever shapes what renders | Enforce the real check again wherever the protected data is actually served; the client-side guard is UI only - Section 7 |
Building a login page's post-login redirect from a raw, un-validated next value |
A crafted link can set next to an attacker's own site and silently redirect a user there right after they sign in - an open redirect |
Accept next only as a same-site path starting with / (never // or a full URL), and build it with encodeURIComponent as shown - Section 7 |
Testing a routed component with createMemoryRouter because an older tutorial used it |
createMemoryRouter builds a Data-mode router object for <RouterProvider> - it doesn't match a component built from plain <Routes>/<Route> JSX |
Use <MemoryRouter initialEntries={[...]}> for anything written in Declarative mode - Section 8 |
Quick recap
<Routes>/<Route>map a URL path to an element;<Link>changes that URL without a page reload. Nested<Route>s inherit their parent's path and render through that parent's<Outlet/>, which keeps the parent's own chrome mounted while only the Outlet's content swaps.- A layout route (a parent
<Route>with nopath) groups children under shared UI with no extra URL segment; anindexroute is the child that renders at the parent's own URL. useParamsreads a dynamic:segmentstraight from the current URL;NavLink'sisActivehighlights the current tab, by default staying active across that tab's own nested routes too -endopts out of that, for a tab that should mean "exactly this page."useSearchParamskeeps filter/query state in the URL - shareable, survives a refresh - unlike the same thing inuseState;useNavigatemoves the user after something else finishes, not as a substitute for a<Link>click.- This course's deliberate choice: a routed page fetches its own data in a
useEffectwithAbortController, readinguseParamsinstead of a prop - Part 11's exact pattern, no routerloaderanywhere in this part, because React Router v7+'s Declarative mode (what this course installs and teaches) simply doesn't have one. - A catch-all
path="*"route handles unmatched URLs; a "protected route" is a plain component rendering<Outlet/>or<Navigate/>- not a special router feature, and not real access control on its own. - Test a Declarative-mode component with
<MemoryRouter initialEntries={[...]}>, notcreateMemoryRouter(a Data-mode API for a different kind of app).
Checklist
- I can say, in one sentence, which of React Router's three modes this course teaches and why (Section 0).
- I built nested routes with a shared layout and an
<Outlet/>, and proved the parent's own chrome stays mounted while only the Outlet's content changes between two child routes. - I read a dynamic
:segmentwithuseParamsand showed a not-found branch for an id with no match, instead of crashing. - I can explain what
enddoes on aNavLinkand reproduced it directly: a parent-section tab staying active on a nested detail route by default, then switching off onceendis added. - I kept a filter choice in
useSearchParamsinstead ofuseState, and proved landing directly on a URL with that query param already pre-filters, with no click needed. - I wrote a routed page that fetches its own data with Part 11's
useEffect/AbortControllerpattern, reading the id fromuseParams, with no router loader involved. - I wrote a catch-all 404 route and a
RequireAuth-style protected route that redirects a signed-out visitor to/login?next=...withreplace, and can say why that redirect is UI-only, not real security. - I tested a Declarative-mode routed component with
MemoryRouterandinitialEntries, and can say whycreateMemoryRouterwould have been the wrong tool here.