Wrapper application should be routed as usual and template for each route serves as mapper of micro frontend components:
Upon rendering in the browser Wrapper will run a script that will fetch each of the segments HTML and insert it into those placeholder divs:
Method getSegmentHtml will perform ajax request to service URL with the segment as a parameter to fetch the proper HTML segment. Upon a successful request, the returned segment is inserted into the DOM. That way any number of segments can be served on any number of services.
In this proof-of-concept example, we have a simple page that will fetch four segments to create a simple interface with a form. This form will be used to show how to create generic form submission of a segment’s form and then update only that segment without the full page refresh.
Any form submission on the page is prevented by adding submit event listener on the document object and preventing the default form submission behavior. Next, the form data is used to create a query string that will hold all data user submitted. Since the form is inside one of the segments we can extract data about the segment. Those three pieces of information are then used to call getSegmentHtml method again, but this time URL will contain form data in the query string. Service that receives this request will react to those parameters and return proper HTML response which will, in turn, replace the segment’s HTML. If, for example, the validation fails the service will return the form but this time with error messages. Backend applications this way behave as APIs for micro frontend segments instead of returning full pages with templates and layouts.
If all four segments are served by different services (which can be a case in big systems) we can update the text in the header and still use the form while the header is in the deployment process. Of course, this kind separations have to be carefully planned so user experience is not broken.
Using default browser behavior
When this snippet is inserted into the DOM the toast message will be shown on the screen and when a user clicks on ‘x’ it will disappear. Here we are taking the advantage of the default HTML behavior, when you properly connect the label with input (by for and name attributes matching), the click on the label will change the value on the input. In this case we have a label that will toggle checked state on the checkbox input. By using clever CSS selector “#toast:checked + .toast” we are connecting any sibling that is a class of ‘.toast’ to the aforementioned checked state. And that way toggling display CSS property of the toast container from none to flex.
For more code examples showcasing the same technique used on other UI elements check out this codepen collection.