@rsc-kit/mcp
Version:
An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.
375 lines (269 loc) • 11.6 kB
Markdown
# Authorization
> Protecting pages, server actions and API routes.
There are three ways into your app: a page, a server action and an API route.
Each needs its own check, and guarding one doesn't guard the others.
```ts title="src/app/admin/middleware.ts"
import { redirect } from '@rsc-kit/core/redirect';
export default async function middleware() {
if (!(await currentUser())?.isAdmin) redirect('/login');
}
```
| Question | Where it goes |
| --- | --- |
| May this person see this part of the site? | `middleware.ts` in its folder |
| May this caller run this action? | Inside the action |
| May this caller use this endpoint? | Inside the route handler, or a `middleware.ts` above it |
| Should the page show different things to different people? | The page, which renders per request anyway |
## Protect a page
Put a `middleware.ts` in the folder you want to protect:
```ts title="src/app/admin/middleware.ts"
import { redirect } from '@rsc-kit/core/redirect';
import { currentUser } from '../../auth';
export default async function middleware() {
const user = await currentUser();
if (!user?.isAdmin) redirect('/login');
}
```
It runs before anything in that folder or below it renders. Return nothing to
allow the request; redirect or throw to refuse it.
Middleware files nest like layouts, outermost first, and **every** request runs
the whole chain: a full page load, a navigation, a prefetch, a revalidation.
A prefetch is a page the visitor has not opened yet, so a check that
*remembers* something - the url to return to after signing in - asks first:
```ts title="src/app/settings/middleware.ts"
import { redirect } from '@rsc-kit/core/redirect';
import { cookies, prefetching } from '@rsc-kit/core/request';
import { currentUser } from '../../auth';
export default async function middleware() {
if (await currentUser()) return;
if (!prefetching()) (await cookies()).set('intended', '/settings');
redirect('/login');
}
```
Otherwise a settings link prefetched just after logout becomes where the next
sign-in lands. The refusal is the same either way. A backend's guards are told
too, by `x-rsc-prefetch` on each host call, and a cookie one sets during a
prefetch never reaches the browser. On Laravel that call answers
`$request->prefetch()` with true, and its session is left as it was; on Go,
`rsckit.Prefetching(ctx)` is the same question.
### Several checks
Export a list to run several checks in order. The first refusal stops the
rest:
```ts title="src/app/admin/middleware.ts"
import { signedIn, verified } from '../../guards';
import { redirect } from '@rsc-kit/core/redirect';
export default [
signedIn,
verified,
async () => {
if (!(await currentUser())?.isAdmin) redirect('/');
},
];
```
`src/app/middleware.ts` above it still runs first.
### Answering 404 instead
`notFound()` in a `middleware.ts` answers **404** with `not-found.tsx` before
anything renders. Use it for an area that shouldn't admit to existing:
```ts title="src/app/admin/middleware.ts"
import { notFound } from '@rsc-kit/core/not-found';
export default async function adminsOnly() {
if (!(await currentUser())?.isAdmin) notFound();
}
```
<Aside type="caution" title="Don't put the check in a layout">
It works on a full page load. But a navigation tells the server which layouts
the browser already has, and the server skips them. A request can claim to
have your layout, and then the check never runs. `middleware.ts` is never
skipped.
</Aside>
## Protect a server action
Check inside the action:
```ts title="src/actions.ts"
'use server'
import { currentUser } from './auth';
export async function placeOrder(item: string) {
const user = await currentUser();
if (!user) throw new Error('Not signed in');
// …
}
```
An action is a public endpoint, and its id isn't a secret. Anyone can call it
without your page:
```bash
curl -X POST /_rsc/action \
-H 'X-RSC-Action: 0339292364be#placeOrder' \
-H 'X-RSC-Content-Type: text/plain;charset=UTF-8' \
--data-binary '["a rubber duck"]'
```
<Aside type="caution" title="Middleware does not cover actions">
`middleware.ts` runs when a route renders. An action renders no route, so
none of it runs.
</Aside>
### Writing the check once
Put the check on an action client, and build every action from it:
```ts title="src/server/client.ts"
'use server'
import { createActionClient } from '@rsc-kit/core/action'
export const client = createActionClient()
.use(async ({ next }) => {
const user = await currentUser()
if (!user) throw new ServerAuthenticationError()
return next({ ctx: { user } })
})
```
```ts title="src/server/orders.ts"
'use server'
import { client } from './client'
export const placeOrder = client.input(schema).handler(async ({ input, ctx }) =>
orders.create(ctx.user.id, input),
)
export const listOrders = client.query(async ({ ctx }) => orders.forUser(ctx.user.id))
```
`ctx.user` is typed and never null inside the handler, and an action built
from `client` can't skip the check. `.handler()` makes an action and
`.query()` makes a [read](/guides/queries/); both run the same chain.
Add another `.use()` for a role, and it applies to everything built from it:
```ts
export const admin = client.use(async ({ ctx, next }) => {
if (!ctx.user.isAdmin) throw new ServerAuthorizationError()
return next({ ctx })
})
```
### Checking the record, not only the user
Authorize on **identity, not arguments**. The caller chooses the id they send
to `cancelOrder(id)`, so the handler has to check that the order belongs to
`ctx.user`. Trusting the id is an IDOR.
## Protect an API route
A [route](/guides/api-routes/) runs the same middleware a page in its folder
would:
```text
src/app/admin/
middleware.ts ← guards everything below
page.tsx ← guarded
api/export/route.ts ← guarded too
```
A refused route answers **401** or **403** instead of redirecting, and names
the destination in `X-RSC-Redirect` if the middleware redirected. A `fetch`
would otherwise follow the redirect and return a login page as your data.
For a route with no middleware above it, check inside the handler:
```ts title="src/app/api/orders/route.ts"
import { currentUser } from '../../../auth';
export async function GET(): Promise<Response> {
const user = await currentUser();
if (!user) return new Response('Unauthorized', { status: 401 });
return Response.json(await orders(user.id));
}
```
## Reading the session
`headers()` and `cookies()` read the request in flight:
```ts title="src/app/beta/middleware.ts"
import { redirect } from '@rsc-kit/core/redirect';
import { cookies } from '@rsc-kit/core/request';
export default async function middleware() {
if ((await cookies()).get('beta')?.value !== 'yes') redirect('/waitlist');
}
```
They work anywhere a request is in flight: middleware, server components,
actions and API routes. `request()` returns the whole `Request`.
Every page under a middleware that reads the request is rendered per visitor.
Choosing a language from `Accept-Language` is the usual case where that is not
what you want: do it once, at `/`, and keep the pages stored - see
[Internationalisation](/guides/internationalisation#sending--to-a-language).
They're async because at build time there is no request: the read waits, the
rest of the page is stored, and only the part that read a header renders per
visitor.
### Looking the user up once
Middleware, the layout and the page all want the current user. Wrap the lookup
in `cache()` and it runs once per request:
```ts title="src/session.ts"
import { cache } from '@rsc-kit/core/cache';
export const currentUser = cache(async () => {
const id = await sessionId();
return db.user(id);
});
```
The cache lasts one request, and two requests never see each other's answers.
Outside a request it just calls through.
### Typing the signed-in user
A page under the guard gets the cached user, but its type is still
`User | null`. Put the guarantee in a helper both call:
```ts title="src/session.ts"
import { redirect } from '@rsc-kit/core/redirect';
/** The signed-in user. Redirects otherwise, so the return type is `User`. */
export async function requireUser(): Promise<User> {
const user = await currentUser();
if (!user) redirect('/', { search: { auth: true } });
return user;
}
```
```ts title="src/app/account/middleware.ts"
export default async function middleware() {
await requireUser();
}
```
```tsx title="src/app/account/page.tsx"
export default async function Account() {
const user = await requireUser(); // User, one lookup for the request
return <h1>{user.firstName}</h1>;
}
```
`redirect()` returns `never`, which narrows the type. A page rendered somewhere
the guard doesn't cover redirects too, instead of passing `null` on.
## Writing to the response
Middleware runs before the response exists, so it can set a header or a cookie
on it:
```ts title="src/app/account/middleware.ts"
import { cookies, responseHeaders } from '@rsc-kit/core/request'
// Middleware runs before anything below it renders, which is also before the
// host has built a response — so this is the one place left where a header or a
// cookie can still be put on it. A component runs after, while the response is
// already streaming, and writing from there throws rather than being dropped.
//
// The page below is frozen at build time and stays frozen: what is written here
// is per request, so neither costs the other anything.
export default async function middleware() {
responseHeaders().set('X-Account-Section', 'yes')
const jar = await cookies()
if (!jar.has('seen-account')) {
jar.set('seen-account', new Date().toISOString(), { httpOnly: true, sameSite: 'lax' })
}
}
```
An action can set a cookie too, which is how signing in works:
```ts title="src/app/login/actions.ts"
'use server';
import { action } from '@rsc-kit/core/action';
import { cookies } from '@rsc-kit/core/request';
export const login = action.input(credentials).handler(async ({ input }) => {
const session = await authenticate(input);
(await cookies()).set('session', session.token, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 60 * 60 * 24 * 7,
});
});
```
`get`, `set` and `delete` on the request in flight are all an auth library
needs, so you can wire in whichever one you use.
<Aside type="caution" title="A component is too late">
By the time a page renders, the status and headers have been sent. Writing
from a component throws and tells you to move it to middleware.
</Aside>
## Storing a guarded page
Whether a page is the same for everyone and whether *you* may see it are
separate questions. The build answers the first, and middleware the second, on
every request. So a guarded page whose content never varies is still stored at
build time, and the middleware decides who gets it:
| Route | Navigation |
| --- | --- |
| Guarded and stored: check, then serve from disk | 6.7 ms |
| Guarded, rendered per request | 2626.7 ms |
| Unguarded, stored | 0.6 ms |
The check runs before the file is read, so a refusal never touches it.
<Aside type="caution" title="Two places this doesn't hold">
**A static export can't guard anything.** A static host serves files without
running code, so exporting a guarded route publishes it to anyone.
**Don't put a guarded page in a shared cache.** Your server runs the check,
but a CDN holding the response serves it to the next caller without asking.
</Aside>