Search code examples
javascriptreactjsreact-routerfrontendmicro-frontend

React Routes not working with Module Federation


So I'm using React v18, Router v6 and Module federation

this is root app routes

this is Payments app routes in .packages/payments/scr/app

the problem is that Payments page is rendered and working fine, but all routes inside Payments not working at all this is what i get, no errors

My guess is that routes inside Payments are just not initialized and I don't understand why.All bootstrap.jsx files are made accordingly by React v18 docs

Adding BrowserRouter inside Payments app is causing error

You cannot render <Router> inside another <Router>

Maybe I don't see something, let me know if you need any additional setup details.


Solution

  • The main App code is correct when it appends a wildcard "*" matcher to the routes for the descendent routes to be matched.

    <Route
      path="/payments-kz/*"
      element={<PaymentsKzPage store={store} />}
    />
    

    The issue is in the PaymentsKzPage rendering the descendent routes. The nested Routes component builds its routes relative to the parent route, e.g. "/payments-kz". The descendent routes are incorrectly prepending a "payments-kz" path segment.

    Example:

    <Route
      path="/payments-kz/catalog/:categoryId/providers/:subcategoryId"
      element={<Providers />}
    />
    

    The path actually resolves to:

    "/payments-kz/payments-kz/catalog/:categoryId/providers/:subcategoryId"

    To resolve the issue you should remove the "/payments-kz" segment from the descendent routes.

    <Routes>
      <Route
        path="/catalog/:categoryId/providers/:subcategoryId"
        element={<Providers />}
      />
      <Route path="/catalog/:id/:category" element={<Subcategories />} />
      <Route path="/catalog/:id" element={<Subcategories />} />
      <Route path="/providers/:subcategoryId" element={<Providers />} />
      .... etc ...
    </Routes>