Thoughts on using CustomEvents in a micro frontend application
This is a rough outline of my thoughts to find sensible guidelines for working with CustomEvents across multiple micro frontends.
As you are reading this I assume that you already learned about micro frontends. If this is a topic that you want to learn more about, please let me know.
What do you want to achieve?
Do you want to offer an API that other micro frontends can use or, do you want to trigger a specific action on some other micro frontend API?
Let‘s look at some examples to clarify things.
I have a shopping bookmark widget and I want to offer an API where others can bookmark products.
- Good use case for
- Define a domain-specific event name that is scoped to your team or micro frontend
- Add a listener for this event and document the public API.
- Act each time your widget receives the
I have a product card and I want to add it to the bookmark widget when a user clicks the “bookmark” button.
- Look up the public API for the
bookmark:addevent and dispatch it
I want to trigger the opening of a dialog of another micro frontend and update my user interface when the dialog closes
- Bad use case for
- Instead of events, think of the task as a remote procedure call or command
- The dialog micro frontend should offer a function that returns a
- Query the dialog element and call the
- Wait for the returned
promiseto resolve (or reject) and update your UI accordingly.
Each of these use cases can be solved using
CustomEvents but there are scenarios where event communication is not the best solution.
Who takes ownership of a CustomEvent
If you are in control of a specific piece of frontend or behavior, you own all events that interact with it. Others may…