Skip to content

feat: server action revalidation opt out via $NO_REVALIDATE field. #14154

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

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions .changeset/rsc-no-revalidate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Allow for `<input name="$NO_REVALIDATE" type="hidden" />` to be provided to <form action> and useActionState to allow progressively enhanced calls to opt out of route level revalidation.
89 changes: 88 additions & 1 deletion integration/rsc/rsc-test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { test, expect } from "@playwright/test";
import {
test,
expect,
type Response as PlaywrightResponse,
} from "@playwright/test";
import getPort from "get-port";

import { implementations, js, setupRscTest, validateRSCHtml } from "./utils";
Expand Down Expand Up @@ -479,6 +483,11 @@ implementations.forEach((implementation) => {
path: "hydrate-fallback-props",
lazy: () => import("./routes/hydrate-fallback-props/home"),
},
{
id: "no-revalidate-server-action",
path: "no-revalidate-server-action",
lazy: () => import("./routes/no-revalidate-server-action/home"),
},
],
},
] satisfies RSCRouteConfig;
Expand Down Expand Up @@ -1069,6 +1078,13 @@ implementations.forEach((implementation) => {

"src/routes/hydrate-fallback-props/home.tsx": js`
export { default, clientLoader, HydrateFallback } from "./home.client";

export const unstable_middleware = [
async (_, next) => {
const response = await next();
return response.headers.set("x-test", "test");
}
];
`,
"src/routes/hydrate-fallback-props/home.client.tsx": js`
"use client";
Expand Down Expand Up @@ -1108,6 +1124,47 @@ implementations.forEach((implementation) => {
);
}
`,

"src/routes/no-revalidate-server-action/home.actions.ts": js`
"use server";

export async function noRevalidateAction() {
return "no revalidate";
}
`,
"src/routes/no-revalidate-server-action/home.tsx": js`
import ClientHomeRoute from "./home.client";

export function loader() {
console.log("loader");
}

export default function HomeRoute() {
return <ClientHomeRoute identity={{}} />;
}
`,
"src/routes/no-revalidate-server-action/home.client.tsx": js`
"use client";

import { useActionState, useState } from "react";
import { noRevalidateAction } from "./home.actions";

export default function HomeRoute({ identity }) {
const [initialIdentity] = useState(identity);
const [state, action, pending] = useActionState(noRevalidateAction, null);
return (
<div>
<form action={action}>
<input name="$NO_REVALIDATE" type="hidden" />
<button type="submit" data-submit>No Revalidate</button>
</form>
{state && <div data-state>{state}</div>}
{pending && <div data-pending>Pending</div>}
{initialIdentity !== identity && <div data-revalidated>Revalidated</div>}
</div>
);
}
`,
},
});
});
Expand Down Expand Up @@ -1525,6 +1582,36 @@ implementations.forEach((implementation) => {
// Ensure this is using RSC
validateRSCHtml(await page.content());
});

test.only("Supports server actions that disable revalidation", async ({
page,
}) => {
await page.goto(
`http://localhost:${port}/no-revalidate-server-action`,
{ waitUntil: "networkidle" },
);

const actionResponsePromise = new Promise<PlaywrightResponse>(
(resolve) => {
page.on("response", async (response) => {
if (!!(await response.request().headerValue("rsc-action-id"))) {
resolve(response);
}
});
},
);

await page.click("[data-submit]");
await page.waitForSelector("[data-state]");
await page.waitForSelector("[data-pending]", { state: "hidden" });
await page.waitForSelector("[data-revalidated]", { state: "hidden" });
expect(await page.locator("[data-state]").textContent()).toBe(
"no revalidate",
);

const actionResponse = await actionResponsePromise;
expect(await actionResponse.headerValue("x-test")).toBe("test");
});
});

test.describe("Errors", () => {
Expand Down
18 changes: 12 additions & 6 deletions packages/react-router/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ export interface StaticHandler {
requestContext?: unknown;
filterMatchesToLoad?: (match: AgnosticDataRouteMatch) => boolean;
skipLoaderErrorBubbling?: boolean;
skipRevalidation?: boolean;
skipRevalidation?: boolean | (() => boolean);
dataStrategy?: DataStrategyFunction<unknown>;
unstable_generateMiddlewareResponse?: (
query: (r: Request) => Promise<StaticHandlerContext | Response>,
Expand Down Expand Up @@ -3631,7 +3631,9 @@ export function createStaticHandler(
skipLoaderErrorBubbling === true,
null,
filterMatchesToLoad || null,
skipRevalidation === true,
skipRevalidation === true ||
(typeof skipRevalidation === "function" &&
skipRevalidation() === true),
);

if (isResponse(result)) {
Expand Down Expand Up @@ -3729,7 +3731,8 @@ export function createStaticHandler(
skipLoaderErrorBubbling === true,
null,
filterMatchesToLoad || null,
skipRevalidation === true,
skipRevalidation === true ||
(typeof skipRevalidation === "function" && skipRevalidation() === true),
);

if (isResponse(result)) {
Expand Down Expand Up @@ -3912,7 +3915,7 @@ export function createStaticHandler(
skipLoaderErrorBubbling: boolean,
routeMatch: AgnosticDataRouteMatch | null,
filterMatchesToLoad: ((m: AgnosticDataRouteMatch) => boolean) | null,
skipRevalidation: boolean,
skipRevalidation: boolean | (() => boolean),
): Promise<Omit<StaticHandlerContext, "location" | "basename"> | Response> {
invariant(
request.signal,
Expand Down Expand Up @@ -3979,7 +3982,7 @@ export function createStaticHandler(
skipLoaderErrorBubbling: boolean,
isRouteRequest: boolean,
filterMatchesToLoad: ((m: AgnosticDataRouteMatch) => boolean) | null,
skipRevalidation: boolean,
skipRevalidation: boolean | (() => boolean),
): Promise<Omit<StaticHandlerContext, "location" | "basename"> | Response> {
let result: DataResult;

Expand Down Expand Up @@ -4054,7 +4057,10 @@ export function createStaticHandler(
};
}

if (skipRevalidation) {
if (
skipRevalidation === true ||
(typeof skipRevalidation === "function" && skipRevalidation() === true)
) {
if (isErrorResult(result)) {
let boundaryMatch = skipLoaderErrorBubbling
? actionMatch
Expand Down
34 changes: 32 additions & 2 deletions packages/react-router/lib/rsc/server.rsc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,7 @@ async function processServerAction(
revalidationRequest: Request;
actionResult?: Promise<unknown>;
formState?: unknown;
revalidate: boolean;
}
| Response
| undefined
Expand Down Expand Up @@ -559,9 +560,30 @@ async function processServerAction(
// The error is propagated to the client through the result promise in the stream
onError?.(error);
}

// We check both the first and second args to cover both <form action> and useActionState.
let formData1 =
actionArgs &&
typeof actionArgs[0] === "object" &&
actionArgs[0] instanceof FormData
? actionArgs[0]
: null;
let formData2 =
actionArgs &&
typeof actionArgs[1] === "object" &&
actionArgs[1] instanceof FormData
? actionArgs[1]
: null;
let revalidate =
(formData1 && formData1.has("$NO_REVALIDATE")) ||
(formData2 && formData2.has("$NO_REVALIDATE"))
? false
: true;

return {
actionResult,
revalidationRequest: getRevalidationRequest(),
revalidate,
};
} else if (isFormRequest) {
const formData = await request.clone().formData();
Expand Down Expand Up @@ -591,6 +613,7 @@ async function processServerAction(
return {
formState,
revalidationRequest: getRevalidationRequest(),
revalidate: true,
};
}
}
Expand Down Expand Up @@ -698,14 +721,18 @@ async function generateRenderResponse(
});

let actionResult: Promise<unknown> | undefined;
let skipRevalidation = false;
const ctx: ServerContext = {
runningAction: false,
};
const result = await ServerStorage.run(ctx, () =>
staticHandler.query(request, {
requestContext,
skipLoaderErrorBubbling: isDataRequest,
skipRevalidation: isSubmission,
skipRevalidation: () => {
// TODO: This should opt out of loader calls but is not at the moment.
return isSubmission || skipRevalidation;
},
...(routeIdsToLoad
? { filterMatchesToLoad: (m) => routeIdsToLoad!.includes(m.route.id) }
: null),
Expand Down Expand Up @@ -741,6 +768,7 @@ async function generateRenderResponse(
);
}

skipRevalidation = result?.revalidate === false;
actionResult = result?.actionResult;
formState = result?.formState;
request = result?.revalidationRequest ?? request;
Expand Down Expand Up @@ -782,6 +810,7 @@ async function generateRenderResponse(
isSubmission,
actionResult,
formState,
skipRevalidation,
staticContext,
temporaryReferences,
ctx.redirect?.headers,
Expand Down Expand Up @@ -873,6 +902,7 @@ async function generateStaticContextResponse(
isSubmission: boolean,
actionResult: Promise<unknown> | undefined,
formState: unknown | undefined,
skipRevalidation: boolean,
staticContext: StaticHandlerContext,
temporaryReferences: unknown,
sideEffectRedirectHeaders: Headers | undefined,
Expand Down Expand Up @@ -949,7 +979,7 @@ async function generateStaticContextResponse(
payload = {
type: "action",
actionResult,
rerender: renderPayloadPromise(),
rerender: skipRevalidation ? undefined : renderPayloadPromise(),
};
} else if (isSubmission && isDataRequest) {
// Short circuit without matches on non server-action submissions since
Expand Down
Loading