Skip to content

Restore handling of 204 "soft" redirects on data requests #13364

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 6 commits into from
Apr 23, 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
9 changes: 9 additions & 0 deletions .changeset/new-hornets-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"react-router": patch
---

Update Single Fetch to also handle the 204 redirects used in `?_data` requests in Remix v2

- This allows applications to return a redirect on `.data` requests from outside the scope of React Router (i.e., an `express`/`hono` middleware)
- ⚠️ Please note that doing so relies on implementation details that are subject to change without a SemVer major release
- This is primarily done to ease upgrading to Single Fetch for existing Remix v2 applications, but the recommended way to handle this is redirecting from a route middleware
3 changes: 3 additions & 0 deletions integration/helpers/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export const EXPRESS_SERVER = (args: {
port: number;
base?: string;
loadContext?: Record<string, unknown>;
customLogic?: string;
}) =>
String.raw`
import { createRequestHandler } from "@react-router/express";
Expand All @@ -166,6 +167,8 @@ export const EXPRESS_SERVER = (args: {
}
app.use(express.static("build/client", { maxAge: "1h" }));
${args?.customLogic || ""}
app.all(
"*",
createRequestHandler({
Expand Down
66 changes: 65 additions & 1 deletion integration/single-fetch-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ import {
js,
} from "./helpers/create-fixture.js";
import { PlaywrightFixture } from "./helpers/playwright-fixture.js";
import { reactRouterConfig } from "./helpers/vite.js";
import {
EXPRESS_SERVER,
createProject,
customDev,
reactRouterConfig,
viteConfig,
} from "./helpers/vite.js";
import getPort from "get-port";

const ISO_DATE = "2024-03-12T12:00:00.000Z";

Expand Down Expand Up @@ -1538,6 +1545,63 @@ test.describe("single-fetch", () => {
expect(await app.getHtml("#target")).toContain("Target");
});

test("processes redirects returned outside of react router", async ({
page,
}) => {
let port = await getPort();
let cwd = await createProject({
"vite.config.js": await viteConfig.basic({ port }),
"server.mjs": EXPRESS_SERVER({
port,
customLogic: js`
app.use(async (req, res, next) => {
if (req.url === "/page.data") {
res.status(204);
res.append('X-Remix-Status', '302');
res.append('X-Remix-Redirect', '/target');
res.end();
} else {
next();
}
});
`,
}),
"app/routes/_index.tsx": js`
import { Link } from "react-router";
export default function Component() {
return <Link to="/page">Go to /page</Link>
}
`,
"app/routes/page.tsx": js`
export function loader() {
return null
}
export default function Component() {
return <p>Should not see me</p>
}
`,
"app/routes/target.tsx": js`
export default function Component() {
return <h1 id="target">Target</h1>
}
`,
});
let stop = await customDev({ cwd, port });

try {
await page.goto(`http://localhost:${port}/`, {
waitUntil: "networkidle",
});
let link = page.locator('a[href="/page"]');
await expect(link).toHaveText("Go to /page");
await link.click();
await page.waitForSelector("#target");
await expect(page.locator("#target")).toHaveText("Target");
} finally {
stop();
}
});

test("processes thrown loader errors", async ({ page }) => {
let fixture = await createFixture({
files: {
Expand Down
23 changes: 23 additions & 0 deletions packages/react-router/lib/dom/ssr/single-fetch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ interface StreamTransferProps {
nonce?: string;
}

// We can't use a 3xx status or else the `fetch()` would follow the redirect.
// We need to communicate the redirect back as data so we can act on it in the
// client side router. We use a 202 to avoid any automatic caching we might
// get from a 200 since a "temporary" redirect should not be cached. This lets
// the user control cache behavior via Cache-Control
export const SINGLE_FETCH_REDIRECT_STATUS = 202;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pulled into here from the server-runtime file to avoid circular deps


// Some status codes are not permitted to have bodies, so we want to just
// treat those as "no data" instead of throwing an exception:
// https://datatracker.ietf.org/doc/html/rfc9110#name-informational-1xx
Expand Down Expand Up @@ -535,6 +542,22 @@ async function fetchAndDecodeViaTurboStream(
throw new ErrorResponseImpl(404, "Not Found", true);
}

// Handle non-RR redirects (i.e., from express middleware)
if (res.status === 204 && res.headers.has("X-Remix-Redirect")) {
return {
status: SINGLE_FETCH_REDIRECT_STATUS,
data: {
redirect: {
redirect: res.headers.get("X-Remix-Redirect")!,
status: Number(res.headers.get("X-Remix-Status") || "302"),
revalidate: res.headers.get("X-Remix-Revalidate") === "true",
reload: res.headers.get("X-Remix-Reload-Document") === "true",
replace: res.headers.get("X-Remix-Replace") === "true",
},
},
};
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we get back a 204 redirect we convert it to a single fetch redirect here for downstream processing


if (NO_BODY_STATUS_CODES.has(res.status)) {
let routes: { [key: string]: SingleFetchResult } = {};
// We get back just a single result for action requests - normalize that
Expand Down
6 changes: 4 additions & 2 deletions packages/react-router/lib/server-runtime/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import {
getSingleFetchRedirect,
singleFetchAction,
singleFetchLoaders,
SINGLE_FETCH_REDIRECT_STATUS,
SERVER_NO_BODY_STATUS_CODES,
} from "./single-fetch";
import { getDocumentHeaders } from "./headers";
Expand All @@ -38,7 +37,10 @@ import type {
SingleFetchResult,
SingleFetchResults,
} from "../dom/ssr/single-fetch";
import { SingleFetchRedirectSymbol } from "../dom/ssr/single-fetch";
import {
SINGLE_FETCH_REDIRECT_STATUS,
SingleFetchRedirectSymbol,
} from "../dom/ssr/single-fetch";
import type { MiddlewareEnabled } from "../types/future";

export type RequestHandler = (
Expand Down
8 changes: 1 addition & 7 deletions packages/react-router/lib/server-runtime/single-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
} from "../dom/ssr/single-fetch";
import {
NO_BODY_STATUS_CODES,
SINGLE_FETCH_REDIRECT_STATUS,
SingleFetchRedirectSymbol,
} from "../dom/ssr/single-fetch";
import type { AppLoadContext } from "./data";
Expand All @@ -28,13 +29,6 @@ import { ServerMode } from "./mode";
import { getDocumentHeaders } from "./headers";
import type { ServerBuild } from "./build";

// We can't use a 3xx status or else the `fetch()` would follow the redirect.
// We need to communicate the redirect back as data so we can act on it in the
// client side router. We use a 202 to avoid any automatic caching we might
// get from a 200 since a "temporary" redirect should not be cached. This lets
// the user control cache behavior via Cache-Control
export const SINGLE_FETCH_REDIRECT_STATUS = 202;

// Add 304 for server side - that is not included in the client side logic
// because the browser should fill those responses with the cached data
// https://datatracker.ietf.org/doc/html/rfc9110#name-304-not-modified
Expand Down