Building Microfrontends Part V — Communication Between Apps
Just to recap, we created 3 apps, a header, a products list and a cart, put then all inside a page, our homepage, and mapped all their URLs using the router, but they still do not talk with each other.
Now we are going to add communication. There are probably a bunch of ways of doing that, but, like with the rest of this blog posts, I'll go with the most simple way I know: Native CustomEvents.
On our products-list app, change
src/App.js to this:
Now when the button is clicked we trigger dispatch an event to
window passing the product chose in
Now on our cart app, we need to listen to that event. Change its
src/App.js to this:
That's it, we send events to the window from one app, and listen from the other, using browser native APIs and simple JSON.
The reason I believe it should be kept simple this way, or somewhere near, is because it should work with any other technologies and frameworks, you can send messages from React to Angular for example. This is the same reason nowadays everybody uses JSON to communication on the back-end, even if nobody uses NodeJS!
Here is a gif of apps talking with each other:
Cool, right? You know what else is cool? We manage to get two apps talking only by changing and redeploying the two of them. We hadn't to change anything on the homepage, the header or the router, this is independence!
If you want more ideas for the integration and communication between apps, I recommend the sandbox approach by Nicholas Zakas.
Unfortunately, I don't have anything more to show besides those, for example, how do we test this communication? How to write integration or contract tests here? I don't know. Also adding some ideas from Event Driven Architecture here might be good. If you have anything to contribute, please share with us.
That's it! We built it, Microfrontends, yay! Thanks for reading this far!
If you had any trouble, please comment so I can improve the articles, also, all the code is available at github.com/microfrontends.
Don't use any of this if you don't need it
I like the Lean as most as I can, avoid waste, so again, I'll recommend, do not use the ideas described here until it is needed, it will make things more complex. If you are in a big company, those ideas could help you, if not, a Majestic Monolith might serve you well.
If you do use some ideas, adapt it to your flavor, and know that there are some unsolved issues that you will probably face.
Bonus Part! Changing Technologies
I did say we can use different technologies for our apps, but I haven't proved it have I? So now we are going to rewrite cart using the coolest language ever: Elm!