Skip to content

Commit db27be2

Browse files
evanpurkhiserc298lee
authored andcommitted
feat(rr6): Add shim to avoid crashing on ? in {pathname} (#77167)
1 parent ce2b728 commit db27be2

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

static/app/utils/reactRouter6Compat/location.tsx

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {Location as Location6, To} from 'react-router-dom';
2+
import * as Sentry from '@sentry/react';
23
import type {Location as Location3, LocationDescriptor, Query} from 'history';
34
import * as qs from 'query-string';
45

@@ -10,18 +11,61 @@ export function locationDescriptorToTo(path: LocationDescriptor): To {
1011
return path;
1112
}
1213

14+
let query = path.query ? {...path.query} : undefined;
15+
1316
const to: To = {
1417
pathname: path.pathname,
1518
};
1619

20+
// XXX(epurkhiser): In react router 3 it was possible to include the search
21+
// query parameters in te pathname field of a LocationDescriptor. You can no
22+
// longer do this with 6 and it will result in an error
23+
//
24+
// > Cannot include a '?' character in a manually specified `to.pathname` field
25+
//
26+
// To shim for this, since there may be some hiding around, we can extract
27+
// out the query string, parse it, and merge it into the path query object.
28+
29+
if (to.pathname?.endsWith('?')) {
30+
to.pathname = to.pathname.slice(0, -1);
31+
}
32+
33+
if (to.pathname?.includes('?')) {
34+
const parts = to.pathname.split('?');
35+
36+
Sentry.captureMessage('Got pathname with `?`', scope =>
37+
scope.setExtra('LocationDescriptor', path)
38+
);
39+
40+
if (parts.length > 2) {
41+
Sentry.captureMessage(
42+
'Unexpected number of `?` when shimming search params in pathname for react-router 6'
43+
);
44+
}
45+
46+
const [pathname, search] = parts;
47+
48+
if (search && path.search) {
49+
Sentry.captureMessage('Got search in pathname and as part of LocationDescriptor');
50+
}
51+
52+
to.pathname = pathname;
53+
54+
if (query) {
55+
query = {...query, ...qs.parse(search)};
56+
} else {
57+
query = qs.parse(search);
58+
}
59+
}
60+
1761
if (path.hash) {
1862
to.hash = path.hash;
1963
}
2064
if (path.search) {
2165
to.search = path.search;
2266
}
23-
if (path.query) {
24-
to.search = `?${qs.stringify(path.query)}`;
67+
if (query) {
68+
to.search = `?${qs.stringify(query)}`;
2569
}
2670

2771
// XXX(epurkhiser): We ignore the location state param

0 commit comments

Comments
 (0)