# CSRF Protection

> How CSRF protection works in Makerkit.

*Canonical: https://makerkit.dev/docs/tanstack-supabase/data-fetching/csrf-protection*

---

## CSRF Protection

CSRF protection is handled automatically by TanStack Start for server functions. You do not need to manage CSRF tokens manually.

### Server Functions

Server functions (`createServerFn`) are protected against CSRF attacks by TanStack Start's built-in CSRF middleware. The kit registers it explicitly in `apps/web/src/start.ts`, scoped to server-function requests:

```tsx
import { createCsrfMiddleware, createStart } from '@tanstack/react-start';

const csrfMiddleware = createCsrfMiddleware({
  filter: (ctx) => ctx.handlerType === 'serverFn',
});

export const startInstance = createStart(() => ({
  requestMiddleware: [csrfMiddleware /* ...security headers */],
}));
```

The middleware validates the origin of every server-function request, ensuring it comes from the same origin as your application. Server functions are invoked over same-origin RPC and Supabase auth cookies are `SameSite`, so no additional configuration or token passing is needed.

### Server Routes

Server routes under `apps/web/src/routes/api/*` are plain HTTP endpoints and are not covered by the server-function CSRF middleware, since they are typically used for webhooks, external services, and third-party integrations. Protect them explicitly:

- **Verify signatures** for webhooks (e.g. Stripe / Lemon Squeezy) against the raw request body.
- **Require authentication** by calling `requireUser(client)` inside the handler and returning `401` on failure.
- **Check the request origin** when a route performs state-changing operations on behalf of the current session.

### Recommendations

- **Prefer server functions** for all mutations from client components. They provide built-in CSRF protection and type safety.
- **Use server routes** only for webhooks, streaming responses, or integrations that require standard HTTP endpoints, and add your own signature or auth checks.
