@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.
255 lines (186 loc) • 8.83 kB
Markdown
# Redirects
> Sending the visitor somewhere else from a page, a middleware or a server action.
Call `redirect()` to send the visitor to another URL:
```tsx title="src/app/products/[slug]/page.tsx"
import { redirect } from '@rsc-kit/core/redirect';
import { findProduct } from '../../../data';
export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const product = await findProduct(slug);
if (!product) redirect('/products');
return <h1>{product.name}</h1>;
}
```
`redirect` never returns: it throws, which stops the component.
## Redirecting from a page
The default status is `307`, which keeps the request method, so a redirect out
of a `POST` doesn't turn into a `GET` of the destination. For a permanent one,
pass the status:
```ts
redirect('/old', { status: 308 });
redirect('/old', 308); // the same
```
- **During a navigation** the redirect is a navigation too. The document
doesn't reload, and the layouts you are inside stay mounted.
- **The URL that redirected is replaced in history**, so Back doesn't land on
it and redirect again.
- **A form posted without JavaScript** - before the page has loaded it, or in a
browser without it - gets `303 See Other`, whatever status you gave. The
browser follows it with a `GET`; a `307` would post the form again at the
destination and run the action twice.
## With a query string
Pass `search`. It is typed by the destination page's own `searchParams`
schema, as `Link`'s `search` prop is, so a key the page never reads doesn't
compile:
```ts
redirect('/', { search: { auth: true } }); // → /?auth=true
redirect('/search', { search: { q, page: 2 } }); // checked against /search's schema
```
## Leaving the app
A redirect can go to another site, or to a URL your backend answers:
```tsx
// Another site: any http(s) URL type-checks as written.
redirect('https://gitlab.com/oauth/authorize?client_id=…');
// A URL your backend owns, named in backendPaths.
redirect('/gitlab/connect');
```
Both are full page loads rather than navigations. Name the backend's prefixes
in the config, since the app can't otherwise tell them from a page it hasn't
built yet:
```ts title="vite.config.ts"
rscKit({ backendPaths: ['/auth', '/github', '/gitlab'] })
```
A URL in `backendPaths` is typed for `redirect()`, `Link` and `visit()`, loads
as a document, and is never prefetched, so hovering a link can't start an OAuth
flow. Without it, the router fetches the URL as a page, the backend redirects
to another site, and the browser refuses that hop: the click does nothing.
See [backend-answered pages](/hosts/backend-answered-pages/).
It works the same above a `<Suspense>` boundary or inside one, on a first visit
or on a click. Back from the other site lands on the page before the redirect.
## Redirecting from a server action
Call `redirect()` in the action:
```ts title="src/actions.ts"
'use server'
import { redirect } from '@rsc-kit/core/redirect';
export async function createPost(title: string) {
const post = await savePost(title);
redirect(`/posts/${post.slug}`);
}
```
The client follows it as a navigation, and the form's history entry is
replaced, so Back doesn't return to the submitted form. This works for a plain
`"use server"` function and for one built with `createActionClient()`.
The layouts aren't rendered again, as on any navigation. When the action
changed something a layout shows - a team switch, a sign-in, a count in the
sidebar - say so: `revalidate('all')` before the `redirect()` asks for
the destination whole, layouts included:
```ts
'use server'
export async function switchTeam(id: string) {
await setCurrentTeam(id)
revalidate('all')
redirect('/dashboard')
}
```
Without it, the page shows the new team and the sidebar the old one until a
reload. A named section counts too, since it can live in a layout. For a
backend action it is `Rsc::revalidate('all')` before the redirect. A `<Form>`
shows nothing for a redirect: arriving is the success.
### Back to the same page
A redirect back to the page the action was called from is the action
succeeding, not the visitor leaving. It is how a Laravel action answers a save
(`back()`), and how Fortify answers enabling two-factor authentication. The page
renders again, and the `<Form>` or `useAction` that called it settles as a
success: `onSuccess` runs and `resetOnSuccess` resets. The path and the query
have to match. A different query, such as `?page=2`, counts as another page.
### Checking for a redirect in the caller
A redirected action **resolves** with `{ redirected: '/where' }` instead of
its result. It doesn't throw, so a `startTransition` with no `catch` can't
unmount the page.
A stub generated for a backend action is typed `Promise<T | Redirected>`.
Narrow it with `isRedirected` before reading the value:
```ts
import { isRedirected } from '@rsc-kit/core/errors'
const secret = await databases.reveal(id)
if (isRedirected(secret)) return // on its way to /login
copy(secret.Password)
```
An action built on `createActionClient()` always resolves to an object with
`redirected` among its fields. A plain `"use server"` function is typed as what
it returns, so check `isRedirected` on its result, or build it on
`createActionClient()`.
An action that returns nothing needs the check too: in
`await stub(); toast.success('Saved')` the toast runs after the redirect has
started, for a write that never happened. No type or lint rule catches that,
so cover it in review and with a [test](/guides/testing#components) that
clicks it.
`tsc` also misses a redirect read as text: `` visit(`/t/${id}`) `` on a
`string | Redirected` compiles and goes to `/t/[object Object]`. Three
type-aware lint rules catch it, and a project from `create-rsc-kit` with
`--lint` has them on. Elsewhere:
```sh
npm i -D oxlint-tsgolint
```
```json title=".oxlintrc.json"
{
"rules": {
"typescript/restrict-template-expressions": "error",
"typescript/no-base-to-string": "error",
"typescript/restrict-plus-operands": "error"
}
}
```
and run `oxlint src --type-aware`. Type-aware rules need the flag.
## A route that only redirects
A page that always redirects is stored by the build, status and location, and
answered without rendering. A static export carries it too:
```text
○ /old-pricing (redirects to /pricing)
```
## Don't catch a redirect
`redirect` works by throwing. A `try`/`catch` that swallows everything turns it
into a blank region. If you have to wrap the call, rethrow it:
```ts
import { isRedirectSignal } from '@rsc-kit/core/redirect';
try {
await mightRedirect();
} catch (error) {
if (isRedirectSignal(error)) throw error;
// …
}
```
## Redirects and Suspense
Where the redirect is called decides what the browser has already seen:
| Called | Answered with | What the browser saw first |
| --- | --- | --- |
| Above every `<Suspense>` boundary | A real `3xx`, or `X-RSC-Redirect` on a navigation | Nothing |
| Inside a boundary | The shell, then the redirect | The layouts, and the fallbacks |
Either way the browser ends up at the destination. A page sends its shell as
early as it can, so a redirect decided inside a boundary arrives after it, as
a navigation. An `error.tsx` never sees a redirect, from a page, a component
under its own `<Suspense>` or a parallel slot.
That matters for an authorization check. A redirect for a missing record is
fine inside a boundary, but a page that must reveal nothing needs its check
before the shell is sent. A `loading.tsx` puts the whole page inside a
boundary, so an `await` at the top of that page is inside it.
Put the check in a `middleware.ts`. It runs before anything at or below its
folder renders, on every path. See [Authorization](/guides/authorization).
<Aside type="danger" title="A layout is not a security boundary">
A navigation tells the server which layouts the client already has, in
`X-RSC-Segments`, and the server skips rendering those. A client that
*claims* to hold your layout skips a check in it:
```bash
curl -H 'X-RSC: 1' -H 'X-RSC-Segments: app/layout' /guarded
# 204, X-RSC-Redirect: /orders ← the middleware ran
curl -H 'X-RSC: 1' -H 'X-RSC-Segments: app/layout,app/guarded/layout' /guarded
# 200, and the page's content ← it did not
```
The header can't be verified. Use a `middleware.ts` beside the layout.
</Aside>
A check at the top of a page with no `loading.tsx` also runs on every render.
It is fragile: adding a `loading.tsx` later moves it inside a boundary, and
nothing warns.
## Redirect loops
A navigation follows at most **8** redirects, then throws, so a page that
redirects to itself is an error you can see rather than an endless run of
renders.