# Add Protected Routes to a React Router App

Yes. An agent adds a cookie session, a login route and a layout whose middleware redirects signed-out visitors, then typechecks and builds it in its own sandbox.

[Run this on Rush](https://cloud.getrush.ai/run/add-protected-routes/react-router/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts from the version it is working with, because protected routes are written differently in React Router 7 and 8. In the default template of remix-run/react-router-templates, `package.json` asks for `react-router` at `*`, and `pnpm-lock.yaml` resolves that to 8.4.0 together with `@react-router/node`, `@react-router/serve` and `@react-router/dev`, on React 19.2.8 and Vite 8.0.3. The installed `CHANGELOG.md` for that release says middleware is always on in v8, that the `future.v8_middleware` flag is gone, and that the `context` a loader, action or middleware receives is always a `RouterContextProvider`. So the guard is a route middleware, not a check copied into every loader. `app/routes.ts` has one entry, `index("routes/home.tsx")`, `app/root.tsx` renders an `Outlet` inside `Layout`, and `react-router.config.ts` keeps `ssr: true`, so the middleware runs on the server for document requests and `.data` requests.

It adds the session first. `app/session.server.ts` calls `createCookieSessionStorage` with an `httpOnly` cookie, `sameSite: "lax"`, `secure` outside development and a secret read from `SESSION_SECRET`, and exports `getSession`, `commitSession` and `destroySession`. `app/context.ts` exports `userContext = createContext<User | null>(null)`, the typed context the middleware guide in the package's own `docs/how-to/middleware.md` recommends over writing properties onto `context`. The template has no user store, so the agent adds a small `app/users.server.ts` with one function that checks a username and password against environment variables, written so the reader can replace it with a database lookup without touching the routes.

Then the routes. `app/routes.ts` gains `route("login", "routes/login.tsx")`, `route("logout", "routes/logout.tsx")` and a `layout("routes/protected.tsx", [route("dashboard", "routes/dashboard.tsx")])`. `routes/protected.tsx` exports a `middleware` array with one function: it reads the session from the request, throws `redirect("/login?redirectTo=...")` with the requested path when there is no user id, and otherwise calls `context.set(userContext, user)`. It also exports a `loader` that returns `null`. That loader is not decoration: the guide explains that server middleware only runs on a client-side navigation when the route makes a `.data` request, so without a loader a signed-out visitor could reach a child route that has no loader of its own. `routes/login.tsx` has an `action` that verifies the credentials, writes the user id into the session and redirects with a `Set-Cookie` header from `commitSession`; `routes/logout.tsx` is an action-only route that calls `destroySession`. `routes/dashboard.tsx` reads the user with `context.get(userContext)` in its loader and shows it.

Last, it proves the change the way the repository does. The template's `typecheck` script runs `react-router typegen && tsc`, so the generated `Route.MiddlewareFunction` and `Route.LoaderArgs` types under `.react-router/types` are checked, not assumed. The agent runs `npm run typecheck` and `npm run build`, starts `npm run start` on the built server and requests `/dashboard` with no cookie to see the 302 to `/login`, then signs in and requests it again. The repository's own `.tests/test.default.ts` drives the template with Playwright through `pnpm typecheck`, `pnpm dev` and `pnpm build` plus `pnpm start` and asserts an empty `stderr`, so the agent runs that suite too and keeps the empty-stderr expectation.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add protected routes to this React Router app. Read package.json and the lockfile to confirm the react-router version, then read app/routes.ts, app/root.tsx, react-router.config.ts, vite.config.ts and the middleware and sessions docs inside node_modules/react-router/docs before writing anything. Use the route middleware that is always enabled in v8, not per-loader checks. Add app/session.server.ts with createCookieSessionStorage (httpOnly, sameSite lax, secure outside development, secret from SESSION_SECRET), app/context.ts with a typed userContext from createContext, a small users.server.ts that checks credentials from environment variables, a login route with an action, a logout action route, and a layout route routes/protected.tsx whose middleware redirects to /login with a redirectTo param when there is no session user and sets the user on context otherwise. Give that layout a loader that returns null so the middleware also runs on client navigations, and say in the pull request why. Put a dashboard route under the layout that reads the user from context. Run npm run typecheck, npm run build, then start the built server and show the 302 for /dashboard without a cookie and the 200 after signing in. Run the repository's Playwright suite under .tests if it exists. Paste the output in the pull request and open it.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that adds `app/session.server.ts`, `app/context.ts`, `app/users.server.ts`, four files under `app/routes/` and the new entries in `app/routes.ts`, and changes nothing in `app/root.tsx`. The description quotes the typecheck and build output, the two `curl` exchanges against the built server, one 302 with a `Location` of `/login?redirectTo=/dashboard` and one 200 with the dashboard body, and names `SESSION_SECRET` as the one variable a deployment must set, with a note in the `Dockerfile` section of the README.

A reviewer reads `routes/protected.tsx` first and checks two things the types cannot: that the redirect carries the original path so a sign-in returns the visitor where they were, and that every route that must be private sits under that `layout()` entry, since a route added beside it later is public by default. Then they read `users.server.ts` and decide what replaces the environment-variable check, which is the part the agent left deliberately small.

They also check how the app is served. The middleware runs on the server, so an app switched to `ssr: false` later would lose it; the pull request says so and points at `clientMiddleware` as the place a client-only guard would go.

## Run it on every Linear issue labelled auth

Once the layout exists, each later request is a route to move under it or a rule to add to the middleware. In the console, add an automation on the Project that holds the repository with a `linear` trigger on `linear.issue.labeled` and the label `auth`, and a prompt that says: move the route the issue names under the protected layout, or add the check it describes to the middleware in routes/protected.tsx, run typecheck and build, and open a pull request. The issue is placed after the prompt as the event and fills in nothing, so the route name comes from the issue text. The trigger needs a Linear connection for the automation's runner and fires only when the label is applied by someone in your Rush org.

## Why run it on Rush?

What goes wrong in this job is not the redirect, which is three lines, but the behaviour of middleware in the version you have: whether it runs on a client-side navigation to a route with no loader, what `context` is, and whether the generated route types accept the function you wrote. The agent reads the answers from the installed package's own changelog and docs, and then checks them by running the built server, in a sandbox that holds your lockfile's versions and nothing else.

Every command it ran stays in the run's transcript at `GET /o/{org}/sessions/{id}/messages`, command and output together, and the files it changed are listed with their diff at `GET /o/{org}/p/{project}/sessions/{id}/changes`. When the pull request says the 302 happened without a cookie and the 200 happened with one, the two responses are there to read, which is a better basis for merging than a description of what the code should do.

## Frequently asked questions

### Why a middleware and not a check at the top of each loader?

Because React Router 8 always runs route middleware, and a middleware on a layout route covers every child, including children added later. The installed `CHANGELOG.md` records that the `future.v8_middleware` flag was removed and middleware is always enabled, so there is no flag to turn on. A per-loader check has to be remembered on every new route.

### Why does the protected layout export a loader that only returns null?

The package's middleware guide says server middleware runs on a client-side navigation only when that navigation makes a `.data` request, which happens when a route in the match has a loader or action. The empty loader forces that request, so a signed-out visitor is redirected on navigation and not only on a full page load.

### Does it work with SPA mode?

Not as written. The guard is a server middleware and `react-router.config.ts` in this template keeps `ssr: true`. With `ssr: false` there is no server to run it; the equivalent is a `clientMiddleware` export, which runs in the browser on every client navigation, and a session that lives somewhere the client can read.

### Where do the users come from?

The template has none, so the agent adds a single credential check read from environment variables and keeps it in one file. The routes call one function with a username and password and get a user or `null` back, so replacing it with a database query changes that file only.

## More React Router jobs

- [Add PWA Support to a React Router v7 App](https://getrush.ai/run/add-pwa-support/react-router/)
- [Add Rate Limiting to a React Router App](https://getrush.ai/run/add-rate-limiting/react-router/)
- [Add Request ID Logging to a React Router App](https://getrush.ai/run/add-request-id-logging/react-router/)

## More jobs like this: Turn a Linear label into a PR

- [Add Pull to Refresh to a React Native List from a Linear Issue](https://getrush.ai/run/add-pull-to-refresh/react-native/)
- [Add Push Notifications to an Expo App from a Linear Issue](https://getrush.ai/run/add-push-notifications/expo/)
- [Add Push Notifications to a React Native App](https://getrush.ai/run/add-push-notifications/react-native/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
