Skip to content
Source
Sign inSign up
TanStack/router

fix(router): `rewriteBasepath` not working without trailing slash #5244

Mergedthenglong(GitHub profile, opens in a new tab)merged 2 commits intomain fromrefs/pull/5244/headmerged by schiller-manuel(GitHub profile, opens in a new tab)

Fixes: https://github.com/TanStack/router/issues/5221

Summary by CodeRabbit

  • Bug Fixes

    • Improved base path handling in routing: URLs that end exactly at the base path or include various leading/trailing slash forms are now recognized and rewritten consistently, preventing navigation failures and incorrect routing across different deployments.
  • Tests

    • Added extensive tests covering many basepath and navigation scenarios to ensure consistent behavior.
    1. Walkthrough

      Replaced regex-based basepath rewriting with explicit normalization and matching logic in the router core; added extensive tests exercising basepath input/output rewriting across many scenarios. No public exports or signatures changed.

      Changes

      Cohort / File(s)Summary of changes
      Router rewrite logic
      packages/router-core/src/rewrite.ts
      Rewrote rewriteBasepath internals: normalize basepath (ensure leading slash, compute trailing-slash variant), compute lowercase variants for case-insensitive handling, detect exact basepath and prefix matches, strip basepath portion or rewrite to /. Output joinPaths call remains unchanged; no export signature changes.
      Tests for basepath handling
      packages/react-router/tests/router.test.tsx
      Added a comprehensive suite of tests for rewriteBasepath covering leading/trailing slash permutations, empty basepath, navigation (Link & programmatic), search/hash preservation, nested/compound rewrites, hostname/subdomain scenarios, and interactions with output rewrites.

      Sequence Diagram(s)

      sequenceDiagram
        autonumber
        participant C as Client
        participant R as Router
        participant RB as rewriteBasepath
      
        C->>R: Request / Navigation with original URL
        R->>RB: rewriteBasepath(inputPath, basepath, options)
        alt basepath is empty or no match
          RB-->>R: return inputPath (unchanged)
        else exact basepath match (e.g., "/app")
          RB-->>R: return "/"
        else basepath prefix match (e.g., "/app/other")
          RB-->>R: return path with basepath stripped ("/other")
        end
        R->>R: joinPaths(outputBase?, rewrittenPath)
        R-->>C: Route using final path

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      Suggested reviewers

      • schiller-manuel
      • Sheraff

      Poem

      I nibble slashes, trim the trail, Normalize each tiny trail. Exact or prefix, I peel away, So routes find home and never stray. Hop, hop — the basepath’s set to play. 🐇✨

      Pre-merge checks and finishing touches

      ❌ Failed checks (1 warning)
      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run @coderabbitai generate docstrings to improve docstring coverage.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title Check✅ PassedThe title clearly specifies that the fix addresses the rewriteBasepath utility failing when a trailing slash is omitted and accurately reflects the main change in the code without extra noise.
      Linked Issues Check✅ PassedThe pull request implements explicit normalization for basepath slashes and rewrites input and output paths to resolve the regression described in issue #5221, and the comprehensive tests confirm the expected behavior for both trailing slash and no-trailing-slash scenarios.
      Out of Scope Changes Check✅ PassedAll changes are focused on enhancing and testing the rewriteBasepath logic in the router-core package and corresponding react-router tests, without introducing modifications unrelated to the basepath handling regression.
      ✨ Finishing touches
      • 📝 Generate Docstrings
        🧪 Generate unit tests
      • Create PR with unit tests
      • Post copyable unit tests in a comment

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core

    3. Actionable comments posted: 1

      📜 Review details

      Configuration used: CodeRabbit UI

      Review profile: CHILL

      Plan: Pro

      📥 Commits

      Reviewing files that changed from the base of the PR and between 7771c00db2141d9cfba41a7e19d865acd02ddc9c and ea4b76b9309852276b4cae58b5f285247ae20cc0.

      📒 Files selected for processing (1)
      • packages/router-core/src/rewrite.ts (1 hunks)
      🧰 Additional context used
      📓 Path-based instructions (2)
      **/*.{ts,tsx}

      📄 CodeRabbit inference engine (AGENTS.md)

      Use TypeScript in strict mode with extensive type safety across the codebase

      Files:

      • packages/router-core/src/rewrite.ts
      packages/router-core/**

      📄 CodeRabbit inference engine (AGENTS.md)

      Keep framework-agnostic core router logic in packages/router-core/

      Files:

      • packages/router-core/src/rewrite.ts
      OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)
    4. schiller-manuel(GitHub profile, opens in a new tab)replied on packages/router-core/src/rewrite.ts lines 25 to 29

      seems reasonable, but a bit complex... maybe there is a simpler solution to that?

    5. coderabbitai[bot](GitHub profile, opens in a new tab)replied on packages/router-core/src/rewrite.ts lines 25 to 29

      @schiller-manuel You're absolutely right! There's a much simpler solution using String.prototype.startsWith() instead of regex. This completely avoids the regex metacharacter issue:

      export function rewriteBasepath(opts: {
        basepath: string
        caseSensitive?: boolean
      }) {
        const trimmedBasepath = trimPath(opts.basepath)
      -  const regex = new RegExp(
      -    `^/${trimmedBasepath}(?:/|$)`,
      -    opts.caseSensitive ? '' : 'i',
      -  )
      +  const fullBasepath = `/${trimmedBasepath}`
      +  const fullBasepathWithSlash = `${fullBasepath}/`
      +  
        return {
          input: ({ url }) => {
      -      url.pathname = url.pathname.replace(regex, '/')
      +      const pathname = opts.caseSensitive ? url.pathname : url.pathname.toLowerCase()
      +      const checkBasepath = opts.caseSensitive ? fullBasepath : fullBasepath.toLowerCase()
      +      const checkBasepathWithSlash = opts.caseSensitive ? fullBasepathWithSlash : fullBasepathWithSlash.toLowerCase()
      +      
      +      if (pathname === checkBasepath) {
      +        url.pathname = '/'
      +      } else if (pathname.startsWith(checkBasepathWithSlash)) {
      +        url.pathname = url.pathname.slice(fullBasepath.length)
      +      }
            return url
          },
          output: ({ url }) => {
            url.pathname = joinPaths(['/', trimmedBasepath, url.pathname])
            return url
          },
        } satisfies LocationRewrite
      }

      This approach:

      • Uses simple string methods instead of regex
      • Handles case sensitivity explicitly
      • Avoids any regex metacharacter issues
      • Is more readable and maintainable
      • Performs the same logic: exact basepath match becomes '/', basepath with trailing content gets the basepath removed
    6. thanks for the PR! can you please add some tests to the base path tests in packages/react-router/tests/router.test.tsx ?

    7. schiller-manuel(GitHub profile, opens in a new tab)replied on packages/router-core/src/rewrite.ts lines 25 to 29

      @thenglong can you please take over this non-regex based approach?

    8. coderabbitai[bot](GitHub profile, opens in a new tab)replied on packages/router-core/src/rewrite.ts lines 25 to 29

      Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

    9. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router

    10. Actionable comments posted: 0

      🧹 Nitpick comments (4)
      packages/router-core/src/rewrite.ts (2)

      31-40: Minor: fast‑path empty basepath and avoid needless work

      Guarding for empty basepath avoids computing lowercase variants and double‑slash checks for every call.

      Apply this diff:

           input: ({ url }) => {
      +      // No-op when basepath is empty (common in tests/configs)
      +      if (!trimmedBasepath) return url
             const pathname = opts.caseSensitive
               ? url.pathname
               : url.pathname.toLowerCase()

      41-47: Handle duplicated basepath prefixes in one pass (eg. /app/app → /)

      When history contains a duplicated basepath (a common artifact when navigating to “/” from a nested route), current logic strips only one prefix and may leave /app, which typically 404s. Fold the exact second prefix to / in the same pass.

      Apply this diff:

             } else if (pathname.startsWith(checkBasepathWithSlash)) {
      -        // Handle basepath with trailing content (e.g., /my-app/users -> /users)
      -        url.pathname = url.pathname.slice(normalizedBasepath.length)
      +        // Handle basepath with trailing content (e.g., /my-app/users -> /users)
      +        const after = url.pathname.slice(normalizedBasepath.length)
      +        // If the remainder is exactly the basepath again (e.g., /my-app/my-app), normalize to '/'
      +        if (
      +          (!opts.caseSensitive && after.toLowerCase() === checkBasepath) ||
      +          (opts.caseSensitive && after === checkBasepath)
      +        ) {
      +          url.pathname = '/'
      +        } else {
      +          url.pathname = after
      +        }
             }

      Suggested test to verify the regression in the linked issue is fully covered (place under “rewriteBasepath utility”):

      it('does not duplicate basepath when navigating to "/" from a nested route', async () => {
        const root = createRootRoute({
          component: () => (
            <div>
              <Link to="/" data-testid="home-link">Home</Link>
              <Outlet />
            </div>
          ),
        })
        const users = createRoute({ getParentRoute: () => root, path: '/users', component: () => <div>Users</div> })
        const router = createRouter({
          routeTree: root.addChildren([users]),
          history: createMemoryHistory({ initialEntries: ['/my-app/users'] }),
          rewrite: rewriteBasepath({ basepath: '/my-app' }),
        })
        render(<RouterProvider router={router} />)
        fireEvent.click(await screen.findByTestId('home-link'))
        await waitFor(() => expect(router.state.location.pathname).toBe('/'))
        expect(router.history.location.pathname).toBe('/my-app')
      })
      packages/react-router/tests/router.test.tsx (2)

      2763-2881: Add a case for navigating to "/" from a nested route (dup basepath guard)

      To prevent regressions like /app/app, add a test that starts at /my-app/users, clicks a Link to "/", and asserts history becomes /my-app and router state "/".

      Here’s a minimal test you can add in this describe block:

      it('navigating to "/" from nested route does not produce /my-app/app', async () => {
        const root = createRootRoute({
          component: () => (
            <div>
              <Link to="/" data-testid="home-link">Home</Link>
              <Outlet />
            </div>
          ),
        })
        const users = createRoute({ getParentRoute: () => root, path: '/users', component: () => <div data-testid="users">Users</div> })
        const routeTree = root.addChildren([users])
        const history = createMemoryHistory({ initialEntries: ['/my-app/users'] })
        const router = createRouter({ routeTree, history, rewrite: rewriteBasepath({ basepath: '/my-app' }) })
        render(<RouterProvider router={router} />)
        fireEvent.click(await screen.findByTestId('home-link'))
        await waitFor(() => expect(router.state.location.pathname).toBe('/'))
        expect(history.location.pathname).toBe('/my-app')
      })

      2883-2927: Consider adding case‑sensitivity and metacharacter basepath tests

      • Default (case-insensitive): basepath 'app' should rewrite '/APP/users' to '/users'.
      • With caseSensitive: true: basepath 'APP' should not rewrite '/app/users'.
      • Metacharacters: basepath 'v1.0' should rewrite '/v1.0/users' to '/users'.

      These ensure the non‑regex implementation is robust across real‑world inputs.

      Example additions:

      it('default is case-insensitive', async () => {
        const root = createRootRoute({ component: () => <Outlet /> })
        const users = createRoute({ getParentRoute: () => root, path: '/users', component: () => <div data-testid="users">Users</div> })
        const router = createRouter({
          routeTree: root.addChildren([users]),
          history: createMemoryHistory({ initialEntries: ['/APP/users'] }),
          rewrite: rewriteBasepath({ basepath: 'app' }),
        })
        render(<RouterProvider router={router} />)
        await waitFor(() => expect(screen.getByTestId('users')).toBeInTheDocument())
        expect(router.state.location.pathname).toBe('/users')
      })
      
      it('caseSensitive=true requires exact case', async () => {
        const root = createRootRoute({ component: () => <Outlet /> })
        const users = createRoute({ getParentRoute: () => root, path: '/users', component: () => <div data-testid="users">Users</div> })
        const router = createRouter({
          routeTree: root.addChildren([users]),
          history: createMemoryHistory({ initialEntries: ['/app/users'] }),
          rewrite: rewriteBasepath({ basepath: 'APP', caseSensitive: true }),
        })
        render(<RouterProvider router={router} />)
        // Should not rewrite, so users component should not render
        await act(() => router.latestLoadPromise)
        expect(screen.queryByTestId('users')).toBeNull()
        expect(router.state.statusCode).toBe(404)
      })
      
      it('handles basepath with dots (metacharacters in old regex impl)', async () => {
        const root = createRootRoute({ component: () => <Outlet /> })
        const users = createRoute({ getParentRoute: () => root, path: '/users', component: () => <div data-testid="users">Users</div> })
        const router = createRouter({
          routeTree: root.addChildren([users]),
          history: createMemoryHistory({ initialEntries: ['/v1.0/users'] }),
          rewrite: rewriteBasepath({ basepath: 'v1.0' }),
        })
        render(<RouterProvider router={router} />)
        await waitFor(() => expect(screen.getByTestId('users')).toBeInTheDocument())
        expect(router.state.location.pathname).toBe('/users')
      })
      📜 Review details

      Configuration used: CodeRabbit UI

      Review profile: CHILL

      Plan: Pro

      📥 Commits

      Reviewing files that changed from the base of the PR and between ea4b76b9309852276b4cae58b5f285247ae20cc0 and ee968963272daeb2217666e179285d8b63b99315.

      📒 Files selected for processing (2)
      • packages/react-router/tests/router.test.tsx (1 hunks)
      • packages/router-core/src/rewrite.ts (1 hunks)
      🧰 Additional context used
      📓 Path-based instructions (3)
      **/*.{ts,tsx}

      📄 CodeRabbit inference engine (AGENTS.md)

      Use TypeScript in strict mode with extensive type safety across the codebase

      Files:

      • packages/react-router/tests/router.test.tsx
      • packages/router-core/src/rewrite.ts
      packages/{react-router,solid-router}/**

      📄 CodeRabbit inference engine (AGENTS.md)

      Implement React and Solid bindings/components only in packages/react-router/ and packages/solid-router/

      Files:

      • packages/react-router/tests/router.test.tsx
      packages/router-core/**

      📄 CodeRabbit inference engine (AGENTS.md)

      Keep framework-agnostic core router logic in packages/router-core/

      Files:

      • packages/router-core/src/rewrite.ts
      🧠 Learnings (1)
      📓 Common learnings
      Learnt from: nlynzaad
      PR: TanStack/router#5182
      File: e2e/react-router/basic-file-based/src/routes/non-nested/named/$baz_.bar.tsx:3-5
      Timestamp: 2025-09-22T00:56:49.237Z
      Learning: In TanStack Router, underscores are intentionally stripped from route segments (e.g., `$baz_` becomes `baz` in generated types) but should be preserved in base path segments. This is the correct behavior as of the fix in PR #5182.
      Learnt from: nlynzaad
      PR: TanStack/router#5182
      File: e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts:167-172
      Timestamp: 2025-09-22T00:56:53.426Z
      Learning: In TanStack Router, underscores are intentionally stripped from route segments during path parsing, but preserved in base path segments. This is the expected behavior implemented in PR #5182.
      🧬 Code graph analysis (1)
      packages/react-router/tests/router.test.tsx (2)
      packages/history/src/index.ts (1)
      • createMemoryHistory (568-614)
      packages/router-core/src/rewrite.ts (1)
      • rewriteBasepath (21-55)
      🔇 Additional comments (2)
      packages/router-core/src/rewrite.ts (1)

      26-28: Good move: dropped regex in favor of string checks

      This eliminates regex metacharacter pitfalls and ReDoS risk while improving readability. Addresses prior review concerns about escaping and complexity.

      packages/react-router/tests/router.test.tsx (1)

      2673-2761: Nice coverage for basepath slash variants

      These cases ensure both leading and trailing slash permutations behave consistently with input rewriting.

    11. the tests dont fail with the current implementation, so something is off here (most likely the tests...)

    12. the tests dont fail with the current implementation, so something is off here (most likely the tests...)

      I'll do a recheck on those tests.

    13. @thenglong I also noticed that throw redirect ignores the basepath as well, didn't see a test here, might be useful to add one for that as well? wdyt @schiller-manuel

    14. @omridevk please create a new github issue for this including a complete minimal reproducer

    15. @schiller-manuel Thanks for the quick response, opened a new issue here: https://github.com/TanStack/router/issues/5300

    16. View your CI Pipeline Execution ↗ for commit b31414ce6f59b284c6638091a692c9d122f60ffc

      CommandStatusDurationResult
      nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded5m 38sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1m 24sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-09-30 20:49:13 UTC

    17. More templates

      @tanstack/arktype-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5244

      @tanstack/directive-functions-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5244

      @tanstack/eslint-plugin-router

      npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5244

      @tanstack/history

      npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5244

      @tanstack/nitro-v2-vite-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5244

      @tanstack/react-router

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5244

      @tanstack/react-router-devtools

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5244

      @tanstack/react-router-ssr-query

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5244

      @tanstack/react-start

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5244

      @tanstack/react-start-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5244

      @tanstack/react-start-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5244

      @tanstack/router-cli

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5244

      @tanstack/router-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5244

      @tanstack/router-devtools

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5244

      @tanstack/router-devtools-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5244

      @tanstack/router-generator

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5244

      @tanstack/router-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5244

      @tanstack/router-ssr-query-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5244

      @tanstack/router-utils

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5244

      @tanstack/router-vite-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5244

      @tanstack/server-functions-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5244

      @tanstack/solid-router

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5244

      @tanstack/solid-router-devtools

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5244

      @tanstack/solid-start

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5244

      @tanstack/solid-start-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5244

      @tanstack/solid-start-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5244

      @tanstack/start-client-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5244

      @tanstack/start-plugin-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5244

      @tanstack/start-server-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5244

      @tanstack/start-static-server-functions

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5244

      @tanstack/start-storage-context

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5244

      @tanstack/valibot-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5244

      @tanstack/virtual-file-routes

      npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5244

      @tanstack/zod-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5244

      commit: b31414c

    18. @thenglong sorry i was running the tests in the wrong package and therefore mistakenly thought that they ran without the fix. i updated the PR slightly and will merge asap

Sign in to join this conversation.