<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Jilshak K on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Jilshak K on Medium]]></description>
        <link>https://medium.com/@mohd.jilshak?source=rss-87b6ab9e9727------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HkgPeU95RBchXb-gE1FDog.jpeg</url>
            <title>Stories by Muhammad Jilshak K on Medium</title>
            <link>https://medium.com/@mohd.jilshak?source=rss-87b6ab9e9727------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:34:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohd.jilshak/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Privacy in RAG systems]]></title>
            <link>https://medium.com/@mohd.jilshak/privacy-in-rag-systems-856531c48ef7?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/856531c48ef7</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 20:08:03 GMT</pubDate>
            <atom:updated>2025-12-02T20:08:03.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*AX06padEWUMP-XZjlGGIGw.png" /></figure><p>When creating an RAG system, <strong>Privacy </strong>is one of the most important things which we should keep in mind. This will keep our data protected and safe from external sources. So let’s dive into it.</p><p>I’ll try to explain it with the help of an example. Suppose we are implementing the RAG application for an Educational firm and we are not using our own pre trained language model (LLM) and instead using third party models like OpenAI’s chatGPT, Googles Gemini etc. The problem here is that even though it works really well, we are giving our private data to these models which will store our inputs for monitoring abuse or any other reason. So technically we are giving away our data to these models and they can use this data for whatever they want.</p><p>This is an major concern, since data from Educational firms are supposed to be protected. In such an scenario what can we do? as we already know, if we don’t provide the data to the LLM it won’t give us personalized response and it might hallucinate. If we give it our data, we are giving away the data which is supposed to be private and secure to the LLM’s for free using which they can train their model or use it for any other purpose. So what should we do? There are several ways through which we can tackle this situation, and I’ll be explaining 3 of them for you here.</p><ol><li><strong>Send minimal information</strong></li><li><strong>Create a RAG summary index</strong></li><li><strong>Keep private data in your backend</strong></li></ol><p><strong>Send Minimal Information:</strong></p><p>Now you guys might be thinking, what does this guy mean by minimal information? isn’t sharing any information concerning and is considered as data leak? Yes, you are absolutely right, but here me out for a second. What I meant when I said minimal information is providing the context of our query but without actual data. This might be a bit confusing but I’ll give you an example.</p><p>suppose we have a user named <strong><em>John Doe</em></strong>, and his email which is<strong><em> john@gmail.com. </em></strong>When we pass the data to the LLM it’ll be like <strong>customer_123 </strong>for the name, and <strong>customer123@gmail.com </strong>for the email. thus we can get the answer from the LLM without providing the actual user data. So in short we are masking/anonymizing them</p><p>&quot;John Doe&quot; → &quot;CUSTOMER_123&quot;</p><p><strong>Create a RAG summary index:</strong></p><p>This is actually quiet an simple method and easy to do. What we do in this method is that instead of storing customer details we just store abstracted knowledge/summarized chunks of the information. This way we are not giving away our sensitive data to these LLM’s. Now when we make this request, it’ll only have access to this summarized data and won’t have access to the actual user data</p><p><strong>Keep Private Data In Your Backend:</strong></p><p>For this one, what we are doing is similar to that of the first method we’ve discussed. We won’t share any data to the LLM, we’ll mask it by sending data like customer_123, and it’ll respond back with that name. now in the backend what we’ll do is, we’ll inject (replace) the customer_123 with the actual data of the user form our context. This way we are not sharing any data with the LLM’s and is also getting personalized response.</p><pre>User → Backend → Masking → LLM → Response → Backend → Unmask → User</pre><p>There are many more ways for handling privacy in RAG systems, but these three are the most used and basic ones implemented in almost all of the systems. Implementing this steps in an RAG system poses another issue, it’ll increase the network latency a bit as the number of steps increased before returning the response.</p><p>So in the next article, I’ll be explaining about the methods using which we can improve the performance and reduce the latency in RAG systems. So keep an eye out for that one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=856531c48ef7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to the LangChain Stack]]></title>
            <link>https://medium.com/@mohd.jilshak/introduction-to-the-langchain-stack-a8dd91ec4f03?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8dd91ec4f03</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langsmith]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 22:52:50 GMT</pubDate>
            <atom:updated>2025-10-08T23:06:49.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*0qu8id5v_m3sWu803PLsig.png" /></figure><p>Hey, In the era of AI and Machine Learning models, it is crucial that we understand how these systems works, especially since we use this in our daily day to day life and it has become a part of our life. In this article we’ll briefly discuss about this stack.</p><h4><strong><em>LangChain:</em></strong></h4><p>It is a framework for building applications using large language models (LLM’s). To simply put, think of LangChain as a <strong><em>glue</em></strong>, it connects various data sources to your LLM, like databases, APIs, logical workflows etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*pfnv7YBu9FDipsbHdy-gRw.png" /><figcaption>LangChain (LLM glue)</figcaption></figure><p>Now you might be thinking why does this glue exist ? Doesn’t the LLM have all the data pre-trained into it already, so why use this at all ?</p><p>LLMs are powerful but they can’t directly:</p><ul><li>Fetch external data (like from the DB or API)</li><li>Perform multistep reasoning</li><li>Remember context over long conversations</li></ul><p>So in order to fix all of these issues, LangChain lets us build chains — sequences of operations</p><p>Let me explain it with an example:</p><p>Suppose we are building an app that answers questions about your company’s documents.</p><p><strong><em>Without LangChain we’d manually have to:</em></strong></p><ol><li>Read document</li><li>Create document</li><li>Store them in a vector DB</li><li>Query them</li><li>Pass context to the LLM manually</li></ol><p>With LangChain all of these are simplified.</p><pre>from langchain.chains import RetrievalQA<br>from langchain.llms import OpenAI<br>from langchain.vectorstores import Chroma<br>from langchain.embeddings import OpenAIEmbeddings<br><br># Create vector store<br>embeddings = OpenAIEmbeddings()<br>db = Chroma(persist_directory=&quot;docs_db&quot;, embedding_function=embeddings)<br><br># Create a retrieval-based QA chain<br>qa = RetrievalQA.from_chain_type(<br>    llm=OpenAI(),<br>    chain_type=&quot;stuff&quot;,<br>    retriever=db.as_retriever()<br>)<br><br># Ask questions!<br>print(qa.run(&quot;What does our refund policy say?&quot;))</pre><p><strong>LangGraph:</strong></p><p>It’s basically an upgraded version of LangChain. It’s a <em>graph-based orchestration engine</em> for LLM applications. Ok, so now you might be wondering how did LangChain worked then ? was it not graph ? The answer is NO<strong>, </strong>It was a linear workflow (which means it’ll always follow the same path), just like when we create and API network request call in REST.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*aPQihQIu0nI3Fqx9z-vJGA.png" /><figcaption>LangChain v/s LangGraph</figcaption></figure><p>Since LangChain is <em>Linear, </em>it has its limits. This is where <strong>LangGraph </strong>comes in to play. It enables the us to build multi-agent workflows (AI systems) making it far superior to that of LangChain <strong><em>(linear workflow)</em></strong>.</p><p><strong>LangSmith:</strong></p><p>It is used as an observing and debugging platform for LLM applications, which is also build by the same team.</p><p>Think of it like <strong>Postman + Datadog + GitHub Logs</strong> — but specifically designed for <strong>tracking, debugging, and improving LLM workflows</strong> built with LangChain or LangGraph.</p><p>So what this does is that, it enables us to debug or understand the flow of the request, and how the answer is generated. Each and every step can be monitored here which enables us to customize and tweak our LLM to better respond and improve as well as optimize its performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*8oKSsf8e9bOyTxeQwEIipg.png" /></figure><p>The key features of LangSmith are:</p><ul><li><em>Tracing </em>→ helps you debug and optimize</li><li><em>Dataset Testing</em> → Helps you systematically test your app</li><li><em>Evaluation </em>→ Improves accuracy over time</li><li><em>Versioning </em>→ Makes prompt tuning easier</li><li><em>Dashboard </em>→ See everything from latency to cost</li><li><em>Integration </em>→ Seamless end-to-end experience</li></ul><p>So, the combination of all of these components makes the LangStack (LangChain Stack). I hope you guys understand the differences and the use cases of each of these three components in LangStack . This enables us to build complex agentic workflows, and automations in our systems (Businesses, Home).</p><p>I’ll be writing another article in which I’ll be showing you people how to build a simple Multi-modal agentic AI workflow using LangStack. So keep an eye out for that one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8dd91ec4f03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advantages and Disadvantages of RAG (Retrieval Augmented Generation)]]></title>
            <link>https://medium.com/@mohd.jilshak/advantages-and-disadvantages-of-rag-retrieval-augmented-generation-9ecbd44ee372?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ecbd44ee372</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai-and-ml]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 20:50:41 GMT</pubDate>
            <atom:updated>2025-10-06T20:57:18.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOUOgR2H-8JXVAa2cRf5XA.png" /></figure><p>So before we start with the advantages and disadvantages, at first we need to understand what RAG is. So RAG stands for Retrieval Augmented Generation, It helps us to retrieve data from the data source given to it or it have access to, then enhance or augments the context of the data, and then provide it to the LLM model and then it generates the data with enhanced data retrieved from the data source provided to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*WZuG4JX9Oy7G2P7_YwtVxA.png" /></figure><p>Now since that is out of the way, let’s start explaining the advantages and disadvantages of RAG. Let’s start with the Advantages shall we ?</p><p><strong>Advantages:</strong></p><ol><li>Access to up-to-date information</li></ol><p>Now what does this mean, up-to-date information ? doesn’t LLM already give us that ? So what is the role of RAG here ? Ok so this is a common misconception that mass majority of people have about LLM models, and unfortunately that is not how it works. The LLM stands for Large Language Models, and these are trained on large datasets (corpus of data).</p><p>Unfortunately once trained it won’t just automatically update, which means it have no means of getting new and latest information unless it is retrained (finetuned) which costs a lot of money. So that’s where RAG comes in. It provides more context to the LLM (which is outdated) and then from this context provide the answer based off on the new context it was given.</p><p>2. Uses Private / Proprietary Data</p><p>This might be an obvious one, but I’ll explain it any way. Since the Large Language Models are trained on publicly available data, for someone to use it for their custom needs and desires apart from the general knowledge it needs to have context of private data, which we can provide through RAG. So this way, the LLM can respond to the users request with the desired data. So instead of finetuning an LLM with the private data (which is costly) we provide the context through RAG which makes it cost efficient and easy.</p><p>3. Reduces Hallucination</p><p>This one is also a no brainer. One of the most faced issues in Large Language models is hallucination, now what does hallucination mean ? It means that the model might occasionally provide incorrect answer (and that too very confidently). This is why they always say, always take the response generated by large models with a pinch of salt, as it might be or could be an hallucination. So by providing more context through RAG, it’ll reduce the hallucination by a great extend but not completely.</p><p>4. Cheaper Than Fine Tuning</p><p>So instead of fine tuning or retraining the model every time you need to add the latest information which is really costly this method of using RAG is way more cost efficient</p><p>5. Dynamic Updates</p><p>You can add new data source whenever we want to, so that the context is updated. This way the LLM always have the latest relevant information given to it through the RAG. This way even though we are using an very old LLM model, it can still have latest information without fine tuning it and still get up-to-date data.</p><p>6. Modular Design</p><p>You can swap out parts as you wish like the retriever, embedding models etc. this makes it really flexible and efficient.</p><p><strong>Disadvantages:</strong></p><ol><li>Dependent On Retrieval Quality</li></ol><p>So this is just like when we train a Large Language model. If we were to give it bad data, it will spit out bad response, <strong><em>“Garbage in Garbage out”. </em></strong>So if the data source given it is bad/noisy, or it is really messy, then the response given by it will also be really bad.</p><p>2. Slower Response Time</p><p>This one is a given when using RAG, since adding RAG to the equation increases the number of steps in the process for the generation of the answers it increases the latency a bit.</p><pre>Note: Caching can be implemented for better performance or,<br>we can always use a better vector store for faster generation</pre><p>3. Needs Storage and Infrastructure</p><p>Now unlike the LLM, which is pretrained of the dataset, for RAG we need to have proper system for this to work like a vector database, retrieval logic, embeddings etc. So all of these has to be in place for this to work. Hence it can be considered as a disadvantage</p><p>4. Retrieval errors with ambiguous queries</p><p>If the question is vague, there might be too many possible context for this, which would be an issue since it won’t know which one is to be given as a context for the LLM to generate accurate answer for our query.</p><p>5. Still not 100% factual</p><p>Even with retrieval, the LLM can <strong>misinterpret</strong> context or merge facts incorrectly which has to be handled separately using various other methods.</p><p>So these are a few but among the most important, advantages and disadvantages of RAG system. If you wish to know the learn more about the roles of <a href="https://medium.com/@mohd.jilshak/rag-in-llms-2a35e33fccbf">RAG in LLM’s</a> you can read it in an article that I’ve already published here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ecbd44ee372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG in LLM’s]]></title>
            <link>https://medium.com/@mohd.jilshak/rag-in-llms-2a35e33fccbf?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a35e33fccbf</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 18:52:10 GMT</pubDate>
            <atom:updated>2025-10-06T21:07:37.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*fg0s8QiYe2XeeRWIhspp0A.png" /></figure><p>Before I start explaining to you people what the role of RAG in LLM’s are, at first we need to understand what <strong>RAG (Retrieval Augmented Generation) </strong>is and how it works. So as the name itself suggests, It is the process of retrieving data from a source given to it, enhancing the context from the data source given, and then generating the data with the enhanced data.</p><p>Now the explanation that I’ve given above is just putting it simply, each of these steps can be further elaborated. into various steps. But overall this is the process flow and this is how RAG works: Retrieve (the data), Augment (enhance the data) and Generate (the data)</p><p><strong><em>Role of RAG in LLM’s:</em></strong></p><p>Since the advent of Large Language Models (LLM) the term RAG also became popular though this design principle has been used way before the AI wave, in search engines, QA (question answer) applications etc. Now that raises the questions:</p><ol><li>Why did it become popular along with LLM’s ?</li><li>Why is this term used along with LLM’s in the first place ?</li><li>Does it help the LLM’s in any way or form ?</li></ol><p>I’ll answer all of these by explaining the role of RAG in LLM’s. So Large language models are trained on a particular sets of data (Corpus of data), That is how it is so knowledgeable, it is trained on publicly available data throughout the internet. But this set of training data is limited with time and availability.</p><p>Let me explain it more clearly, suppose we are now creating a LLM’s it can be only trained with data up until today, the LLM’s won’t know what happens tomorrow or the future events. It also won’t know the private data (like medical, corporate data). Now this creates a problem, the LLM will be cut off from the date since its released. So though the model is good in general responses and conversation, it won’t be able to give us responses regarding the current scenarios or situations happening throughout the world or it might hallucinate (which is a common problem in LLM’s).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*m0uEHUyr3bF_uKMeKLDrNQ.png" /></figure><p>This is where RAG comes into play. RAG enhances the LLM’s context (knowledge base) with new data so that it can answer the questions without hallucinating, how cool is that. So, we don’t need to re-train the model (which might cost lot of money) with the new data, instead just provide the new data (it can be pdf, excel, txt file, database etc.)</p><p>So there you have it. Now you know how RAG enhances and helps LLM (Large Language Models). It helps the model to not to hallucinate, and retrieve new and up-to date data from the data source given to it or which it has access to.</p><p><strong><em>Advantages And Disadvantages of Using RAG</em></strong></p><p>As every technology has its Advantages and Disadvantages, this one also have them. I’ll list a few of them for you which are important.</p><p><strong><em>Advantages</em></strong><em>:</em></p><ol><li>Access to up to date information</li><li>Use Private / Proprietary data</li><li>Reduces Hallucination</li><li>Cheaper than fine tuning</li><li>Dynamic update</li><li>Modular Design</li></ol><p><strong><em>Disadvantages:</em></strong></p><ol><li>Dependent on retrieval quality</li><li>Slower response time</li><li>Needs storage and infrastructure</li><li>Retrieval errors with ambiguous queries</li><li>Embedding cost and drift</li><li>Still not 100% factual</li></ol><p>Now these are just one liners of advantages and disadvantages. Explaining all of them here will make this article too long, which is not a good thing. So I’ll be writing a <a href="https://medium.com/@mohd.jilshak/advantages-and-disadvantages-of-rag-retrieval-augmented-generation-9ecbd44ee372">new article</a> explaining all of these in detail so keep an eye out for that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a35e33fccbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro Frontend- Build Time Composition and Run Time Composition]]></title>
            <link>https://medium.com/@mohd.jilshak/micro-frontend-build-time-composition-and-run-time-composition-9690b72ebaeb?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/9690b72ebaeb</guid>
            <category><![CDATA[micro-front-end]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 10:37:43 GMT</pubDate>
            <atom:updated>2024-07-29T11:05:06.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJwBi4cB7S1P5plC4tagvg.png" /></figure><p>For those of who are familiar with micro frontends, and those who getting in to micro frontends, I’m pretty sure you’ve come across these terms <strong>Build</strong> <strong>time</strong> and <strong>Run</strong> <strong>time</strong> <strong>composition</strong>. Trust me, these topics are pretty important, if you are planning to implement micro frontend architecture in your project.</p><p>So we’ll start with the term “<em>Composition”. </em>The term composition in the development field means, combination (aggregation) of various components (parts) of code in to a single one.</p><p><strong>Build Time Composition</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*S_lUVY1nLV7qM1_NVv96Rw.png" /><figcaption>Ecommerce application (build time)</figcaption></figure><p>As you can see in the flow diagram given above, We’ve depicted a Ecommerce application with 3 micro frontend units, <em>Home</em>, <em>Cart</em>, and <em>Payment</em>. All these components are <em>composed </em>or <em>combined </em>or <em>compiled </em>at a particular stage, which then results in to the entire web application. This is called <strong>Build time composition</strong>.</p><p>I’ll explain with an example now. Suppose the micro frontend application shown above has already been deployed into production. Now we want to introduce a new feature or functionality to a particular unit (micro frontend, lets say <em>Cart</em>). Now if we want the change that we made to be reflected into the entire application, all the units (micro frontends) has to be build again (similar to that of a monolithic application with typescript in it).</p><p><strong>Advantages of Build Time Composition:</strong></p><ol><li>Performance Optimization</li><li>Consistent User Experience</li><li>Simplified Deployment Process</li><li>Predictable State</li></ol><p><strong>Disadvantages of Build Time Composition:</strong></p><ol><li>Reduced Flexibility</li><li>Increased Build Time</li><li>Scalability Challenges</li><li>Versioning and Dependency Management</li></ol><p><strong>Run Time Composition:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*czcfQ4emPQmFuU6iHO5QPA.png" /><figcaption>Ecommerce Application (run time composition)</figcaption></figure><p>Now let’s get into the term Run time composition. This one is a little different from the previous one. Here we can take the same example <em>Home</em>, <em>Cart</em>, and <em>Payment</em>. If we were to make some changes to the unit, lets take <em>Cart</em> as an example, suppose there was a bug in the <em>Cart</em> micro frontend, the number of the items in the cart is not correct. We went through the code, and figured out the root cause of the problem and fixed it. Now we need this to be pushed to the production. But this time unlike, Build time composition, instead of building all the other micro frontends, we’ll only need to build that particular micro frontend and then push it. That’s it, It will be reflected in all the micro frontend units that is depended on it as well.</p><p><strong>Advantages of Run Time Composition:</strong></p><ol><li>Flexibility and Independence</li><li>Scalability and Modularity</li><li>Reduced Initial Build and Deployment Complexity</li><li>Resilience</li></ol><p><strong>Disadvantages of Run Time Composition:</strong></p><ol><li>Performance Overhead</li><li>Complexity in Dependency Management</li><li>Security Concerns</li><li>Increased Run time Complexity</li></ol><p>Understanding build-time and run-time composition is crucial when delving into micro frontend architecture. These two methods offer distinct advantages and challenges, shaping how micro frontends are integrated, deployed, and managed.</p><ul><li><strong>Build-Time Composition</strong> emphasizes performance optimization and consistency, providing a cohesive user experience at the cost of flexibility. It’s ideal for scenarios where stability and efficiency are paramount.</li><li><strong>Run-Time Composition</strong> offers unparalleled flexibility, enabling independent deployments and dynamic feature integration. However, it requires careful handling of performance, dependency management, and security considerations.</li></ul><p>Mastering these composition strategies is essential for effectively leveraging micro frontend architecture, enabling scalable, modular, and efficient web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9690b72ebaeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Micro Frontend Application with Module Federation: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@mohd.jilshak/building-a-simple-micro-frontend-application-with-module-federation-a-step-by-step-guide-911813c75645?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/911813c75645</guid>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 10:27:26 GMT</pubDate>
            <atom:updated>2024-08-01T13:11:39.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*Re5YSF8eEwY0yxn7mtqdqg.png" /></figure><p>Implementing micro frontend architecture in project might be an intimidating thought for many, as it requires a lot of prerequisites to be set up. But if you ask me, it’s not as hard as many claims it to be. In this article I’ll show you the step by step process of creating a simple micro frontend application, and to manage state and share data between them.</p><p>So before we get started, I’ll give you guys an brief idea about micro frontends. It is the splitting up of our client side codebase(Front End part of our code) in to small and manageable units, each having its own responsibilities, which are then later combined together to form the entire web application. In short it is nothing but <strong>Microservices</strong> brought to the frontend part of the code.</p><p>If you are new to this topic, I’d recommend you to go through my previous article “<a href="https://medium.com/@mohd.jilshak/a-beginners-walkthrough-understanding-micro-frontend-architecture-a62027b72f39"><strong><em>Understanding Micro frontend Architecture</em></strong></a><strong><em>” </em></strong>and come back. If that’s not the case, lets get started.</p><blockquote>Note: For this I’ll be using <a href="https://vitejs.dev/guide/"><strong>Vite</strong> <strong>React</strong></a>, <a href="https://zustand-demo.pmnd.rs/"><strong>Zustand</strong></a> for state management, and <a href="https://www.npmjs.com/package/@originjs/vite-plugin-federation"><strong>Runtime Module federation</strong></a></blockquote><blockquote>• <strong><em>Vite-React</em></strong><em>:</em> <em>Is a fast and modern build tool and development server for React applications, providing instant startup and efficient hot module replacement (HMR).</em><br>• <strong><em>Runtime Module federation: </em></strong><em>Is a webpack feature that enables the dynamic sharing of modules between separate builds at runtime.<br></em>• <strong><em>Zustand</em></strong><em>: Is a small, fast, and scalable state management library for React, providing an easy-to-use API for managing global state in applications.</em></blockquote><ol><li>Setup a simple Vite-React application</li></ol><pre>npm create vite@latest</pre><p>So for this project I’ll be using JavaScript with React. I’ll be naming my first project directory as “<em>Remote</em>” (you’ll understand later why) though you are free to name it what ever you want.</p><p>2. Now I’ll do the same process again, but this time I’ll be naming my project directory as “<em>Host”.</em></p><p>3. Now we’ll have to install Vite module federation plugin as dev dependency.</p><blockquote>Note: This has to be installed in all the micro frontend unit you wish to create in our case both the “remote” and the “host”</blockquote><pre>npm install @originjs/vite-plugin-federation -D</pre><p>4. Now go to your “<em>remote</em>” micro frontend unit (in my case the name of the directory is remote, you might have named it differently so go to that one) and then go to its “<em>package.json</em>” file, there you’ll be able to see scripts defined. Here we’ll have to add</p><pre>&quot;serve&quot;: &quot;npx serve -s dist -l 5001 --cors&quot;,</pre><p>Now you might be wondering, why are we adding a “<em>serve”</em> command to scripts. The same thought went through me as well, while implementing this for the first time. We are going to build this project after setting it up, then we are going to serve this on that specified port mentioned. So for this purpose, we’ll be needing a script, which is exactly what I’ve given above.</p><blockquote>Note: In the serve command given below we can see a lot of flags, I’ll explain each, which will make you understand why this is imporatant. <br>“<strong>-s</strong>” → stands for single page application mode, it tells server to serve the <strong>index.html</strong> file<br>“<strong>dist</strong>” → dist is the directory containing static files which is to be served, once you run the command “<strong>npm run build” </strong>within your project directory you’ll be able to see it.<br>“<strong>-l 5001</strong>” → -l command stand for listening, so what this does is it listens on the port 5001 (note: listening and running are the same in this context)</blockquote><p>5. Now we’ll have to configure our “<strong><em>vite.config.js</em></strong>” file</p><p><em>“Vite.config.js”</em> file will be automatically created once you create you vite application, and it’ll look something like this</p><pre>import { defineConfig } from &#39;vite&#39;<br>import react from &#39;@vitejs/plugin-react&#39;<br><br>// https://vitejs.dev/config/<br>export default defineConfig({<br>  plugins: [react()],<br>})</pre><p>Now we’ll have to configure this file. This is where we define from where we will expose our components to other micro frontends to use it (consume it) and from which micro frontend we should get the data (components) from.</p><pre>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br>import federation from &#39;@originjs/vite-plugin-federation&#39;;<br>import packageJson from &#39;./package.json&#39;<br>const deps = packageJson.dependencies; <br><br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    federation({<br>      name: &#39;remoteApp&#39;,<br>      filename: &#39;remoteEntry.js&#39;,<br>      shared: {<br>        ...deps,<br>        react: {<br>          singleton: true,<br>          requiredVersion: deps.react,<br>        },<br>        &#39;react-dom&#39;: {<br>          singleton: true,<br>          requiredVersion: deps[&#39;react-dom&#39;],<br>        },<br>      },<br>    }),<br>  ],<br>  server: {<br>    port: 5001,<br>    cors: true,<br>    headers: {<br>      &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>    },<br>  },<br>  build: {<br>    target: &#39;esnext&#39;,<br>  },<br>});</pre><p>As you can see, we’ve made quite some changes here, Don’t worry, I’ll explain each of these.</p><p>At first we will need to import the “<em>federation</em>” package from “<em>@originjs/vite-plugin-federation”, </em>it is required for us to share multiple, independently build and deployed application to share code and dependencies at runtime</p><p>Now we’ll have to import the “<em>package.json”</em> file here, this is imported here so that we can define the dependencies which will be required to run component shared by the micro frontend application.</p><blockquote><strong>**Important Note**</strong>: the component shared by the micro frontend might be using some installed libraries, so for the micro frontend using this shared component it also should have the same version of the library used.</blockquote><p>Now within the plugins we will have to also add the “<em>federation”</em> as you can see above, we’ll have to define a name for it, the <em>filename</em> can be anything, but the standard name used is “<strong><em>remoteEntry.js</em></strong>”, and then we define what all are we going to share. So here I’ve spread all the dependencies from my <em>package.json</em> file. And if need be we can specifically mention the package name and the version to be used. After that, I’ve configured the server configuration, what is the <em>port</em> to run, enabled <em>cors</em> and then I’ve also set the headers to accept the request from any origin and enable access to its resources. (cors has to be configured properly, but here for just showcase I’m allowing access to the resources from any origin)</p><p>6. Now we’ll create a component in our remote, which we’ll be using in our host application. Here I’ll be creating a button component.</p><pre>// scr\Button.jsx<br>function Button() {<br>  return (<br>    &lt;button&gt;<br>      Button From Remote<br>    &lt;/button&gt;<br>  )<br>}<br><br>export default Button</pre><p>7. Now we have to go to the <em>“vite.config.js” </em>file from where we are going to expose this component to other micro frontends.</p><pre>plugins: [<br>    react(),<br>    federation({<br>      name: &#39;remoteApp&#39;,<br>      filename: &#39;remoteEntry.js&#39;,<br>      exposes: {<br>        &#39;./Button&#39;: &#39;./src/Button&#39;,<br>      },<br>      shared: {<br>        ...deps,<br>        react: {<br>          singleton: true,<br>          requiredVersion: deps.react,<br>        },<br>        &#39;react-dom&#39;: {<br>          singleton: true,<br>          requiredVersion: deps[&#39;react-dom&#39;],<br>        },<br>      },<br>    }),<br>  ],</pre><p>If you notice it here, you can see that I have added <em>“exposes”</em> within the federation, within which i have added a component named “./Button” and I’ve given its path which is “./src/Button”. Now this component is exposed and it can be accessed by other micro frontends.</p><p>8. Now go to your host application (other micro frontend). So this micro frontend unit will be the one consuming our exposed Button from our remote application. So for this to consume it at first we’ll have to define from where it should be getting this remote component from, then we’ll also have to define the shared dependencies as I’ve already told you, it has to be the same in both the host and remote application to run the project otherwise it’ll throw error. So it’ll look something like this</p><pre>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br>import federation from &#39;@originjs/vite-plugin-federation&#39;;<br>import packageJson from &#39;./package.json&#39;<br>const deps = packageJson.dependencies;<br><br><br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    federation({<br>      name: &#39;hostApp&#39;,<br>      filename: &#39;remoteEntry.js&#39;,<br>      remotes: {<br>        remoteApp: &#39;http://localhost:5001/assets/remoteEntry.js&#39; ,<br>      },<br>      shared: {<br>        ...deps,<br>        react: {<br>          singleton: true,<br>          requiredVersion: deps.react,<br>        },<br>        &#39;react-dom&#39;: {<br>          singleton: true,<br>          requiredVersion: deps[&#39;react-dom&#39;],<br>        },<br>      },<br>    }),<br>  ],<br>  build: {<br>    target: &#39;esnext&#39;,<br>  },<br>  server: {<br>    port: 3000,<br>    cors: true,<br>    headers: {<br>      &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>    },<br>  },<br>});</pre><p>As you can see here, I’ve added within the plugins <em>“remotes”. </em>This is where we define from which all endpoints we need to get the components from, for instance here I’ve mentioned within the remotes, “<em>remoteApp</em>”, the remote app is the pointer (name) given to endpoint of that particular micro frontend from where we are getting the component, in our case the button and as you can see, I also have the same shared dependencies, here and I’m running this on the port 3000. All the rest is the same.</p><blockquote>Note: We may have multiple components coming from multiple micro frontend units, so we can use all of these unit here. So for this, we can simply add multiple endpoints within the “<strong>remotes”</strong>.</blockquote><pre>remotes: {<br>        remoteApp: &#39;http://localhost:5001/assets/remoteEntry.js&#39; ,<br>        anyName:&#39;http://localhost:5002/assets/remoteEntry.js&#39; ,<br>         },</pre><p>So that’s, all the setup you have to do. We are almost there, now the only thing left to do is to import this component and run it. But before that we’ll have to build and serve our remote application</p><p>Go to the remote application and run these commands:</p><pre>npm run build<br>npm run serve</pre><p>Now go to your host application and then we’ll have to import the Button from the remote application</p><pre>// host\src\App.jsx<br>import &#39;./App.css&#39;;<br>import Button from &quot;remoteApp/Button&quot;; // Importing from remoteApp<br><br>function App() {<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;This is the Host Application&lt;/h1&gt;<br>      &lt;Button /&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default App</pre><p>Here you can see that i am importing the button from the remoteApp. Now this might not necessarily be the remoteApp for you, its according to the name that you’ve given in your “<em>vite.config.js</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*sdOysD6krtE0BoRsI2mZDw.png" /></figure><p>the name I’ve given here is remoteApp, within the remote, so i am importing it from there, if you’ve given the name CartApp then it would be something like <strong><em>import Button from “CartApp/Button”. </em></strong>I hope you get the idea.</p><p>Now simply Build and run the host application as well</p><pre>npm run build<br>npm run preveiw</pre><p>Go to the endpoint in which it is running, and you can see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXzcarl2CfC0GbMKQxOw_Q.png" /><figcaption>The host application having the imported button from the remote</figcaption></figure><p>Congrats, You’ve set up a basic Micro frontend application. Now lets level it up a bit. What we are going to do here is, implementing state management within this micro frontend application.</p><p>So for this we’ll be using “<em>Zustand</em>”. Now for managing states across micro frontends, there are multiple methods. We can create an micro frontend application for the sole purpose of state management, acting as a centralized store, for all the other micro frontends. We can also assign an existing micro frontend as a store and then utilize the state from that particular micro frontend. Here we’ll be implementing the later one, i.e. we’ll be using the existing “<strong><em>remote” </em></strong>micro frontend to act as a global store.</p><p><strong>Steps to implement State management in Micro Frontends:</strong></p><ol><li>Install Zustand library on both the remote and host application</li></ol><pre>npm install zustand</pre><p>2. Create a store within the remote micro frontend</p><pre>// remote\src\store.js<br>import { create } from &#39;zustand&#39;;<br>import { persist } from &#39;zustand/middleware&#39;;<br><br>const useStore = create(<br>  persist(<br>    (set) =&gt; ({<br>      count: 0,<br>      increment: () =&gt; set((state) =&gt; ({<br>        count: state.count + 1<br>      })),<br>      decrement: () =&gt; set((state) =&gt; ({<br>        count: state.count - 1<br>      })),<br>      setCount: (newCount) =&gt; set({ count: newCount }),<br>    }),<br>    {<br>      name: &#39;count-storage&#39;,<br>    }<br>  )<br>);<br><br>export default useStore;</pre><p>3. Now it is similar to what we have done before to the Button component. We’ll have to expose this to the other micro frontend, and also add it to the shared within the “<em>vite.config.js”.</em></p><pre>import { defineConfig } from &#39;vite&#39;;<br>import react from &#39;@vitejs/plugin-react&#39;;<br>import federation from &#39;@originjs/vite-plugin-federation&#39;;<br>import packageJson from &#39;./package.json&#39;<br>const deps = packageJson.dependencies; <br><br>export default defineConfig({<br>  plugins: [<br>    react(),<br>    federation({<br>      name: &#39;remoteApp&#39;,<br>      filename: &#39;remoteEntry.js&#39;,<br>      exposes: {<br>        &#39;./Button&#39;: &#39;./src/Button&#39;,<br>        &#39;./store&#39;: &#39;./src/store&#39;<br>      },<br>      shared: {<br>        ...deps,<br>        react: {<br>          singleton: true,<br>          requiredVersion: deps.react,<br>        },<br>        &#39;react-dom&#39;: {<br>          singleton: true,<br>          requiredVersion: deps[&#39;react-dom&#39;],<br>        },<br>        zustand: {<br>          singleton: true,<br>          requiredVersion: deps.zustand,<br>        },<br>      },<br>    }),<br>  ],<br>  server: {<br>    port: 5001,<br>    cors: true,<br>    headers: {<br>      &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>    },<br>  },<br>  build: {<br>    target: &#39;esnext&#39;,<br>  },<br>});</pre><p>Here I’ve also exposed the store created so that it can be utilized by the host application, and if you take a look at the shared dependencies, you’ll be able to notice zustand there, as it is now a requirement for any micro frontend which uses this store.</p><p>4. Now re build the remote application</p><pre>npm run build<br>npm run serve</pre><p>5. Go to the host application and then utilize this store like you’ve used the Button component, you’ll be able to use all the methods created within the store like, increment, decrement, count etc.</p><pre>import &#39;./App.css&#39;;<br>import Button from &quot;remoteApp/Button&quot;;<br>import useStore from &#39;remoteApp/store&#39;;<br><br>function App() {<br><br>  const { count, increment } = useStore()<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;This is the Host Application&lt;/h1&gt;<br>      &lt;h1&gt;This is the count from the remote: {count}&lt;/h1&gt;<br>      &lt;Button /&gt; &lt;br /&gt;<br>      &lt;button style={{ margin: &quot;20px&quot; }} onClick={() =&gt; increment(1)}&gt;button From host application but increment method from remote&lt;/button&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default App</pre><p>Here as you can see that i have imported the store from the remote Application and then I’ve used the method within the useStore like count and increment. And as a result you can see the count, and upon clicking on the button you can see the count increasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3cF-ufkTa59wnra9r6k2g.png" /><figcaption>UI of host after the implementation of the remote store</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*45tJFKiFMAZhipaH5VX70w.png" /></figure><p>It’s as easy as that, Now we’ve put up a simple micro frontend application, and also learned how to implement global state management in it. That’s it for this article. In the next one we’ll learn how to implement routing in micro frontend application.</p><p>If any of you want to my codebase where I’ve setup this project, I’ll link it below.</p><p><a href="https://github.com/Jilshak/micro-frontend-vite">GitHub - Jilshak/micro-frontend-vite</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911813c75645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the Gap: Effective Communication Strategies for Micro Frontends]]></title>
            <link>https://medium.com/@mohd.jilshak/bridging-the-gap-effective-communication-strategies-for-micro-frontends-5f226c073fd6?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f226c073fd6</guid>
            <category><![CDATA[micro-front-end]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[front-end-design]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 17:16:16 GMT</pubDate>
            <atom:updated>2024-08-01T13:40:56.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*4UNs1X5RAtpFbKKwbECneA.png" /></figure><p>In the <a href="https://medium.com/@mohd.jilshak/a-beginners-walkthrough-understanding-micro-frontend-architecture-a62027b72f39"><strong>previous part</strong></a>, we’ve discussed about how micro frontends are loosely coupled with one another. Well, it is this coupling that enables the seamless communication between these micro frontends possible.</p><p>Communication between micro frontends are very crucial. Without them, each of the micro-frontends (<em>units</em>) created, are just chunks of code isolated from one another, which basically makes the whole idea of implementing micro frontend architecture absurd.</p><p>There are multiple ways in which seamless communication between micro frontends can be implemented.</p><p><strong>Modes Of Communication</strong></p><ol><li>Custom Events</li><li>URL Query Parameters</li><li>Global State Management</li><li>Shared Services</li><li>Post Message API <em>(communication between Iframes)</em></li><li>Server Side Communication</li><li>Local Storage and Session Storage</li></ol><p>All of these communication strategies (methods) have it’s own advantages and disadvantages. As we go through each of these we’ll get to know and understand them. Though here we’ll be only discussing the most important ones among them.</p><blockquote>Note: I’ll be using the keyword “Unit” and “Micro-frontend” interchangeably through out this article</blockquote><p><strong>Custom Events:</strong></p><p>To simply put, they work by <strong>Emitting </strong>and <strong>Listening </strong>to events which are being transmitted from micro-frontends (units).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*c7Tmo5SE5Bz-Vqa6ZgkAWw.png" /><figcaption>Units interacting with one another using custom events (0.1)</figcaption></figure><p>Here as you can see, these are the same examples from our previous article, we have 3 units from an e-commerce website, which are interacting with one another. Now, Imagine a scenario where an user named Bob goes to this e-commerce website, the first page he will see is an <em>Home </em>page<em>, </em>which is one of our unit. From here when he clicks on the add to cart button there has to be some sort of interaction between the <em>Home</em> unit and the <em>Cart</em> unit for the changes to occur in the <em>Cart (for the product to be added)</em>, this communication here is done through the help of emitting and listening to events. ( <em>the same goes for the interaction between Cart and Payment)</em></p><p><em>Example:</em></p><ol><li>Create an event in the <em>Home </em>unit like this</li></ol><pre>const event = new CustomEvent(&#39;cartUpdated&#39;, { detail: { item: &#39;newItem&#39; } });<br>window.dispatchEvent(event);</pre><p>This sends (dispatches) an <em>customEvent</em> named “<em>cartUpdated</em>” with some values defined within it.</p><p>2. Create an Listener in the <em>Cart </em>unit so that when this event is dispatched it can listen to it and take necessary actions based on the dispatched events.</p><pre>window.addEventListener(&#39;cartUpdated&#39;, (event) =&gt; {<br>  console.log(&#39;Cart updated with:&#39;, event.detail.item);<br>});</pre><p>Here it receives the <em>cartUpdated</em> event which was fired by the other unit by using <em>addEventListener. W</em>hat it is basically do is, it waits for the event by the name of <em>cartUpdated</em> to be fired, if such an event is fired it captures that events and then logs the value.</p><blockquote>Note: The name of the event has to be same on both the units (global namespaces) i.e. the one who emits the event and the one which listens to it. So this in turn creates a strong coupling between these units, because if the name of the event changes in the emitter it also has to be changed on the listener.</blockquote><p><strong>Advantages Of Using Custom Events As Communication Method:</strong></p><ul><li>Decoupling</li><li>Simplicity</li><li>Asynchronous communication</li><li>Built in browser support.</li></ul><p><strong>Disadvantages Of Using Custom-Events As Communication Method</strong></p><ul><li>Global Namespace</li><li>Limited Scope</li><li>Performance Issue</li></ul><p>In short Custom Events are generally preferred, when we need decoupled and asynchronous communication within the same browser window.</p><p><strong>URL Query Parameters:</strong></p><p>So here the idea is to update the URL parameters, i.e. One unit updates the query parameter and the other one reads it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*CmxcHB8G-2pttxmIijPWWA.png" /><figcaption>Example for an URL along with parameters (0.2)</figcaption></figure><p>Let’s take the previous example of <em>Cart</em> and <em>Home</em> as an example here. Imagine a scenario where an user named Alan is using our website. He saw a product which he want to buy and adds it to the cart. We’ve already discussed how this will occur if we were using the custom events. In this case when Alan clicks on the add to cart button, the parameter in the URL changes, this change is read by the other unit (Cart) and then acts according to the logic written for handling this.</p><p><em>Example:</em></p><ol><li>Create a function in the <em>Home</em> unit, which upon clicking it adds the item ID to the URL upon clicking on it</li></ol><pre>function addToCart(itemId) {<br>  const url = new URL(window.location);<br>  url.searchParams.set(&#39;cartItem&#39;, itemId);<br>  window.history.pushState({}, &#39;&#39;, url);<br>}</pre><pre>addToCart(&#39;12345&#39;);</pre><p>2. Now in the <em>Cart</em> unit create a function which reads the URL query parameters</p><pre>function getCartItemFromUrl() {<br>  const urlParams = new URLSearchParams(window.location.search);<br>  return urlParams.get(&#39;cartItem&#39;);<br>}</pre><pre>const cartItem = getCartItemFromUrl();<br>if (cartItem) {<br>  console.log(&#39;Item to add to cart:&#39;, cartItem);<br>}</pre><blockquote>Note: It has to be in the same window for this to work. If Cart unit is opened in one window and the Home unit in another, this won’t work</blockquote><p><strong>Global State Management:</strong></p><p>Communication done with the help of state is one of the most effective and efficient method which can be implemented in micro frontend architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*E-OjcKHy8IEHYmN5yy6WPA.png" /><figcaption>Global state management for micro-frontend (0.3)</figcaption></figure><p>In the above given image, as we can see, there is an <em>Global Store </em>set up which is connected to all the units (micro-frontends). Here all the global states (states which are required by more than one micro frontend) are managed in the global store, so if there are any changes in the store, all its dependents (which consumes that state from the store) are also effected. This helps in synchronization between micro frontends much more easier and efficient compared to the other methods.</p><blockquote>Note: The global store can be a micro-frontend unit in and of itself. I’ve given here an global store on top of all three units just for understanding. If need be, we can assign on of the three units i.e. Cart, Payment or Home as the global store, and it’s not necessary for us to assign an individual micro frontend store, though it is preferred by many.</blockquote><p><em>Example:</em></p><blockquote>I’ll be using “<a href="https://zustand-demo.pmnd.rs/">Zustand</a>” here, as it is much easier to use and we can avoid a lot of boilerplate code</blockquote><ol><li>Set up the <a href="https://zustand-demo.pmnd.rs/">zustand</a> store in your desired micro frontend unit, or you can create a separate one solely for this purpose.</li></ol><pre>import { create } from &#39;zustand&#39;;<br><br>const useStore = create((set) =&gt; ({<br>  user: null,<br>  setUser: (user) =&gt; set({ user }),<br>  cartItems: [],<br>  addItem: (item) =&gt; set((state) =&gt; ({ cartItems: [...state.cartItems, item] })),<br>  removeItem: (id) =&gt; set((state) =&gt; ({ cartItems: state.cartItems.filter(item =&gt; item.id !== id) })),<br>}));<br><br>export default useStore;</pre><p>2. Now we need to expose the store (we’ll get to that in the next part of the article)</p><blockquote>Note: Image this running on the port <a href="http://localhost:3001/">http://localhost:3001</a></blockquote><pre>// webpack.config.js of the store unit (micro frontend) application<br>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &#39;Store&#39;,<br>      exposes: {<br>        &#39;./store&#39;: &#39;./src/store&#39;,<br>      }, // the name of the store and the path to it <br>      shared: {<br>        react: { singleton: true },<br>        &#39;react-dom&#39;: { singleton: true },<br>        zustand: { singleton: true },<br>      },<br>    }),<br>  ],<br>};</pre><p>3. Now go to the <em>Home</em> unit and then fetch the exposed store from the store unit (micro frontend).</p><pre>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &#39;Home&#39;,<br>      remotes: {<br>        remoteApp: &#39;microfrontend1@http://localhost:3001/remoteEntry.js&#39;, <br>      }, // mention the end point from where we are importing the store<br>      shared: {<br>        react: { singleton: true },<br>        &#39;react-dom&#39;: { singleton: true },<br>        zustand: { singleton: true },<br>      }, // both should have the zustand here as it is being used here also<br>    }),<br>  ],<br>};</pre><p>4. Now you can simply use it by importing it in our <em>Home </em>unit, Yes! it’s as easy as that.</p><pre>// Home/src/App.js<br>import React from &#39;react&#39;;<br>import useStore from &#39;remoteApp/store&#39;;<br><br>const App = () =&gt; {<br>  const user = useStore((state) =&gt; state.user);<br>  const setUser = useStore((state) =&gt; state.setUser);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Microfrontend 1&lt;/h1&gt;<br>      &lt;p&gt;User: {user}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setUser(&#39;John Doe&#39;)}&gt;Set User&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>There are many more communication strategies which we can bring to the table, while implementing micro frontend architecture. And here we’ve discussed 3 of the most widely used ones.</p><p>In the next part of this article, we’ll be creating an simple <a href="https://medium.com/@mohd.jilshak/building-a-simple-micro-frontend-application-with-module-federation-a-step-by-step-guide-911813c75645"><strong>micro-frontend application using module federation</strong></a> and we’ll also learn about the difference between <a href="https://medium.com/@mohd.jilshak/micro-frontend-build-time-composition-and-run-time-composition-9690b72ebaeb"><strong>Build time and Run time composition</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f226c073fd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Walkthrough: Understanding Micro frontend Architecture]]></title>
            <link>https://medium.com/@mohd.jilshak/a-beginners-walkthrough-understanding-micro-frontend-architecture-a62027b72f39?source=rss-87b6ab9e9727------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62027b72f39</guid>
            <category><![CDATA[micro-front-end]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[architecture-pattern]]></category>
            <dc:creator><![CDATA[Muhammad Jilshak K]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 11:40:15 GMT</pubDate>
            <atom:updated>2024-07-29T11:30:45.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*n4tnUy8pzPZP4QJ_05pM1Q.png" /></figure><p>Before we get into the topic of Micro Frontend, first we need to understand what the term “<em>Architecture</em>” actually means. To put it simply, it is a <strong>blueprint,</strong> which details the structure, layouts and connection between various components which interact with one another within a system. In software development field, an architecture outlines how different parts of a software system are organized and are interacting with one another.</p><p><strong>Few Examples of Software Architecture:</strong></p><ul><li>Monolithic Architecture</li><li>Microservice Architecture</li><li>Micro-frontend Architecture</li><li>Event-Driven Architecture</li></ul><p><strong>What is Micro frontend?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*kPbaNs9P50bmtfaV8fjcKA.png" /><figcaption>Microservice architecture and Micro-Frontend Architecture (0.1)</figcaption></figure><p>Micro frontend is an architectural style which implements the concept of microservices to the frontend. So what it basically does is, It divides the monolithic frontend application to smaller, independent units. Now each of these units will have their own specific functionality (feature) of the overall application.</p><p><strong>Key Characteristics of Micro frontends:</strong></p><ol><li>Independence</li><li>Single Responsibility</li><li>Loose Coupling</li><li>Technological Diversity</li><li>Deployment</li></ol><p><strong>Detailed Explanation of Each Characteristic:</strong></p><ol><li><strong>Independence:</strong></li></ol><p>Each micro frontend operates independently, allowing different teams to develop, test, and deploy their micro frontend without interfering with others.</p><p><em>Example:</em></p><p>Imagine you’re creating an Ecommerce application using micro frontend architecture. You have multiple independent micro-frontends, each with its own functionality. say, you have an Payment-micro-frontend and Cart-Micro frontend, now each of these serve a different purpose and work can be done on each one of these without interfering with the other one, whilst if it were an monolithic architecture, there will be tight coupling between these two and working on one part can interfere and effect the other one.</p><p><strong>2. Single Responsibility:</strong></p><p>A micro frontend is responsible for a single functionality or feature of the application. This adherence to the single responsibility principle ensures that each micro frontend remains focused and manageable.</p><p><em>Example:</em></p><p>In an Ecommerce application, the cart feature can be considered a single responsibility. The sole purpose of this micro frontend is to handle the cart’s functionality.</p><p><strong>3. Loose Coupling:</strong></p><p>Micro frontends are not completely decoupled, but are loosely coupled as each of these micro-frontends need to interact with one another. All of them are units of the same application having their own individual functionalities (responsibilities). This enables faster development, improves the maintainability of the code, increases the flexibility of the technologies used in each of these, and offers many more benefits.</p><p><em>Example:</em></p><p>Consider an e-commerce application that uses a micro frontend architecture, divided into three units: <em>Cart, Payment,</em> and <em>Home</em> (refer to diagram <em>0.1</em>). Each unit operates independently with its own responsibility. However, these units may need to communicate with each other at times.</p><p>For instance, a user named Alan is using our e-commerce application. Upon entering the Home page, Alan finds a product he has been searching for a long time. He immediately adds it to his <em>Cart</em> (showing interaction between the Home and Cart micro frontends). Next, Alan proceeds to the Cart to purchase the product. During the purchasing process, there is an interaction between the Cart micro frontend and the Payment micro frontend.</p><p>In this scenario, even though<em> Home, Cart</em>, and <em>Payment</em> are independent units, they interact to provide a seamless user experience. This loose coupling allows each micro frontend to be developed, maintained, and scaled independently while still functioning cohesively as part of the overall application.</p><p><strong>4. Technological Diversity:</strong></p><p>One of the main advantages of implementing micro frontend while building frontend is that we don’t need to stick to any specific technology.</p><p><em>Example:</em></p><p>Suppose we are building that Ecommerce website shown in the diagram above <em>(0.1). </em>Imagine that first unit (<em>Cart </em>micro-frontend)<em>, </em>is build using React. Now, if this was not following the micro frontend architecture, we might have to create the entire frontend part of the application using this single technology i.e. React, but since we are using micro frontend, we can also use other technologies to build the rest of the units i.e. <em>Payment</em> and <em>Home. (</em>we could use<em> Angular </em>or<em> Vue </em>if need be<em>)</em></p><p><strong>5. Deployment:</strong></p><p>Since micro frontends are divided into small units with single responsibility in mind, they can also be deployed independently without effecting the other. So if there is any change to one part of the application, we won’t have to redeploy the entire frontend, instead we can just redeploy only that unit where the change is required, which in turn, will reflect in the other units as well.</p><p><em>Example:</em></p><p>If there is a change in the <em>Cart</em> micro-frontend, we won’t have to redeploy the entire frontend, instead, we only need to redeploy that individual unit <em>i.e. Cart</em>, and by doing so, the other units which are loosely coupled with that unit, will also have the desired change reflected in them without them ever being redeployed.</p><p><strong>Advantages of using micro frontend architecture:</strong></p><ul><li><strong>Scalability:</strong> Individual micro frontends can be scaled as per our requirement.</li><li><strong>Maintainability:</strong> Since each unit is loosely coupled, it is easier to maintain them.</li><li><strong>Team Autonomy:</strong> Multiple teams can work independently of one another without affecting the others.</li><li><strong>Reduced Risk:</strong> Isolated updates reduce the risk of widespread bugs.</li></ul><p><strong>Disadvantages of using micro frontends:</strong></p><ul><li><strong>Increased Complexity:</strong> Management of multiple micro frontend units can be quite complex.</li><li><strong>Performance Overhead:</strong> Since there are multiple units, it can lead to performance issues as each of them is deployed independently.</li><li><strong>Consistency Issues:</strong> Ensuring consistent look and feel across all micro frontends can be challenging.</li></ul><p><strong>Conclusion:</strong></p><p>Micro frontend architecture allows breaking down monolithic frontends into smaller, independent units, enhancing scalability, maintainability, and team autonomy. Despite the challenges of increased complexity and potential performance overhead, its benefits in terms of flexibility and independent deployments make it a compelling choice for modern web applications. Embracing micro frontends can lead to more modular and efficient frontend development, meeting the evolving demands of the software industry.</p><p>This article is published in installments, and here’s where first one ends. In the next part you’ll read about the way <a href="https://medium.com/@mohd.jilshak/bridging-the-gap-effective-communication-strategies-for-micro-frontends-5f226c073fd6"><strong>micro frontends communicate and share data</strong></a> between each other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62027b72f39" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>