27,59 €
Although deservedly popular and highly performant tools for building modern web applications, React and single-page applications (SPAs) become more and more sluggish as your applications and teams grow. To solve this problem, many large web apps have started to break down monolith SPAs into independently deployable smaller apps and components—a pattern called micro frontends. But micro frontends aren't a perfect solution, but rather a double-edged sword. This book teaches you how to architect and build them with the right principles to reap all the benefits without the pitfalls.
This book will take you through two patterns of building micro frontends, the multi-SPA pattern and the micro apps pattern. You’ll find out which patterns to use and when, as well as take a look at the nuances of deploying these micro frontends using cloud-native technologies such as Kubernetes and Firebase. With the help of this book, you’ll gain an in-depth understanding of state management, solving problems with routing, and deployment strategies between the different micro frontends.
By the end of this book, you’ll have learned how to design and build a React-based micro frontend application using module federation and deploy it to the cloud efficiently.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 248
Veröffentlichungsjahr: 2023
Building Micro Frontends with React 18
Develop and deploy scalable applications using micro frontend strategies
Vinci J Rufus
BIRMINGHAM—MUMBAI
Copyright © 2023 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Kushal Dave
Senior Editor: Aamir Ahmed
Book Project Manager: Sonam Pandey
Technical Editor: K Bimala Singha
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Manju Arasan
Production Designer: Ponraj Dhandapani
DevRel Marketing Coordinator: Nivedita Pandey
First published: September 2023
Production reference: 1180923
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB
ISBN 978-1-80461-096-1
www.packtpub.com
Vinci J Rufus is VP of Technology with Publicis Sapient, with over 25 years of experience in leading teams that build rich web and internet applications for top retail brands. He was an early pioneer in adopting HTML5 and JavaScript frameworks such as Angular, React, and serverless technologies to deploy web apps in production.
For the past 5 years, Vinci has specialized in architecting and implementing micro frontends. He enjoys the technical challenges and complexity these systems entail.
At his core, Vinci is an engineer who loves collaborating directly with his team to solve real-world problems. He still codes regularly and stays hands-on with the latest technologies.
Vinci is particularly fascinated by emerging technologies such as edge computing and generative AI. He sees enormous potential in how these innovations can transform the way we develop software in the coming years.
To Sheldon Monteiro and the entire leadership team at the Chief Marketing Technology Officer University (CMTOu) – where my journey into micro frontends all began.
I am tremendously thankful for the guidance, support, and opportunities provided by my leaders at Publicis Sapient, Tilak Doddapaneni and Rakesh Ravuri. Your trust in allowing me to explore cutting-edge technologies has been instrumental in my knowledge of micro frontends. My sincere appreciation to the outstanding experience Engineering community at Publicis Sapient, from whom I have learned so much.
A huge thank you to Sourav Mondal for our many brainstorming and debugging. Thanks to Nuala Monaghan, Devesh Kaushal, Hari Om Bangari and Davide Fortuna for those additional reviews, comments and feedback. I am grateful for your time and insight. Most importantly, I wish to express my deepest love and gratitude to my amazing wife, Raina, and wonderful children, Shannon and Jaden. Your unrelenting support and understanding during our many sacrificed holidays have made this book possible. I could not have done this without you.
Alberto Arias López is a continuously evolving software engineer with extensive work experience building consumer-focused online products and services in different domains within a number of international companies of all sizes. He has witnessed the evolution of the frontend, empowering developers to build more complex web applications each time that improve the user experience. Nevertheless, it is still a young software engineering area compared to others. Micro frontends is a step further that allows the community to keep evolving and responding to the increasing demand of the product life cycle.
The work I’ve done on this book is dedicated to my family: my parents, Ana María and Antonio, and my brothers, Antonio and Chumy. I love you.
I would also like to mention all the professional mates I have had the opportunity to know and learn from during the journey – teamwork is invaluable.
Israel Antonio Rosales Laguan is an experienced full stack software engineer using JavaScript, React, and Node.js, with a focus on process improvement, developer ergonomics, systems integration, and pipeline automation. He also has a lot of experience in international SCRUM teams and mentoring others, working in Equinox, OnDeck, and Lazard, among others. Other expertise: OWASP compliance, GraphQL, CI/CD with Docker, and advanced CSS.
Microfrontends have emerged as a popular architectural pattern for building large, complex web applications by breaking them down into smaller, independent pieces that can be developed and deployed separately. This makes it easier to scale development, accelerate release velocity, and adopt new technologies incrementally.
This book provides a comprehensive guide to implementing micro frontends in practice, from architectural principles and patterns to hands-on examples using frameworks such as React. You will learn how to divide a monolithic application into autonomous micro frontends. We will look at some of the key principles of micro frontends and scenarios where micro frontends may or may not be the right pattern.
We will explore the different patterns of micro frontends and create micro frontends using module federation for client-side rendered apps and server-side rendered apps.
We will learn how to deal with things such as routing and state management when building micro frontends, and finally, we will learn how to deploy our micro frontends on Firebase and on a Kubernetes cluster using Azure.
This book is for frontend and full stack developers aiming to build large, scalable web applications using modern JavaScript frameworks such as React. It will also benefit solution architects looking to adopt micro frontend architecture. You should have a good understanding of JavaScript, React, module bundling, and basic web development concepts.
Chapter 1, Introducing Microfrontends, introduces different architectural patterns, such as the multi-SPA and micro apps pattern for building micro frontends.
Chapter 2, Key Principles and Components of Microfrontends, covers core principles such as independent deployability, bounded contexts, isolating failures, runtime integrations, and so on.
Chapter 3, Monorepos versus Polyrepos for Microfrontends, compares monorepos and multirepos for managing micro frontend code bases, and why monorepos are preferred for building microfrontends.
Chapter 4, Implementing the Multi-SPA Pattern for Microfrontends, demonstrates building micro frontends as a collection of Single-Page Apps.
Chapter 5, Implementing the Micro-Apps Pattern for Microfrontends, dives deeper into building micro frontends using module federation and covering critical topics around routing and sharing state between different micro apps.
Chapter 6, Server-Rendered Microfrontends, shows how to go about building a server-side rendered micro-frontend using module federation.
Chapter 7, Deploying Microfrontends to Static Storage, takes us through the journey of deploying our micro frontend to a static storage hosting service such as Firebase.
Chapter 8, Deploying Microfrontends to Kubernetes, demonstrates deploying micro frontends to Kubernetes such as AKS on Azure.
Chapter 9, Managing Microfrontends in Production, covers topics such as branching strategies, versioning, rollback strategies, and feature toggles that are essential to managing micro frontends in production.
Chapter 10, Common Pitfalls to avoid when Building Microfrontends, talks about some of the common mistakes developers and architects make that negatively impact the benefits of why we chose micro frontends in the first place.
Chapter 11, Latest Trends in Microfrontends, covers some of the new trends, such as ES builds, cloud or edge functions, island patterns, and generative AI, and how they could be used to build micro frontends in the future.
The code examples use React, webpack, Node.js, and npm. Familiarity with these tools will be helpful. The examples can be followed on any operating system.
The digital version of this book includes detailed code examples that can be copied and pasted to get up and running quickly. For the best learning experience, try building the examples yourself from scratch.
Software/hardware covered in the book
Operating system requirements
React 18
Windows, macOS, or Linux
TypeScript 3.7
Windows, macOS, or Linux
Docker Engine 24
Windows, macOS, or Linux
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Building-Micro-Frontends-with-React-18. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Ensure we have the URL routing set up in the proxy.conf.json file.”
A block of code is set as follows:
"scripts": { "start": "nx serve", "build": "nx build", "test": "nx test", "serve:all": "nx run-many --target=serve" },When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
pnpm install semantic-ui-react semantic-ui-cssAny command-line input or output is written as follows:
pnpm serve:allBold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Next, we update the Add and Remove button onclick events as follows.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
Once you’ve read Building Micro Frontends with React 18, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781804610961
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly.
This part covers the core concepts and principles behind microfrontends, including the motivations for using this architecture, key components, and how microfrontends differ from monoliths.
This part has the following chapters:
Chapter 1, Introducing MicrofrontendsChapter 2, Key Principles and Components of MicrofrontendsChapter 3, Monorepos versus Polyrepos for MicrofrontendsWe are coming full circle with microfrontends! During the Web 1.0 era, websites primarily comprised single pages built in ASP, JSP, or PHP, where we could make changes to each individual page and upload it to a server via FTP and it was immediately available to consumers. Then came the Web 2.0 era and the notion of web apps and Single-Page Apps (SPAs), where we compile, transpile, and deploy large monolithic apps. Now, we seem to be going back to working with smaller apps and pages.
The early 2000s brought in the era of Web 2.0 and the notion of web apps. A few years later, JavaScript frameworks allowed you to build SPAs that updated instantly and didn’t reload a new page each time the user clicked on a link or a button. SPAs were indeed fast for small to medium-sized apps, but as teams went full throttle with building large-scale SPAs, and as applications and teams grew, the velocity and speed of development dropped significantly. Teams seemed to be debating about folder structures, state management, and breaking each other’s code, due to centrally managed libraries and so on. These large SPAs also started becoming less performant due to the large bundle sizes of these apps. More importantly, the high execution time required to parse these JavaScript bundles made the apps even more sluggish on low-end devices and mobile phones. That’s when developers and architects started looking for solutions to these problems. Thankfully, they didn’t have to look too far.
You see, the backend teams went through the exact same problems with the large backend monoliths a few decades back and moved toward the microservices architecture pattern in order to solve their performance and scaling challenges. The frontend teams now look to apply the same principles of microservices to their frontend apps, which are being referred toas microfrontends.
The journey for backend teams toward microservices has been a very long one, spanning multiple decades, and many teams still struggle with it. However, thanks to a lot of debates, discussions, thoughts, leadership, and sharing learning from various microservice implementations, there is an overall maturity to and consensus around microservices architecture.
Frontend teams are just waking up to the notion of microfrontends, and there are multiple schools of thought on what defines a microfrontend, including, in fact, whether microfrontends are even a good thing or not. It will take a couple of years, if not a decade, before there is some consensus around microfrontends. The good thing, however, is that we can learn a lot from the journey of microservices, as a lot of principles and architecture patterns of microservices also apply to microfrontends.
In this chapter, we’ll start by understanding the need for microfrontends. We will cover the definition of microfrontends, and then the different patterns of microfrontends. We will also look into the parameters that will help us choose which pattern to go with for designing your apps. Finally, we will create our very first microfrontend.
In this chapter, we will cover the following topics:
Defining MicrofrontendsUnderstanding Microfrontend patternsChoosing a suitable patternHello World with MicrofrontendsBy the end of this chapter, you will have a better understanding of two of the most common patterns for building microfrontends and a guide to help you decide which one would be most suitable for you.
Toward the end of this chapter, we will build out a simple multi-SPA microfrontend example and get a feel for how we navigate between the the different SPAs.
As you go through the code examples in this chapter, you will need the following:
A PC, Mac, or Linux desktop/laptop with at least 8 GB of RAM (16 GB preferred)An Intel chipset i5+, AMD, or an Apple M1 + chipsetAt least 256 GB of free hard disk storageYou will also need the following software installed on your computer:
Node.js version 16+ (use nvm to manage different versions of Node.js if you have to).Terminal: A modern shell such as zsh, iTerm2 with oh-my-zsh for Mac (you will thank me later), or Hyper for Windows (https://hyper.is/).IDE: We recommend VS Code.npm, yarn, or pnpm. We recommend PNPM because it’s fast and storage efficient.Browser: Chrome/Microsoft Edge, Brave, or Firefox (I use Firefox).The code files for this chapter can be found here: https://github.com/PacktPublishing/Building-Micro-Frontends-with-React.
In this section, we will focus on defining what microfrontends and their key benefits are, and also become aware of the initial upfront investments associated with setting up microfrontends.
The currently accepted definition of a microfrontend is as follows.
“Microfrontends are a composition of micro apps that can be independently deployed and are owned by independent teams responsible for delivering business value of a focused area of the overall application”.
The keywords in this definition are independently deployed and independent teams. If at least one of these terms doesn’t apply to you or your team, then you probably don’t need a microfrontend. A regular SPA would work out to be more efficient and productive. As we will see later, microfrontends come with a bit of upfront complexity and may not be worth it unless you have a large application, where sections of the app are managed by individual teams.
We’ve noticed that some teams that are on their journey to implementing microfrontends misinterpret the micro part of microfrontends and believe an application doesn’t follow a microfrontend architecture unless it’s broken down to its smallest level. They break down their apps into really small apps, which adds a lot of unnecessary complexity. In fact, it negates all the benefits that microfrontends are supposed to deliver.
In our opinion, it actually works the other way around. When breaking down an application into micro apps, the teams should ideally look to identify the largest possible micro app or micro apps that a scrum team can independently manage and deploy to production without impacting other micro apps.
The key takeaway from this is not to be swayed by the term “micro” but instead identify the largest possible app that can be independently deployed by a single scrum team.
Before we go deeper into the wonderful world of microfrontends, it is important to remember that every application doesn’t need to be a microfrontend. Let’s learn more about this in the following section.
Martin Fowler talks about the microservice premium. This refers to the fact that microservices come with a bit of overhead and complexity, mainly in terms of the initial setup and the communication channels between the services. Martin goes on to say that the benefits of a microservices architecture only start showing when size and complexity boosters kick in. To understand this, let’s look at the following diagram:
Figure 1.1 – The microservice premium graph (source: https://martinfowler.com/bliki/MicroservicePremium.html)
The preceding diagram is a graph of the productivity versus the complexity of an application and depicts the drop in productivity for a monolith SPA and microfrontend as complexity grows.
The same holds true for the microfrontend architecture. The whole process of decoupling the various parts of components, routing, and templates and delegating them to different systems can become an unnecessary overhead for small or medium-scale apps.
The benefits of microfrontends kick in only when your project starts reaching the size and complexity thresholds shown in Figure 1.1.
All the benefits of a microfrontend architecture are linked to size and scale. Having said that, the following benefits of microfrontends hold true only for apps that are built and supported by teams with over 15 people.
In the following sections, we will learn about the benefits that teams can expect when they implement a microfrontend architecture, all of which are directly linked to improved productivity and better developer experience for team members.
One of the main drawbacks of monolithic Single Page Apps is that as the application and team sizes grow, feature development and deployments come to a crawl. We notice the team spending a lot more time where one team is waiting on the other team to finish something before the application can be deployed. With a microfrontend architecture, every scrum team works independently on their micro app, building and releasing features without having to worry a lot about what other teams are doing.
A microfrontend architecture is all about composing smaller micro apps, so as the application grows in size, it’s just a question of adding additional micro apps and having a scrum team own it.
Now, since each team deals with a smaller micro app, their team members need to spend less time understanding the code base and should not get overwhelmed or worried about how their code changes will impact other teams.
Microfrontends allow one to scale up very quickly, with scrum teams working in parallel once the base microfrontend framework is set up.
With isolated, independent micro apps, the time required for each team to compile, build, and run automated unit tests for their part of the micro apps is greatly reduced. This allows teams to build and deliver features a lot faster.
While teams run isolated unit and automation tests for their micro apps more frequently, we recommend running full regression suites of end-to-end tests on demand or before committing the code to Git.
The frontend ecosystem is the fastest-evolving ecosystem. Every few months, a new framework or library springs up that is better and faster than the previous one. Having said that, there is always an urge to rewrite your existing application using the latest framework.
With large applications, it’s not possible to easily upgrade or introduce a new framework without rewriting the entire application. The cost of rewriting the application and the associated risks of introducing bugs due to the rewrite are far too high. Teams keep deprioritizing the upgrade and within a few years, they find themselves working on an outdated framework.
With microfrontends, it is easier to pick up one small micro app and upgrade it or rewrite it and then gradually roll it out to other micro apps. This also allows teams to experience the benefits of the new change and learn and course-correct as they migrate the new framework to the other micro apps.
As we move on to the next section, let’s quickly recap some of the key points that we’ve learned so far:
Microfrontends are suited for building large-scale apps where teams are set up as full-stack teams, where the backend developers, frontend developers, product owners, and so on are within the same scrum team.Microfrontends have numerous benefits, such as team independence, features launched with improved velocity, and better developer experience. However, these benefits will start becoming visible once you have overcome the initial phase of complexity associated with the “microfrontend premium.”When it comes to microfrontends, there are way too many interpretations. These are still early days for microfrontends, and there is no right or wrong way of building them. The answer to any technical/architectural question is “It depends….” In this section, we will focus on two of the most common patterns that teams adopt while building microfrontends. We will see what key factors to consider when deciding which pattern may be right for you. We will end this section by building a really basic microfrontend to get the ball rolling.
At a very high level, there are two primary patterns for microfrontends. Both of these patterns can be applied irrespective of whether you are building a Server-Side-Rendered (SSR) app or a Client-Side-Rendered (CSR) app. To better illustrate these patterns, we will take the use case of an e-commerce application such as Amazon.
In the following subsections, we will look at these two patterns and how they differ from each other.
The first pattern that we will discuss is the multi-SPA pattern. As the name suggests, the application is built up of multiple SPAs. Here, the app is broken down into 2-3 distinct SPAs and each app is rendered at its own URL. When the user navigates from one SPA to another, they are redirected via a browser reload. In the case of an e-commerce application, we could look at the search, product listing, and product details as one SPA, and the cart and checkout as the other SPA. Similarly, the My Accounts section, which includes the login, registration, and profile information, would form the third SPA.
The following figure shows an illustration of a multi-SPA pattern microfrontend for an e-commerce app:
Figure 1.2 – Multi-SPA pattern microfrontend for an e-commerce app
As you can see from the preceding figure, our e-commerce application consists of three SPAs: the Catalog SPA, the Checkout SPA, and the Accounts SPA.
In the simplest form of this pattern, each app behaves as an independent SPA that sits within its own unique global URL.
Each SPA is deployed at a unique global route. For example, the catalog app would be deployed at a URL such as mysite.com/catalog/* and all subsequent secondary routes within the catalog app will load up as an SPA within the /catalog/* route.
Similarly, the accounts app would live in the global route of mysite.com/accounts/ and the different pages within the account’s app login, signup, and profile would be available at URLs such as mysite.com/accounts/loginor mysite.com/accounts/register.
As mentioned earlier, when the user moves from one macro app to another, there will be a reload of the page in the browser. This is because we usually use the HTML href
