Authorization in Remix and React Router v7 with Route Middleware

- Share:





3366 Members
If your Remix auth tutorial still talks about the old remix package loaders as if that were the current stack, it is out of date. Remix's framework functionality lives in React Router framework mode. Route middleware is on by default in React Router v8. On v7, it is available from 7.9 when you enable the future.v8_middleware flag, which is also the first step of the v7 to v8 upgrade. Authentication libraries typically cover sign-in, and sometimes coarse roles. Resource-level permissions are still left to you.
This post is for a developer with an app in progress who needs to protect loaders and actions. You will put the authenticated user into typed context with route middleware, then call permit.check() in each loader and action. Hiding a button never protects the data behind it.
Remix v2's framework features moved into React Router. Framework mode still gives you file-based routes, loaders, and actions. The mental model that matters for authorization did not shrink: every loader and every action is an HTTP endpoint. A client can call them without rendering your route component.
Middleware is the right place to establish identity once for a subtree. It is the wrong place to assume a single parent check covers every child endpoint. Parent middleware can redirect unauthenticated users. Child loaders still need their own permission checks for the resources they return.
On React Router v7 (7.9 or later), enable middleware in react-router.config.ts. On v8 you can skip this step:
import type { Config } from "@react-router/dev/config";
export default {
future: {
v8_middleware: true,
},
} satisfies Config;
Middleware also changes the shape of context on loaders and actions. Use createContext from react-router instead of stuffing ad-hoc fields onto the old context object.
Create a typed context key and a middleware that resolves the session:
// app/context.ts
import { createContext } from "react-router";
export type AppUser = { id: string; email: string };
export const userContext = createContext<AppUser | null>(null);
// app/routes/_app.tsx
import { redirect } from "react-router";
import type { Route } from "./+types/_app";
import { userContext } from "~/context";
import { getUserFromSession } from "~/auth.server";
async function authMiddleware({ request, context }: Route.MiddlewareArgs) {
const user = await getUserFromSession(request);
if (!user) {
throw redirect("/login");
}
context.set(userContext, user);
}
export const middleware: Route.MiddlewareFunction[] = [authMiddleware];
Loaders under _app can read context.get(userContext) without re-parsing the cookie. That is authentication plumbing. Authorization still happens next to the data.
Set up the Permit SDK once, pointed at a local PDP so checks stay on the request path:
// app/permit.server.ts
import { Permit } from "permitio";
export const permit = new Permit({
token: process.env.PERMIT_API_KEY!,
pdp: process.env.PERMIT_PDP_URL ?? "http://localhost:7766",
});
A documents loader that only trusted the parent auth middleware would still leak rows. Check the action and resource:
// app/routes/documents.$id.tsx
import { data } from "react-router";
import type { Route } from "./+types/documents.$id";
import { userContext } from "~/context";
import { permit } from "~/permit.server";
import { getDocument } from "~/db.server";
export async function loader({ params, context }: Route.LoaderArgs) {
const user = context.get(userContext)!;
const documentId = params.id!;
const allowed = await permit.check(user.id, "read", {
type: "document",
key: documentId,
});
if (!allowed) {
throw data({ message: "Forbidden" }, { status: 403 });
}
const document = await getDocument(documentId);
return { document };
}
export async function action({ request, params, context }: Route.ActionArgs) {
const user = context.get(userContext)!;
const documentId = params.id!;
const form = await request.formData();
const intent = String(form.get("intent") ?? "update");
const allowed = await permit.check(user.id, intent, {
type: "document",
key: documentId,
});
if (!allowed) {
throw data({ message: "Forbidden" }, { status: 403 });
}
// mutate...
return { ok: true };
}
Same pattern for list routes: scope the query by tenant in the database first, then apply permission filters or an authorized-query pattern. Do not load every tenant's rows into memory and hide cards in JSX.
For the Express-shaped version of this idea, see Implement RBAC authorization in Express. For why the check belongs at a PEP talking to a PDP, see PEP, PDP, and decision logs.
Most apps begin with roles such as admin, editor, and viewer. Map those in the Permit control plane, assign users to roles per tenant, and keep the check call identical.
When "editor" still means different things on different documents, add attributes or relationships. Example: allow update only when the document's owner_id matches the user, or when the user is an editor on the parent project. The loader still calls permit.check. The policy grows in the control plane, not as nested if statements in every route module.
Run a PDP next to the app (sidecar or local process) so each check avoids a remote network hop. In Permit's hybrid model the Edge PDP evaluates locally while OPAL distributes policy and data updates in the background. As shared in our PDP overview, when the PDP runs as a sidecar on the same host, checks travel over loopback, carry no network latency, and stay in the sub-millisecond range.
Loaders can return a small permission map for the current resource so the UI can hide impossible actions without inventing a second policy:
export async function loader({ params, context }: Route.LoaderArgs) {
const user = context.get(userContext)!;
const documentId = params.id!;
const resource = { type: "document", key: documentId };
const [canRead, canUpdate, canDelete] = await Promise.all([
permit.check(user.id, "read", resource),
permit.check(user.id, "update", resource),
permit.check(user.id, "delete", resource),
]);
if (!canRead) {
throw data({ message: "Forbidden" }, { status: 403 });
}
return {
document: await getDocument(documentId),
permissions: { canUpdate, canDelete },
};
}
Use those flags for buttons and menus only. The action that performs delete must check again. A forged form post will not care what the previous loader returned.
Most authorization bugs show up in specific role and route combinations. For each protected loader and action, assert at least:
Keep fixtures small: three users, one document owned by user A, one shared with user B as viewer. Run them in CI on every policy change.
future.v8_middleware (v8 has middleware on by default), and put the session user in createContext.permit.check(user, action, resource) before reads and writes.Route middleware removes most of the auth boilerplate in React Router v7 and v8. Permission checks still go in each loader and action, next to the data, and the policy stays out of your JSX.

Full-Stack Software Technical Leader | Security, JavaScript, DevRel, OPA | Writer and Public Speaker