Skip to content

Commit 50b96f9

Browse files
authored
Properly escape :param values in generatePath() (#13530)
1 parent 7a25561 commit 50b96f9

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

.changeset/eleven-oranges-design.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"react-router": patch
3+
---
4+
5+
Properly escape interpolated param values in `generatePath()`

packages/react-router/__tests__/generatePath-test.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,8 @@ describe("generatePath", () => {
4545
).toBe("/courses/foo*");
4646
});
4747
it("handles a 0 parameter", () => {
48-
// @ts-expect-error
4948
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
5049
expect(generatePath("/courses/:id", { id: 0 })).toBe("/courses/0");
51-
// @ts-expect-error
5250
// incorrect usage but worked in 6.3.0 so keep it to avoid the regression
5351
expect(generatePath("/courses/*", { "*": 0 })).toBe("/courses/0");
5452
});
@@ -135,6 +133,14 @@ describe("generatePath", () => {
135133
});
136134
});
137135

136+
describe("with a param that contains a /", () => {
137+
it("properly encodes the slash", () => {
138+
expect(generatePath("/courses/:id/grades", { id: "a/b" })).toBe(
139+
"/courses/a%2Fb/grades"
140+
);
141+
});
142+
});
143+
138144
it("throws only on on missing named parameters, but not missing splat params", () => {
139145
expect(() => generatePath(":foo")).toThrow();
140146
expect(() => generatePath("/:foo")).toThrow();

packages/react-router/lib/router/utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1308,7 +1308,7 @@ export function generatePath<Path extends string>(
13081308
const [, key, optional] = keyMatch;
13091309
let param = params[key as PathParam<Path>];
13101310
invariant(optional === "?" || param != null, `Missing ":${key}" param`);
1311-
return stringify(param);
1311+
return encodeURIComponent(stringify(param));
13121312
}
13131313

13141314
// Remove any optional markers from optional static segments

0 commit comments

Comments
 (0)