Nextjs module federation with standalone servers

Viewed 1188

I'm trying to use module federation (webpack 5) beetween nextjs applications. I started from this example (two nextjs applications) and everything works as expected. From my point of view the problem is that this works only if i have both app on the same host. The relevant webpack configuration part on next.config.js is below (the same in the other app)

....
      remotes: {
        next1: isServer
          ? path.resolve(
              __dirname,
              "../next1/.next/server/static/runtime/remoteEntry.js"
            )
          : "next1",
      },
...

If i just remove the server configuration it doesn't works.

It is possible to use module federation between nextjs app without configure the remote server by folder path and reference the remote app only by url ?

1 Answers

It is possible, but it won't work with SSR. Just leave the remote with the global for client side:

  // next.config.js
  ....
    remotes: {
      next1: "next1",
    },
  ...

Create your component and import the remote:

   // component.js
   const Component = (await import("next1/component")).default
   export default Component

And finally in your page, lazy load your remote component with SSR disabled:

  // mypage.js
  import dynamic from 'next/dynamic'
    
  const RemoteComponent = dynamic(
    () => import('../components/component.js'),
    { ssr: false }
  )
    
  const MyPage = () => (<RemoteComponent />)
  export default MyPage

There's a working sample here: https://mf-shell.vercel.app/

And the code: https://github.com/schalela/mf-nextjs

Related