diff --git a/.changeset/tender-sheep-bake.md b/.changeset/tender-sheep-bake.md new file mode 100644 index 0000000000..8194e94970 --- /dev/null +++ b/.changeset/tender-sheep-bake.md @@ -0,0 +1,5 @@ +--- +"react-router": patch +--- + +Fix `basename` usage without a leading slash in data routers diff --git a/contributors.yml b/contributors.yml index b6384a4eb9..7d7fbc856b 100644 --- a/contributors.yml +++ b/contributors.yml @@ -274,6 +274,7 @@ - mtendekuyokwa19 - mtliendo - namoscato +- nanianlisao - ned-park - nenene3 - ngbrown diff --git a/packages/react-router/__tests__/router/router-test.ts b/packages/react-router/__tests__/router/router-test.ts index 07907477dd..d1dc920151 100644 --- a/packages/react-router/__tests__/router/router-test.ts +++ b/packages/react-router/__tests__/router/router-test.ts @@ -237,6 +237,38 @@ describe("a router", () => { }); }); + it("supports a basename prop for route matching without a leading slash", async () => { + let history = createMemoryHistory({ + initialEntries: ["/base/name/path"], + }); + let router = createRouter({ + basename: "base/name", + routes: [{ path: "path" }], + history, + }); + expect(router.state).toMatchObject({ + location: { + hash: "", + key: expect.any(String), + pathname: "/base/name/path", + search: "", + state: null, + }, + matches: [ + { + params: {}, + pathname: "/path", + pathnameBase: "/path", + route: { + id: "0", + path: "path", + }, + }, + ], + initialized: true, + }); + }); + it("supports subscribers", async () => { let history = createMemoryHistory({ initialEntries: ["/"] }); let count = 0; diff --git a/packages/react-router/lib/router/router.ts b/packages/react-router/lib/router/router.ts index c9e9809c96..cbd46db3b4 100644 --- a/packages/react-router/lib/router/router.ts +++ b/packages/react-router/lib/router/router.ts @@ -867,6 +867,9 @@ export function createRouter(init: RouterInit): Router { ); let inFlightDataRoutes: AgnosticDataRouteObject[] | undefined; let basename = init.basename || "/"; + if (!basename.startsWith("/")) { + basename = `/${basename}`; + } let dataStrategyImpl = init.dataStrategy || defaultDataStrategyWithMiddleware; // Config driven behavior flags