TanStack Start Authorization: Protect Server Functions with Middleware

- Share:





3366 Members
TanStack Start 1.0 is stable. Its own docs are blunt about security boundaries: a route guard is not a data authorization boundary. Server functions created with createServerFn are API endpoints. They are reachable without loading the route that happens to call them, so beforeLoad can only handle UX and the permission check has to live on the function.
This post is for someone starting a TanStack Start app who wants permission checks on server functions. You will build a requirePermission middleware factory on top of session middleware, keep resource checks inside handlers, and use beforeLoad only to keep the UI honest.
The same lesson shows up in React Router v7 authorization: identity in middleware, authorization next to the data. For the architecture labels, see PEP, PDP, and decision logs.
TanStack Start supports middleware in more than one place. For authorization, the important split is:
beforeLoad: runs while resolving the route tree. Good for redirects to /login and for passing a session into route context. Bad as your only check, because the server function still exists as its own endpoint..middleware([...]) on createServerFn): runs when that function is invoked. This is the data boundary.The middleware guide lists authorization as a middleware use case and shows a factory that takes permission parameters. The authentication server primitives guide spells out why: the data boundary is the security boundary.
Centralize session loading so every protected handler sees a typed user:
// src/server/auth-middleware.ts
import { createMiddleware } from "@tanstack/react-start";
import { readSessionToken, findValidSession } from "./session";
export const authMiddleware = createMiddleware({ type: "function" }).server(
async ({ next }) => {
const token = readSessionToken();
const session = token ? await findValidSession(token) : null;
if (!session) {
throw new Error("Unauthorized");
}
return next({ context: { session } });
},
);
Attach it to any createServerFn that touches private data:
import { createServerFn } from "@tanstack/react-start";
import { authMiddleware } from "~/server/auth-middleware";
import { db } from "~/server/db";
export const getMyOrders = createServerFn({ method: "GET" })
.middleware([authMiddleware])
.handler(async ({ context }) => {
return db.orders.findMany({
where: { userId: context.session.userId },
});
});
Static "is logged in" checks are not enough for multi-tenant SaaS. Build a factory that takes an action and resource type, composes authMiddleware, and calls Permit:
// src/server/require-permission.ts
import { createMiddleware } from "@tanstack/react-start";
import { Permit } from "permitio";
import { authMiddleware } from "./auth-middleware";
const permit = new Permit({
token: process.env.PERMIT_API_KEY!,
pdp: process.env.PERMIT_PDP_URL ?? "http://localhost:7766",
});
export { permit };
export function requirePermission(action: string, resourceType: string) {
return createMiddleware({ type: "function" })
.middleware([authMiddleware])
.server(async ({ next, context }) => {
// Coarse type-level check scoped to the current tenant (e.g. permission to read "client")
const allowed = await permit.check(context.session.userId, action, {
type: resourceType,
key: resourceType,
tenant: context.session.tenantId,
});
if (!allowed) {
throw new Error("Forbidden");
}
return next();
});
}
For list endpoints, a type-level check works as a coarse gate, but keep the tenant filter in the query too. For instance operations, check inside the handler with the real id (next section).
export const listClients = createServerFn({ method: "GET" })
.middleware([requirePermission("read", "client")])
.handler(async ({ context }) => {
return db.clients.findMany({
where: { tenantId: context.session.tenantId },
});
});
Ownership and tenant fences need the id from the request:
import { z } from "zod";
import { permit } from "~/server/require-permission";
const updateProjectInput = z.object({
projectId: z.string().min(1),
name: z.string().min(1).max(120),
});
export const updateProject = createServerFn({ method: "POST" })
.middleware([authMiddleware])
.handler(async ({ context, data }) => {
const input = updateProjectInput.parse(data);
const allowed = await permit.check(context.session.userId, "update", {
type: "project",
key: input.projectId,
tenant: context.session.tenantId,
});
if (!allowed) {
throw new Error("Forbidden");
}
return db.projects.update({
where: { id: input.projectId, tenantId: context.session.tenantId },
data: { name: input.name },
});
});
Relationships ("editor on this project") and attributes ("stage != archived") belong in the policy. The handler keeps one check call. For multi-tenant patterns, see Best practices for multi-tenant authorization.
Still use route guards so users do not land on a blank error page:
import { createFileRoute, redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/_authenticated/orders")({
beforeLoad: ({ context }) => {
if (!context.auth?.isAuthenticated) {
throw redirect({ to: "/login" });
}
},
loader: () => getMyOrders(),
});
That redirect improves UX. It does not protect getMyOrders. Anyone who can hit the server function endpoint still needs the middleware on the function itself. TanStack's docs give almost exactly this warning.
Compose middleware so TypeScript sees context.session downstream. Prefer factories over copy-pasted checks, which makes it harder for a new server function to ship without auth.
Tests to run on every change:
createServerFn fails.beforeLoad redirect still works (UX), separate from (1).Run a PDP next to the Start server for hot-path checks. With Permit's hybrid model, a locally deployed PDP evaluates decisions without a remote call to Permit's SaaS, while OPAL keeps policy and authorization data in sync. See the PDP overview for deployment options.
The same rule applies when something other than a person calls your server functions. If an AI agent or background job invokes createServerFn endpoints, give it its own identity and permissions in the PDP. Letting it inherit the full permissions of the user who started it is an anti-pattern.
createServerFn as a public HTTP endpoint.requirePermission (or an in-handler permit.check) on every private read or write.beforeLoad for redirects and UI gating only.TanStack Start gives you typed server functions and middleware factories that fit authorization well. The common mistake is treating the router as the security boundary, so put the check on the function, where the data boundary actually is.

Co-Founder & VP of R&D at Permit.io