Skip to content
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/strong-penguins-retire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Allow redirects to be returned from client side middleware
104 changes: 104 additions & 0 deletions packages/react-router/__tests__/router/context-middleware-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1684,6 +1684,110 @@ describe("context/middleware", () => {
});
});
});

describe("redirects", () => {
it("allows you to return redirects before next from client middleware", async () => {
router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: "/",
},
{
path: "/redirect",
middleware: [
async () => {
return redirect("/target");
},
],
},
{
path: "/target",
},
],
});

await router.navigate("/redirect");
expect(router.state.location.pathname).toBe("/target");
});

it("allows you to return redirects after next from client middleware", async () => {
router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: "/",
},
{
path: "/redirect",
middleware: [
async (_, next) => {
await next();
return redirect("/target");
},
],
},
{
path: "/target",
},
],
});

await router.navigate("/redirect");
expect(router.state.location.pathname).toBe("/target");
});

it("allows you to throw redirects before next from client middleware", async () => {
router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: "/",
},
{
path: "/redirect",
middleware: [
async () => {
throw redirect("/target");
},
],
},
{
path: "/target",
},
],
});

await router.navigate("/redirect");
expect(router.state.location.pathname).toBe("/target");
});

it("allows you to throw redirects after next from client middleware", async () => {
router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: "/",
},
{
path: "/redirect",
middleware: [
async (_, next) => {
await next();
throw redirect("/target");
},
],
},
{
path: "/target",
},
],
});

await router.navigate("/redirect");
expect(router.state.location.pathname).toBe("/target");
});
});
});

describe("middleware - handler.query", () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/react-router/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5664,7 +5664,13 @@ function runClientMiddlewarePipeline(
return runMiddlewarePipeline(
args,
handler,
(r) => r, // No post-processing needed on the client
(r) => {
// Throw any redirect responses to short circuit
if (isRedirectResponse(r)) {
throw r;
}
return r;
},
isDataStrategyResults,
errorHandler,
);
Expand Down