Skip to content

support thrown redirects from server actions #13707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions integration/rsc/rsc-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,85 @@ implementations.forEach((implementation) => {
// Ensure this is using RSC
validateRSCHtml(await page.content());
});

test("Supports React Server Functions thrown redirects", async ({
page,
}) => {
let port = await getPort();
stop = await setupRscTest({
implementation,
port,
files: {
"src/routes/home.actions.ts": js`
"use server";
import { redirect } from "react-router/rsc";

export function redirectAction(formData: FormData) {
throw redirect("/?redirected=true");
}
`,
"src/routes/home.client.tsx": js`
"use client";
import { useState } from "react";

export function Counter() {
const [count, setCount] = useState(0);
return <button type="button" onClick={() => setCount(c => c + 1)} data-count>Count: {count}</button>;
}
`,
"src/routes/home.tsx": js`
import { redirectAction } from "./home.actions";
import { Counter } from "./home.client";

export default function ServerComponent(props) {
console.log({props});
return (
<div>
<form action={redirectAction}>
<button type="submit" data-submit>
Redirect via Server Function
</button>
</form>
<Counter />
</div>
);
}
`,
},
});

await page.goto(`http://localhost:${port}/`);

// Verify initial server render
await page.waitForSelector("[data-count]");
expect(await page.locator("[data-count]").textContent()).toBe(
"Count: 0"
);
await page.click("[data-count]");
expect(await page.locator("[data-count]").textContent()).toBe(
"Count: 1"
);

// Submit the form to trigger server function redirect
await page.click("[data-submit]");

await expect(page).toHaveURL(
`http://localhost:${port}/?redirected=true`
);

// Validate things are still interactive after redirect
await page.click("[data-count]");
expect(await page.locator("[data-count]").textContent()).toBe(
"Count: 2"
);
await page.click("[data-count]");
expect(await page.locator("[data-count]").textContent()).toBe(
"Count: 3"
);

// Ensure this is using RSC
validateRSCHtml(await page.content());
});
});

test.describe("Errors", () => {
Expand Down
12 changes: 12 additions & 0 deletions packages/react-router/lib/rsc/browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ declare global {
}
}

const neverResolvedPromise = new Promise<never>(() => {});
export function createCallServer({
decode,
encodeAction,
Expand All @@ -70,6 +71,17 @@ export function createCallServer({
}
const payload = await decode(response.body);

if (payload.type === "redirect") {
if (payload.reload) {
window.location.href = payload.location;
return;
}
window.__router.navigate(payload.location, {
replace: payload.replace,
});
return neverResolvedPromise;
}

if (payload.type !== "action") {
throw new Error("Unexpected payload type");
}
Expand Down
13 changes: 12 additions & 1 deletion packages/react-router/lib/rsc/server.rsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,9 @@ async function processServerAction(
decodeFormAction: DecodeFormActionFunction | undefined,
onError: ((error: unknown) => void) | undefined
): Promise<
{ revalidationRequest: Request; actionResult?: Promise<unknown> } | undefined
| { revalidationRequest: Request; actionResult?: Promise<unknown> }
| Response
| undefined
> {
const getRevalidationRequest = () =>
new Request(request.url, {
Expand All @@ -261,6 +263,9 @@ async function processServerAction(
// Wait for actions to finish regardless of state
await actionResult;
} catch (error) {
if (isResponse(error)) {
return error;
}
// The error is propagated to the client through the result promise in the stream
onError?.(error);
}
Expand All @@ -282,6 +287,9 @@ async function processServerAction(
try {
await action();
} catch (error) {
if (isResponse(error)) {
return error;
}
onError?.(error);
}
return {
Expand Down Expand Up @@ -349,6 +357,9 @@ async function generateRenderResponse(
decodeFormAction,
onError
);
if (isResponse(result)) {
return generateRedirectResponse(statusCode, result, generateResponse);
}
actionResult = result?.actionResult;
request = result?.revalidationRequest ?? request;
}
Expand Down
Loading