Micro Frontends

Main concept

Micro frontends is the idea of treating front end as a micro-service. The idea is fairly simple:

First, you have 1 main page for all the micro-frontend together to create an app. The page can look like as below

<html>
	<body>
		<app1></app1>
		<app2></app2>
		<app3></app3>
	</body>
</html>

And then we need to inject the bundle script for our front-end that will render the corresponding app1, app2, app3. For example

<html>
	<body>
		<app1></app1>
		<app2></app2>
		<app3></app3>
	</body>

	<script src="/app1/bundle.js" async></script>  
	<script src="/app2/bundle.js" async></script>  
	<script src="/app3/bundle.js" async></script>
</html>

Now the /app1/bundle.js or app2 and app3 can be hosted from another origin.

In this case, for example we have an nginx server that hosting this app1/bundle.js as a static content.

Therefore when team1 working on app1, whenever they want to update the content of their app, they can just re-bundle it and update their endpoint hosting app1/bundle.js.

Serverside rendering support

For Serverside rendering (SSR) support, we need to inject the HTML inside our <app> components some how.

To make it simple, we can use SSI and then have an endpoint that serve the serverside content for each app.

So for example our app1 server can have something like this


function renderApp() {
	return `<div> Rendering App1 </div>`
}

app.use('/app1', (req, res) => {  
	res.send(renderApp());  
});

And then in HTML we can change to

<html>
	<body>
		<app1><!--#include virtual="/app1" --></app1>
		<app2></app2>
		<app3></app3>
	</body>

	<script src="/app1/bundle.js" async></script>  
	<script src="/app2/bundle.js" async></script>  
	<script src="/app3/bundle.js" async></script>
</html>

Note: this requires our server to support ssi

This have just made our app1 to be serverside rendered. When app1 js bundle finished loading, it will switch to client side rendering to make it functional.

Note: Doing serverside rendering can be good to have the initial load, however serverside rendering does not provide much functionality and interactivity. Therefore, it's good idea if we use serverside rendering to render the place holder or the main content that user wanna see even if javascript is disabled.

Resources: