Handling module federation failure in host app

Viewed 2376

How do we handle failures in host react app, when the app which is dynamically loaded using module federation is down? I'm testing a scenario where I've bought down the module federation app and testing the host app gives this error, Load script failed error : localhost/remoteentry.js.

This is a genuine scenario where the app which is likely to be imported maybe down or have an issue.

2 Answers

There is no in build mechanic from module-federation to handle async load failures. You have to do that yourself with the usual mechanics for lazy fetched content also used outside of micro frontends. For example in react you could use React.lazy (docs, example) together with React.Suspense (docs, example) to provide a proper fallback.

You can use an ErrorBoundary component to wrap your exposed module, so on you host app you can have:

const MFWrapper = ({ children }) => {
  return (
    <Suspense fallback="Loading...">
      <ErrorBoundary>{children}</ErrorBoundary>
    </Suspense>
  )
}


const renderMF = (Component) => (
  <MFWrapper>
    <Component />
  </MFWrapper>
)

and then on the Router:

const ExposedComponent = lazy(() => import('ExposedComponent/ExposedComponent'))

const Routes = () => {
  return (
    <Switch>
      <Route path="*" render={() => renderMF(ExposedComponent)} />
    </Switch>
  )
}

export default Routes

By doing that, any error that comes from the ExposedComponent will not affect the host app.

Related