Advanced Angular Micro Frontends with Dynamic Module Federation

Dynamic Module Federation is a technique that allows an application to determine the location of its remote applications at runtime. It helps to achieve the use case of “Build once, deploy everywhere”.

“Build once, deploy everywhere” is the concept of being able to create a single build artifact of your application and deploy it to multiple environments such as staging and production.

The difficulty in achieving this with a Micro Frontend Architecture using Static Module Federation is that our Remote applications will have a different location (or URL) in each environment. Previously, to account for this, we would have had to specify the deployed location of the Remote applications and rebuild the application for the target environment.

This guide will walk through how the concept of “Build once, deploy everywhere” can be easily achieved in a Micro Frontend Architecture that uses Dynamic Module Federation.

Aim

The aim of this guide is three-fold. We want to be able to:

  • Set up a Micro Frontend with Static Module Federation
  • Transform an existing Static Module Federation setup to use Dynamic Federation
  • Generate a new Micro Frontend application that uses Dynamic Federation

What we’ll build

To achieve the aims, we will do the following:

  • Create a Static Federation Micro Frontend Architecture
  • Change the Dashboard application to use Dynamic Federation
  • Generate a new Employee Dashboard application that will use Dynamic Federation
    • It should use the existing Login application.
    • It should use a new Todo application.

Final Code

Here's the source code of the final result for this guide.

Example repository/Coly010/nx-ng-dyn-fed

First steps

Create an Nx Workspace

To start with, we need to create a new Nx Workspace and add the Nx Angular plugin. We can do this easily with:

~/

npx create-nx-workspace@latest ng-mf --preset=apps

1 NX Let's create a new workspace [https://nx.dev/getting-started/intro] 2 3✔ Which CI provider would you like to use? · skip 4✔ Would you like remote caching to make your build faster? · skip 5 6

Next run:

cd ng-mf

npx nx add @nx/angular

Creating our applications

We need to generate two applications that support Module Federation.

We'll start with the Admin Dashboard application which will act as a host application for the Micro-Frontends (MFEs):

nx g @nx/angular:host apps/dashboard --prefix=ng-mf

Running nx commands

The terminal examples in this guide will show nx being run as if it is installed globally. If you have not installed Nx globally (not required), you can use your package manager to run the nx local binary:

  • NPM: npx nx ...
  • Yarn: yarn nx ...
  • PNPM: pnpm nx ...

The host generator will create and modify the files needed to set up the Angular application.

Now, let's generate the Login application as a remote application that will be consumed by the Dashboard host application.

nx g @nx/angular:remote apps/login --prefix=ng-mf --host=dashboard

Note how we provided the --host=dashboard option. This tells the generator that this remote application will be consumed by the Dashboard application. The generator performed the following changes to automatically link these two applications together:

  • Added the remote to the apps/dashboard/module-federation.config.ts file
  • Added a TypeScript path mapping to the root tsconfig file
  • Added a new route to the apps/dashboard/src/app/app.routes.ts file

What was generated?

Let's take a closer look after generating each application.

For both applications, the generators did the following:

  • Created the standard Angular application files
  • Added a module-federation.config.ts file
  • Added a webpack.config.ts and webpack.prod.config.ts
  • Added a src/bootstrap.ts file
  • Moved the code that is normally in src/main.ts to src/bootstrap.ts
  • Changed src/main.ts to dynamically import src/bootstrap.ts (this is required for the Module Federation to load versions of shared libraries correctly)
  • Updated the build target in the project.json to use the @nx/angular:webpack-browser executor (this is required to support passing a custom Webpack configuration to the Angular compiler)
  • Updated the serve target to use @nx/angular:dev-server (this is required as we first need Webpack to build the application with our custom Webpack configuration)

The key differences reside within the configuration of the Module Federation Plugin within each application's module-federation.config.ts.

We can see the following in the Login micro frontend configuration:

apps/login/module-federation.config.ts
1import { ModuleFederationConfig } from '@nx/webpack'; 2 3const config: ModuleFederationConfig = { 4 name: 'login', 5 exposes: { 6 './Routes': 'apps/login/src/app/remote-entry/entry.routes.ts', 7 }, 8}; 9 10export default config; 11

Taking a look at each property of the configuration in turn:

  • name is the name that Webpack assigns to the remote application. It must match the name of the project.
  • exposes is the list of source files that the remote application exposes to consuming shell applications for their own use.

This config is then used in the webpack.config.ts file:

apps/login/webpack.config.ts
1import { withModuleFederation } from '@nx/angular/module-federation'; 2import config from './module-federation.config'; 3 4export default withModuleFederation(config, { dts: false }); 5

We can see the following in the Dashboard micro frontend configuration:

apps/dashboard/module-federation.config.ts
1import { ModuleFederationConfig } from '@nx/webpack'; 2 3const config: ModuleFederationConfig = { 4 name: 'dashboard', 5 remotes: ['login'], 6}; 7 8export default config; 9

The key difference to note with the Dashboard configuration is the remotes array. This is where you list the remote applications you want to consume in your host application.

You give it a name that you can reference in your code, in this case login. Nx will find where it is served.

Now that we have our applications generated, let's move on to building out some functionality for each.

Adding Functionality

We'll start by building the Login application, which will consist of a login form and some very basic and insecure authorization logic.

User Library

Let's create a user data-access library that will be shared between the host application and the remote application. This will be used to determine if there is an authenticated user as well as providing logic for authenticating the user.

nx g @nx/angular:lib libs/shared/data-access-user

This will scaffold a new library for us to use.

We need an Angular Service that we will use to hold state:

nx g @nx/angular:service libs/shared/data-access-user/src/lib/user

This will create the libs/shared/data-access-user/src/lib/user.service.ts file. Change its contents to match:

libs/shared/data-access-user/src/lib/user.service.ts
1import { Injectable } from '@angular/core'; 2import { BehaviorSubject } from 'rxjs'; 3 4@Injectable({ providedIn: 'root' }) 5export class UserService { 6 private isUserLoggedIn = new BehaviorSubject(false); 7 isUserLoggedIn$ = this.isUserLoggedIn.asObservable(); 8 9 checkCredentials(username: string, password: string) { 10 if (username === 'demo' && password === 'demo') { 11 this.isUserLoggedIn.next(true); 12 } 13 } 14 15 logout() { 16 this.isUserLoggedIn.next(false); 17 } 18} 19

Now, export the service in the library's entry point file:

libs/shared/data-access-user/src/index.ts
1... 2export * from './lib/user.service'; 3

Login Application

Let's set up our entry.component.ts file in the Login application so that it renders a login form. We'll import FormsModule and inject our UserService to allow us to sign the user in:

apps/login/src/app/remote-entry/entry.component.ts
1import { Component } from '@angular/core'; 2import { CommonModule } from '@angular/common'; 3import { FormsModule } from '@angular/forms'; 4import { UserService } from '@ng-mf/data-access-user'; 5import { inject } from '@angular/core'; 6 7@Component({ 8 standalone: true, 9 imports: [CommonModule, FormsModule], 10 selector: 'ng-mf-login-entry', 11 template: ` 12 <div class="login-app"> 13 <form class="login-form" (ngSubmit)="login()"> 14 <label> 15 Username: 16 <input type="text" name="username" [(ngModel)]="username" /> 17 </label> 18 <label> 19 Password: 20 <input type="password" name="password" [(ngModel)]="password" /> 21 </label> 22 <button type="submit">Login</button> 23 </form> 24 <div *ngIf="isLoggedIn$ | async">User is logged in!</div> 25 </div> 26 `, 27 styles: [ 28 ` 29 .login-app { 30 width: 30vw; 31 border: 2px dashed black; 32 padding: 8px; 33 margin: 0 auto; 34 } 35 .login-form { 36 display: flex; 37 align-items: center; 38 flex-direction: column; 39 margin: 0 auto; 40 padding: 8px; 41 } 42 label { 43 display: block; 44 } 45 `, 46 ], 47}) 48export class RemoteEntryComponent { 49 private userService = inject(UserService); 50 username = ''; 51 password = ''; 52 isLoggedIn$ = this.userService.isUserLoggedIn$; 53 54 login() { 55 this.userService.checkCredentials(this.username, this.password); 56 } 57} 58
More details

This could be improved with things like error handling, but for the purposes of this tutorial, we'll keep it simple.

Now let's serve the application and view it in a browser to check that the form renders correctly.

nx run login:serve

We can see if we navigate a browser to http://localhost:4201 that we see the login form rendered.

If we type in the correct username and password (demo, demo), then we can also see the user gets authenticated!

Perfect! Our Login application is complete.

Dashboard Application

Now let's update our Dashboard application. We'll hide some content if the user is not authenticated, and present them with the Login application where they can log in.

For this to work, the state within UserService must be shared across both applications. Usually, with Module Federation in Webpack, you have to specify the packages to share between all the applications in your Micro Frontend solution. However, by taking advantage of Nx's project graph, Nx will automatically find and share the dependencies of your applications.

Single version policy

This helps to enforce a single version policy and reduces the risk of Micro Frontend Anarchy.

Start by deleting the app.component.html, app.component.css, and nx-welcome.component.ts files from the Dashboard application. They will not be needed for this tutorial.

Next, let's add our logic to the app.component.ts file. Change it to match the following:

apps/dashboard/src/app/app.component.ts
1import { CommonModule } from '@angular/common'; 2import { Component, inject, OnInit } from '@angular/core'; 3import { Router, RouterModule } from '@angular/router'; 4import { UserService } from '@ng-mf/data-access-user'; 5import { distinctUntilChanged } from 'rxjs/operators'; 6 7@Component({ 8 standalone: true, 9 imports: [CommonModule, RouterModule], 10 selector: 'ng-mf-root', 11 template: ` 12 <div class="dashboard-nav">Admin Dashboard</div> 13 <div *ngIf="isLoggedIn$ | async; else signIn"> 14 You are authenticated so you can see this content. 15 </div> 16 <ng-template #signIn><router-outlet></router-outlet></ng-template> 17 `, 18}) 19export class AppComponent implements OnInit { 20 private router = inject(Router); 21 private userService = inject(UserService); 22 isLoggedIn$ = this.userService.isUserLoggedIn$; 23 24 ngOnInit() { 25 this.isLoggedIn$ 26 .pipe(distinctUntilChanged()) 27 .subscribe(async (loggedIn) => { 28 // Queue the navigation after initialNavigation blocking is completed 29 setTimeout(() => { 30 if (!loggedIn) { 31 this.router.navigateByUrl('login'); 32 } else { 33 this.router.navigateByUrl(''); 34 } 35 }); 36 }); 37 } 38} 39

Finally, make sure the application routes are correctly set up:

apps/dashboard/src/app/app.routes.ts
1import { Route } from '@angular/router'; 2import { AppComponent } from './app.component'; 3 4export const appRoutes: Route[] = [ 5 { 6 path: 'login', 7 loadChildren: () => import('login/Routes').then((m) => m.remoteRoutes), 8 }, 9 { 10 path: '', 11 component: AppComponent, 12 }, 13]; 14

We can now run both the Dashboard and Login applications:

nx serve dashboard --devRemotes=login

Navigating to http://localhost:4200 should show the Dashboard application with the Login application embedded within it. If you log in, you should see the content change to show that you are authenticated.

This concludes the setup required for a Micro Frontend approach using Static Module Federation.

Do not fret!

When serving module federation apps locally in dev mode, there'll be an error output to the console: import.meta cannot be used outside of a module. You'll see the error originates from the styles.js script. It's a known error output, and as far as our testing has shown, it doesn't cause any breakages. It happens because the Angular compiler attaches the styles.js file to the index.html in a <script> tag with defer.

It needs to be attached with type=module, but Angular can't make that change because it breaks HMR. They also provide no way of hooking into that process for us to patch it ourselves.

The good news is that the error doesn't propagate to production because styles are compiled to a CSS file, so there's no erroneous JS to log an error.

It's worth stressing that no errors or breakages have been noted from our tests.

Converting the Dashboard application

The Dashboard application is a Host application that loads the Remote applications at runtime based on their deployed locations when the application was built using Static Module Federation.

We want to change this so that the Dashboard application can make a network request at runtime to find out the deployed locations of the Remote applications.

There are 3 steps involved with this:

  • Make a network request to fetch the locations of the Remote applications (the Remote Definitions).
  • Set the Remote Definitions so that webpack is aware of how to find the Remote applications when requested.
  • Change how we load the Remote applications so that webpack can fetch any required files correctly.

Fetch and Set the Remote Definitions

Perhaps one of the easiest methods of fetching the Remote Definitions at runtime is to store them in a JSON file that can be present in each environment. The Host application then only has to make a GET request to the JSON file.

We’ll start by creating this file. Add a module-federation.manifest.json file to the src/public/ folder in our Dashboard application with the following content:

apps/dashboard/src/public/module-federation.manifest.json
1{ 2 "login": "http://localhost:4201" 3} 4

Next, open the main.ts file and replace it with the following:

apps/dashboard/src/main.ts
1import { setRemoteDefinitions } from '@nx/angular/mf'; 2 3fetch('/module-federation.manifest.json') 4 .then((res) => res.json()) 5 .then((definitions) => setRemoteDefinitions(definitions)) 6 .then(() => import('./bootstrap').catch((err) => console.error(err))); 7

You’ll notice that we fetch the JSON file and provide its contents to the setRemoteDefinitions function we invoke next. This tells webpack where each of our remote applications has been deployed to!

Change how Remotes are loaded

At the moment, webpack is statically building our application, telling it at build time where our Remotes are. That is because they are specified in the module-federation.config.ts file.

Open the module-federation.config.ts file at the root of our apps/dashboard/ folder and set the remotes property to be an empty array. It should look like this:

apps/dashboard/module-federation.config.ts
1import { ModuleFederationConfig } from '@nx/webpack'; 2 3const config: ModuleFederationConfig = { 4 name: 'dashboard', 5 remotes: [], 6}; 7 8export default config; 9

Next, we need to change how our application attempts to load the Remote when it is routed to. Open the app.routes.ts file under the src/app/ folder and apply the following changes:

apps/dashboard/src/app/app.routes.ts
1import { Route } from '@angular/router'; 2import { loadRemoteModule } from '@nx/angular/mf'; 3import { AppComponent } from './app.component'; 4 5export const appRoutes: Route[] = [ 6 { 7 path: 'login', 8 loadChildren: () => 9 loadRemoteModule('login', './Routes').then((m) => m.remoteRoutes), 10 }, 11 { 12 path: '', 13 component: AppComponent, 14 }, 15]; 16

The loadRemoteModule helper method simply hides some logic that will check if the Remote application has been loaded, and if not, load it, and then requests the correct exposed routes from it.

Summary

That’s all the changes required to replace Static Module Federation with Dynamic Module Federation.

Running:

nx serve dashboard --devRemotes=login

Should result in the same behaviour as before, except that our Dashboard application is waiting until runtime to find out the deployed location of our Login application.

In the next section, we will see how Nx’s generators can be used to automate a lot of this process for us!


Creating a new Dynamic Host application

Nx provides generators that aim to streamline the process of setting up a Dynamic Micro Frontend architecture.

To showcase this, let’s create a new Host application that will use our previous Login application as well as a new Todo Remote application.

Generate the Employee Host application

Run the following command to generate a new Host application that is preconfigured for Dynamic Federation and add specify the Login Remote application we want to add:

nx g @nx/angular:host apps/employee --remotes=login --dynamic

This will generate:

  • Angular application
  • Webpack Configuration (webpack.config.ts)
  • Module Federation Configuration (module-federation.config.ts)
  • Micro Frontend Manifest File (module-federation.manifest.json)
  • Changes to the bootstrap of application to fetch the Micro Frontend Manifest, set the Remote Definitions and load the Login application correctly

You should take a look at the files generated and see how the Login Remote application was added to the module-federation.manifest.json file and the slight changes to main.ts and app.routes.ts to load the Remotes dynamically.

Generate the Todo Remote application

We’re going to demonstrate how when specifying a dynamic Host when adding a new Remote application, the Remote application will be added to the Host’s Micro Frontend Manifest file correctly.

nx g @nx/angular:remote apps/todo --host=employee

You’ll note that this will generate the same output as the Login Remote application in the previous guide. There’s one difference. Because the Host application is using Dynamic Federation, the new Remote will be added to the Host’s module-federation.manifest.json.

Summary

Dynamic Federation is the perfect way to solve the problem of “Build once, deploy everywhere”. It can be used in tandem with CD solutions that involve spinning up environments for different stages of the release process without having to rebuild the application at all. The CD pipeline only ever needs to replace a JSON file on that environment with one that contains the correct values for the deployed locations of the remote applications.