Setup Module Federation with SSR for Angular and React

This guide will walk you through creating a Module Federated setup with Server Side Rendering (SSR) for Angular and React using Nx and its generators.

Steps

Create an empty workspace

Run the following command with the options listed to create an empty workspace.

~โฏ

npx create-nx-workspace@latest

1 2 > NX Let's create a new workspace [https://nx.dev/getting-started/intro] 3 4โœ” Where would you like to create your workspace? ยท myorg 5โœ” Which stack do you want to use? ยท none 6โœ” Package-based or integrated? ยท integrated 7โœ” Enable remote caching to make your CI faster ยท Yes 8
Opting into Nx Cloud

You will also be prompted whether to add Nx Cloud to your workspace. We won't address this in this recipe, but you can see the introduction to Nx Cloud for more details.

Install your framework plugin

Keep Nx Package Versions In Sync

Make sure to install the @nx/angular or @nx/react versions that matches the version of nx in your repository. If the version numbers get out of sync, you can encounter some difficult to debug errors. You can fix Nx version mismatches with this recipe.

~/myorgโฏ

npm install --save-dev @nx/angular

1 2
Nx 15 and lower use @nrwl/ instead of @nx/

Generating a host and multiple remotes with SSR

We will generate the apps required for a storefront application.
We will need the following applications:

  • Store - host application
  • Product - remote application
  • Checkout - remote application

Nx allows you to do this with a single command:

~/myorgโฏ

npx nx g @nx/angular:host store --ssr --remotes=product,checkout

1 2
Nx 15 and lower use @nrwl/ instead of @nx/

This will generate three applications, set up with SSR and Module Federation.

Serving the store application

When using Module Federation, we want to serve the host application along with the remote applications so that everything works as expected.

To do this, run:

~/myorgโฏ

npx nx serve-ssr store

1 2

This will run all three application servers but only the store will be watching for file changes. If you make a change to one of the remote applications (checkout or product) the changes will not be hot reloaded.

Serving the store application with file watching for checkout

If working on a remote application, we can still serve it via the host application and have it watch for changes.

To serve the store application and watch for changes on the checkout application run:

~/myorgโฏ

npx nx serve-ssr store --devRemotes=checkout

1 2

Additional Resources

To learn more about Module Federation, we have some resources you might find useful: