<?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 Isuru Ariyarathna on Medium]]></title>
        <description><![CDATA[Stories by Isuru Ariyarathna on Medium]]></description>
        <link>https://medium.com/@isuruariyarathna2k00?source=rss-f92ef40b6108------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jzsikq8LimMHHc6Y</url>
            <title>Stories by Isuru Ariyarathna on Medium</title>
            <link>https://medium.com/@isuruariyarathna2k00?source=rss-f92ef40b6108------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:38:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isuruariyarathna2k00/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[Adding Custom Role Claims to an Access Token in Azure AD B2C]]></title>
            <link>https://medium.com/@isuruariyarathna2k00/adding-custom-role-claims-to-an-access-token-in-azure-ad-b2c-c890fe677f4e?source=rss-f92ef40b6108------2</link>
            <guid isPermaLink="false">https://medium.com/p/c890fe677f4e</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-ad-b2c]]></category>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <dc:creator><![CDATA[Isuru Ariyarathna]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 18:40:58 GMT</pubDate>
            <atom:updated>2025-01-30T18:42:33.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rDgLfRLp3b3MR00TZ43cg.png" /></figure><p>When building an application that relies on Azure AD B2C for authentication, it’s often necessary to manage roles for users. You might want to grant different levels of access, like “<em>Admin</em>,” “<em>Editor</em>,” or “<em>User</em>,” based on their assigned roles. However, Azure AD B2C does not natively support role claims in access tokens, so we need to work around this limitation by using custom attributes and the Microsoft Graph API.</p><p>In this guide, we’ll go through the entire process of registering two apps in Azure AD B2C, creating custom attributes, assigning roles dynamically, and retrieving them in an access token.</p><h4>Why Do We Need Two App Registrations?</h4><p>To implement this solution, we need two separate app registrations in Azure AD B2C</p><ol><li><strong>One for authentication (frontend/client app):</strong> This is the app that users log into. It handles authentication and requests access tokens.</li><li><strong>One for API access (backend app):</strong> This is where we define custom API permissions (scopes) and expose them to the authentication app.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6elV2008gYKXPm9IJhkiJQ.png" /><figcaption>All App registrations we should have for this</figcaption></figure><h4>Step 1: Create the First App Registration (Authentication App)</h4><p>First, we need to register an app that will handle user sign-ins and request access tokens.</p><p>Go to the Azure Portal, navigate to Azure AD B2C, and open App registrations. Click New registration and give your app a name. In the Redirect URI section, add thishttps://jwt.ms. This is a simple tool that will let us inspect the tokens for testing purposes.</p><p>After registering the app, go to Authentication and check both</p><ul><li>Access tokens (used for implicit flows)</li><li>ID tokens (used for implicit and hybrid flows)</li></ul><p>This ensures the app can receive tokens containing user claims.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tY2XAIeN5n_ZFOb_d54xMA.png" /><figcaption>Add <a href="https://jwt.ms/">https://jwt.ms</a> as redirect uri and select token types.</figcaption></figure><h4>Step 2: Create the Second App Registration (API App)</h4><p>Now, we need to create another app registration for our API. This app will define custom scopes that the authentication app can request.</p><p>Go back to App registrations and create a new one. This time, you don’t need to add any Redirect URIs. After the app is created, go to API Permissions and add:</p><ul><li>offline_access</li><li>openid</li><li>User.ReadWrite.All</li></ul><p>Then, click Grant admin consent to approve these permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UZxwDh6RkhMUeP5RB8szA.png" /><figcaption>Creta App Registration for API</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VTwNkujiJjPLxwuhw3STdQ.png" /><figcaption>Add API permissions to the API App</figcaption></figure><p>Next, we need to expose an API. Under the expose an API section, create two scopes:</p><ul><li>api://&lt;CLIENT-ID&gt;/Read</li><li>api://&lt;CLIENT-ID&gt;/Write</li></ul><p>These will be used later to control access to specific actions in your backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OiSI_kUOOtwmhTmDa69Acw.png" /><figcaption>Expose 2 APIs for Read &amp; Write</figcaption></figure><h4>Step 3: Link the Authentication App to the API App</h4><p>Now that we’ve set up the API, we need to allow our authentication app to request these permissions.</p><p>Go back to the first app registration (Authentication App) and navigate to API Permissions. Click Add a permission, select My APIs, and choose the API app you just created. Then, add the Read and Write scopes.</p><p>Once done, grant admin consent to finalise the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kAC5Dj5Y11qrA2yrsX7O9w.png" /><figcaption>Add exposed APIs to the authentication App registration.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWcwY-TyHFcN3qfPZsFMuw.png" /><figcaption>These are all API permissions we need to have in authentication App registration.</figcaption></figure><h4>Step 4: Add a Custom Attribute for user roles</h4><p>Azure AD B2C doesn’t include a “role” attribute by default, so we need to create one manually.</p><p>In the Azure AD B2C portal, go to User Attributes and add a new attribute named Role. Set its type to String, and save it. This attribute will store the user’s role, which we can later modify via the Microsoft Graph API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQxmbLp7Bfftc2QTpIYP2Q.png" /><figcaption>Add custom Role attribute the user attributes</figcaption></figure><h4>Step 5: Assign a Role to a User via Microsoft Graph API</h4><p>Since role management isn’t built into Azure AD B2C, we’ll manually update a user’s role using a backend API call. In Azure AD B2C, custom attributes get prefixed with, extension_ followed by your App Client ID.</p><p>To update a user’s role, we’ll send a PATCH request to the Microsoft Graph API using Node.js. Here’s how you do it</p><pre>javascript<br>Copy<br>let key = `extension_${EXTENSIONS_APP_CLIENT_ID}_Roles`;<br>let data = {};<br>data[key] = role;  // Assign a role (e.g., &quot;Admin&quot;, &quot;User&quot;)<br><br>let jsonString = JSON.stringify(data);<br><br>let config = {<br>    method: &#39;patch&#39;,<br>    maxBodyLength: Infinity,<br>    url: `https://graph.microsoft.com/v1.0/users/${USERID}`,<br>    headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        &#39;Authorization&#39;: `Bearer ${TOKEN}`<br>    },<br>    data: jsonString<br>};<br><br>const response = await axios(config);<br>console.log(&#39;Role updated:&#39;, response.data);</pre><p>This script updates the user’s Role attribute. The key is dynamically constructed using the extension_prefix and the App Client ID.</p><h4>Step 6: Get an Access Token to Make API Calls</h4><p>Before making requests to Microsoft Graph, we need an access token. We can obtain one using the following function</p><pre>javascript<br>Copy<br>const getAuthToken = async () =&gt; {<br>    console.log(&#39;Getting token&#39;);<br>    try {<br>        const data = {<br>            scope: &#39;https://graph.microsoft.com/.default&#39;,<br>            grant_type: &#39;client_credentials&#39;,<br>            client_secret: CLIENT_SECRET,<br>            client_id: CLIENT_ID<br>        };<br><br>        let config = {<br>            method: &#39;post&#39;,<br>            maxBodyLength: Infinity,<br>            url: `https://login.microsoftonline.com/${TENANT_ID}/oauth2/v2.0/token`,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;<br>            },<br>            data: data<br>        };<br><br>        const response = await axios(config);<br>        return response.data.access_token;<br>    } catch (error) {<br>        console.error(&#39;Error getting token&#39;, error);<br>        return null;<br>    }<br>};</pre><p>Once you have the token, pass it as the Authorization header when calling Microsoft Graph.</p><h4>Step 7: Verifying the Role Claim in an Access Token</h4><p>Now that we’ve assigned a role to a user, let’s check if it appears in the access token.</p><ol><li>Sign in to your authentication app and request an access token.</li><li>Decode the token using https://jwt.ms and look for the custom role claim.</li><li>If everything is set up correctly, you should see something like this in the token payload</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*HqPS6AMWOFgKbrCRDVIUkQ.png" /></figure><p>If the roles attribute is missing, double-check that the user has been assigned a role and that your API app is correctly configured to include custom claims.</p><h4>Changing User Role Using Postman (cURL Request)</h4><p>Once you have set up everything, you might want to update a user’s role manually using Postman or cURL. Below is the cURL command to update a user’s custom role using the Microsoft Graph API.</p><pre>sh<br>Copy<br>curl --location --request PATCH &#39;https://graph.microsoft.com/v1.0/users/USER_ID&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Authorization: Bearer TOKEN&#39; \<br>--data &#39;{<br>    &quot;extension_EXTENSIONS_APP_CLIENT_ID(WITHOUT&#39;-&#39;_&#39;)_Role&quot;: &quot;custom_role&quot;<br>}&#39;</pre><h4>Conclusion</h4><p>By following these steps, we’ve successfully,</p><ul><li>Created two app registrations to handle authentication and API access.</li><li>Exposed custom API permissions and linked them to the authentication app.</li><li>Created a custom user attribute to store roles.</li><li>Used Microsoft Graph API to dynamically assign roles to users.</li><li>Retrieved the updated role claims in an access token.</li></ul><p>This approach allows you to manage role-based access control (RBAC) in Azure AD B2C without needing an external database. If you run into issues, check your API permissions and admin consents, and make sure the custom attribute is properly registered.</p><h4>Note</h4><p><em>Please note that the screenshots included in this blog are for illustrative purposes only. The Azure resources referenced have been deleted after capturing the images to maintain security and privacy.</em></p><p>For further exploration and collaboration, visit <a href="https://www.isuruariyarathna.me/"><strong>my website</strong></a><strong> </strong>and consider supporting us through <a href="https://www.buymeacoffee.com/isuruariyarathna"><strong>Buy Me a Coffee</strong></a>.</p><p>Catch you on the flip side!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c890fe677f4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to API Management with Azure]]></title>
            <link>https://medium.com/@isuruariyarathna2k00/introduction-to-api-management-with-azure-f357d0cab13c?source=rss-f92ef40b6108------2</link>
            <guid isPermaLink="false">https://medium.com/p/f357d0cab13c</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[azure-api-management]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[api-management]]></category>
            <category><![CDATA[azure-services]]></category>
            <dc:creator><![CDATA[Isuru Ariyarathna]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 12:32:08 GMT</pubDate>
            <atom:updated>2024-04-29T12:32:08.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHn8h7mTy1k7cJfFhyjrXw.png" /></figure><p>Hey there, fellow tech enthusiast! Ever wondered how your favorite apps and websites seamlessly communicate with each other, sharing data and functionality? Well, that’s where APIs come into play. In this beginner’s guide, we’re diving into the exciting world of API Management, with a special focus on Azure API Management (APIM). So, buckle up, and let’s embark on this journey together!</p><h3>What is API?</h3><p>Let’s start with the basics. API stands for Application Programming Interface. Think of it as a bridge that allows different software applications to communicate and interact with each other. APIs define the rules and protocols for how this communication should occur, enabling developers to access certain features or data from another application or service.</p><h4>Managed API vs. Unmanaged APIs (Naked APIs)</h4><p>Okay, let’s break it down further. Imagine you’re a developer building a new application. You need access to data from various sources — weather updates, social media feeds, payment gateways, you name it. Without APIs, you’d have to build everything from scratch, which is time-consuming and error-prone.</p><p>Here’s where the concept of “managed” and “unmanaged” (or “naked”) APIs comes into play.</p><p><strong>Unmanaged (Naked) APIs </strong>— These are APIs that are exposed directly by the service provider. Think of them as raw data pipelines — they provide access to the underlying functionality of a service without any additional management layer. While unmanaged APIs offer flexibility and direct access to resources, they come with challenges such as security risks, scalability issues, and lack of centralized control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1Ad5NF8WBC8t6fxgZzuaA.png" /></figure><p><strong>Managed APIs</strong> — Enter API management platforms like Azure API Management. Managed APIs are like the well-maintained bridges in our city analogy. They provide a layer of abstraction and control over your APIs, offering features such as authentication, authorization, rate limiting, caching, and analytics. With managed APIs, you can ensure security, scalability, and reliability while simplifying the integration process for developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dkVczsGRvAuZzqIrvzNxg.png" /></figure><h3>What is API Management?</h3><p>Imagine you’re at a fancy restaurant, and you’re handed a menu with an extensive list of dishes. Each dish represents a service provided by the restaurant — from appetizers to desserts. Now, think of APIs (Application Programming Interfaces) as the menu of a digital world. They define how different software components or services can interact and communicate with each other.</p><p>API Management, then, is like having a seasoned maître d’ orchestrating the flow of communication between these services. It’s all about ensuring that APIs are easily accessible, secure, and performant, just like ensuring your dining experience at the restaurant is smooth and enjoyable.</p><h4>Why is API Management Important?</h4><p>Let’s put it this way. APIs are the backbone of modern digital ecosystems. They enable applications, systems, and devices to connect, collaborate, and share data. Without proper management, APIs can become chaotic — leading to security vulnerabilities, poor performance, and developer frustration.</p><p>That’s where API Management steps in to save the day! It provides a centralized platform to manage, monitor, and secure your APIs, offering benefits such as:</p><ul><li><strong>Enhanced Security </strong>— Safeguard your APIs against unauthorized access and potential threats.</li><li><strong>Improved Developer Experience </strong>— Streamline the process for developers to discover, consume, and integrate APIs.</li><li><strong>Optimized Performance </strong>— Ensure your APIs deliver blazing-fast responses and scale seamlessly to meet demand.</li><li><strong>Insightful Analytics</strong>: Gain valuable insights into API usage, performance metrics, and user behavior.</li></ul><h4>Benefits of Implementing API Management</h4><p>So, what’s in it for you? Whether you’re a developer, an IT administrator, or a business owner, API Management brings a plethora of advantages.</p><ul><li><strong>Accelerated Innovation</strong>: Empower developers to build new applications faster by leveraging existing APIs.</li><li><strong>Monetization Opportunities</strong>: Unlock new revenue streams by exposing your APIs to external developers or partners.</li><li><strong>Compliance and Governance</strong>: Maintain regulatory compliance and enforce policies to govern API usage effectively.</li><li><strong>Agility and Flexibility</strong>: Adapt to changing market demands and evolving business requirements with ease.</li></ul><h3>Azure API Management Overview</h3><p>Azure API Management (APIM) is a comprehensive platform provided by Microsoft Azure for building, deploying, securing, and monitoring APIs. In this section, we will provide an overview of Azure API Management, highlighting its key features, capabilities, pricing model, and options.</p><h4>Introduction to Azure API Management (APIM)</h4><p>Azure API Management empowers organizations to create scalable and secure API ecosystems, enabling seamless integration and collaboration across applications and services. With Azure APIM, businesses can transform their APIs into consumable products, manage their lifecycle, and expose them to external developers and partners through self-service developer portals.</p><h4>Key Features and Capabilities of Azure APIM</h4><p>Azure API Management offers a wide array of features and capabilities to streamline API management processes:</p><ol><li><strong>API Gateway</strong>: Azure APIM serves as an API gateway, allowing organizations to manage inbound and outbound traffic, enforce policies, and apply security measures such as authentication, authorization, and encryption.</li><li><strong>Developer Portal</strong>: APIM provides a customizable developer portal where developers can discover, explore, and consume APIs. The developer portal offers interactive documentation, code samples, and sandbox environments to facilitate API adoption and integration.</li><li><strong>API Lifecycle Management</strong>: Azure APIM supports the entire API lifecycle, from design and development to deployment and monitoring. Organizations can design APIs using industry-standard specifications like OpenAPI (formerly Swagger), implement them using various protocols and frameworks, and seamlessly deploy them to production environments.</li><li><strong>Security and Access Control</strong>: APIM offers robust security features, including OAuth, API key management, JWT validation, IP filtering, and rate limiting, to protect APIs from unauthorized access, data breaches, and malicious attacks.</li><li><strong>Monitoring and Analytics</strong>: Azure APIM provides comprehensive monitoring and analytics capabilities to track API usage, performance, and health in real time. Organizations can leverage built-in dashboards, logs, and alerts to gain insights, troubleshoot issues, and optimize API performance.</li><li><strong>Scalability and High Availability</strong>: Azure APIM is built on a scalable and resilient infrastructure, ensuring high availability and performance even under heavy workloads. Organizations can scale their API management solutions horizontally or vertically to meet growing demands.</li></ol><h4>Pricing Model and Options</h4><p>Azure API Management offers flexible pricing options tailored to the needs of businesses.</p><ol><li><strong>Consumption </strong>— Pay based on the number of API calls processed, suitable for scenarios with unpredictable traffic patterns.</li><li><strong>Developer </strong>— A free tier with limited features and capacity, allowing developers to experiment with the platform.</li><li><strong>Basic and Basic v2 </strong>— Offer essential features with different performance levels and scale limits.</li><li><strong>Standard and Standard v2 </strong>— Provide additional features like multi-region deployments, traffic manager integration, and higher scale limits.</li><li><strong>Premium </strong>— Offers advanced capabilities such as advanced security, content caching, and multi-region deployments with unlimited scale.</li></ol><h3>Creating an Azure API Management Instance</h3><p>Creating an Azure API Management instance is straightforward and can be done through the Azure portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0eBcmP_8_sZkkdN7qi6ug.png" /></figure><ol><li>Log in to the Azure Portal using your Azure account credentials.</li><li>Once logged in, navigate to the Azure API Management service by searching for “API Management” in the Azure Portal’s search bar.</li><li>Click on “Create” to create a new instance of Azure API Management. You will be prompted to provide details such as subscription, resource group, instance name, location, pricing tier, and organization details.</li><li>Configure additional settings such as SKU, deployment mode (development or production), and virtual network integration based on your requirements.</li><li>Review the settings, terms of use, and pricing details before clicking on “Create” to provision the Azure API Management instance.</li><li>Wait for the deployment process to complete. Once the deployment is successful, you can access your Azure API Management instance from the Azure Portal.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5qgSEOE1y2UFqZvTeRsbw.png" /></figure><p>In the subsequent sections of this blog series, we will explore in detail how to set up and configure Azure API Management, create APIs, manage their lifecycle, implement security measures, and leverage analytics for insights and optimization. Stay tuned for a comprehensive guide on harnessing the power of Azure API Management to drive digital transformation and innovation within your organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvldNJFddHXkS6sH2KAguw.png" /></figure><p>Once the deployment is complete, navigate to your Azure API Management instance from the Azure Portal dashboard. From the API Management instance dashboard, you can access various features and settings related to API management, including APIs, products, subscriptions, analytics, and developer portal customization. Start by creating APIs within your API Management instance. You can import existing APIs, define new APIs using OpenAPI or Swagger specifications, or create APIs from scratch using the built-in editor. Products act as containers for APIs and define access policies, rate limits, and subscription plans. Define products based on your API offerings and target audience. Subscriptions allow developers to access and consume APIs within defined limits. Manage subscriptions to control access, track usage, and enforce security policies.</p><h4>Explaining API Management Terminology</h4><ol><li><strong>APIs</strong> (Application Programming Interfaces) are endpoints that expose functionalities or data from a backend service to external clients.</li><li><strong>Products</strong> are bundles of APIs with predefined access policies, rate limits, and subscription plans, designed to cater to specific use cases or target audiences.</li><li><strong>Subscriptions</strong> grant developers access to APIs within defined usage limits and enforce security policies such as authentication and authorization.</li><li><strong>The developer portal</strong> is a self-service portal where developers can discover, explore, and consume APIs, access documentation, and manage their subscriptions.</li><li><strong>Policies</strong> are configurable rules and behaviors applied to APIs at runtime, allowing you to implement security, transformation, caching, and other custom logic.</li></ol><h3>API Lifecycle Management</h3><p>API Lifecycle Management is a critical aspect of successfully managing APIs from conception to retirement. In this section, we will explore the different phases of the API lifecycle and how Azure API Management facilitates each phase effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQ3CaCcYBKK9gv2oSuoRcw.png" /></figure><h4>Design Phase</h4><ol><li><strong>API Design Guidelines</strong>: Before creating APIs, establish design guidelines to ensure consistency, reusability, and scalability across your API ecosystem. Consider factors such as naming conventions, versioning strategies, error handling, and data formats.</li><li><strong>API Definition</strong>: Use OpenAPI (formerly Swagger) or other industry-standard specifications to define your APIs’ structure, endpoints, parameters, request/response payloads, and authentication mechanisms.</li><li><strong>API Creation</strong>: Within Azure API Management, create APIs by importing existing definitions or designing them using the built-in editor. Define operations, set policies, and configure endpoints to expose your API functionalities.</li></ol><h4>Development Phase</h4><ol><li><strong>API Implementation </strong>— Implement APIs according to the defined specifications, ensuring adherence to design guidelines and best practices. Use Azure Functions, Azure App Service, or other backend services to host your API logic.</li><li><strong>Testing </strong>— Conduct thorough testing of APIs to validate functionality, performance, and security. Leverage tools like Postman, Swagger Inspector, or Azure API Management’s built-in testing capabilities to execute API requests and assess responses.</li><li><strong>Debugging </strong>— In case of issues or errors, use Azure API Management’s debugging features to diagnose and troubleshoot problems. Review logs, monitor traffic, and analyze error responses to identify and resolve issues promptly.</li></ol><h4>Deployment Phase</h4><ol><li><strong>Environment Setup </strong>— Configure different environments such as development, staging, and production within Azure API Management to manage API deployments effectively.</li><li><strong>API Deployment </strong>— Publish APIs to specific environments using Azure API Management’s deployment options. Choose between incremental updates, full deployments, or automated deployment pipelines based on your deployment strategy.</li><li><strong>Versioning </strong>— Implement versioning strategies to manage API changes and backward compatibility effectively. Use semantic versioning or URL-based versioning to ensure smooth transitions between API versions.</li></ol><h4>Monitoring and Versioning APIs</h4><ol><li><strong>Monitoring </strong>— Monitor API usage, performance, and health in real time using Azure API Management’s analytics and monitoring capabilities. Track metrics such as request volume, latency, error rates, and traffic patterns to identify trends and anomalies.</li><li><strong>Alerting </strong>— Configure alerts and notifications to proactively monitor API health and performance. Set up alerts for threshold breaches, anomalies, or critical errors to take timely corrective actions and ensure uninterrupted service.</li><li><strong>Version Control </strong>— Manage API versions and revisions systematically within Azure API Management. Maintain a clear versioning strategy, document changes, and communicate version updates to API consumers to facilitate seamless transitions.</li></ol><h3>Import Azure Function App to Azure API Management and Manage the API</h3><p>In this demonstration, we’ll walk through the process of importing an Azure Function App into Azure API Management (APIM) and managing the API within the APIM instance. This will allow us to centrally manage and secure the Azure Function API alongside other APIs within our API Management solution.</p><h4>Step 1 — Create an Azure Function App</h4><p>First, let’s create a simple Azure Function App that we’ll later import into Azure API Management. Log in to the Azure Portal and navigate to the “Create a resource” page. In the search bar, type “Function App” and select “Function App” from the list of available services. <strong>F</strong>ill in the required details such as subscription, resource group, function app name, runtime stack, and region. Choose the appropriate pricing tier based on your requirements. Click on “Review + create” and then “Create” to provision the Azure Function App. Once the Function App is created, navigate to it and create a new Azure Function within it. You can choose a trigger type and develop the function logic based on your use case. Check out my previous blog <a href="https://medium.com/@isuruariyarathna2k00/a-comprehensive-guide-to-azure-functions-with-node-js-3ebfbd2d0341"><strong>A Comprehensive Guide to Azure Functions with Node.js</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrXniljXaq2Vwf1smZzZGQ.png" /></figure><h4>Step 2 — Import Azure Function App into Azure API Management</h4><p>Now, let’s import the Azure Function App into Azure API Management to manage it centrally. Go to the Azure Portal dashboard and select your Azure API Management instance. In the API Management instance, navigate to the “APIs” section and click on “Add a new API”. Choose “Function App” as the type of API to import. Enter the details of your Azure Function App, including the URL and authentication settings if required. Review the settings and click on “Import” to import the Azure Function App into Azure API Management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n93KnP7G2b7Px5q2kIqSjg.png" /></figure><p>Then you need to select a Function App to continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_x-bLiF4rVL7Q-vIRL43g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqGgNL6cGVZymfpt6020Fw.png" /></figure><h4>Step 3 — Manage the Imported API in Azure API Management</h4><p>Now that we have imported the Azure Function App into Azure API Management, let’s explore how we can manage and configure the API within APIM.</p><ol><li><strong>API Management Dashboard </strong>— In the Azure API Management dashboard, navigate to the imported API under the “APIs” section.</li><li><strong>API Configuration </strong>— Configure various aspects of the API, including endpoints, policies, security settings, and versioning.</li><li><strong>Apply Policies </strong>— Apply policies to the API to enforce security, rate limiting, caching, transformation, and other custom behaviors.</li><li><strong>Test API </strong>— Use the built-in testing capabilities of Azure API Management to test the Azure Function API and verify its functionality.</li><li><strong>Monitor API Usage </strong>— Monitor API usage, performance, and health using the analytics and monitoring features of Azure API Management.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K4N2rNCZrzYB_XrD_HmDbA.png" /></figure><p>Inbound and outbound policies in Azure API Management provide powerful capabilities for controlling and customizing the behavior of incoming requests and outgoing responses. By leveraging these policies effectively, you can enhance security, enforce compliance, optimize performance, and improve the overall API experience for consumers.</p><h4><strong>Inbound Policies</strong></h4><p>Inbound policies in Azure API Management are applied to incoming requests before they reach the backend service. They allow you to manipulate, transform, or control the incoming request based on predefined rules. Here are some commonly used inbound policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnfflnGoK6-OpwAdFBWawA.png" /></figure><ol><li><strong>Filter IP Addresses </strong>— Restrict access to your API by allowing or blocking requests based on the IP address of the client.</li><li><strong>Limit Call Rate </strong>— Throttle the rate of incoming requests to prevent abuse or overload of your backend service.</li><li><strong>Mock Responses </strong>— Return predefined mock responses for testing or development purposes without hitting the actual backend service.</li><li><strong>Rewrite-URI </strong>— Modify the request URI before forwarding it to the backend service, enabling URL rewriting and routing.</li><li><strong>Set Query Parameter </strong>— Add, modify, or remove query parameters from the incoming request before processing.</li><li><strong>Set Header </strong>— Manipulate HTTP headers of incoming requests, such as adding custom headers or modifying existing ones.</li><li><strong>CORS (Cross-Origin Resource Sharing) </strong>— Implement CORS policies to control access to your API from web pages hosted on different domains.</li><li><strong>Cache Lookup/Store </strong>— Cache responses from the backend service to improve performance and reduce latency by serving cached responses for identical requests.</li><li><strong>Quota-by-Key </strong>— Enforce usage quotas and rate limits based on keys associated with API consumers, allowing you to control access and prevent abuse.</li><li><strong>Validate Content </strong>— Validate the content of incoming requests against predefined schemas or patterns to ensure data integrity and security.</li><li><strong>Validate Parameter </strong>— Validate request parameters against predefined rules or constraints to enforce data validation and prevent injection attacks.</li><li><strong>Validate JWT (JSON Web Tokens) </strong>— Authenticate and authorize incoming requests by validating JWT tokens in the request headers against predefined rules and policies.</li></ol><h4><strong>Outbound Policies</strong></h4><p>Outbound policies in Azure API Management are applied to outgoing responses before they are sent back to the client. They allow you to modify, enrich, or validate the outgoing response based on predefined rules. Here are some commonly used outbound policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-S97SFrdjXvhibUIx-aog.png" /></figure><ol><li><strong>Set Header </strong>— Add, modify, or remove HTTP headers from the outgoing response before sending it back to the client.</li><li><strong>Validate Content </strong>— Validate the content of outgoing responses against predefined schemas or patterns to ensure data integrity and security.</li><li><strong>Validate Header </strong>— Validate the HTTP headers of outgoing responses against predefined rules or constraints to enforce compliance and security.</li><li><strong>Validate Status Code </strong>— Ensure that the outgoing response returns the correct HTTP status code based on predefined criteria or conditions.</li></ol><h3>Security and Access Control</h3><p>Security and access control are paramount considerations when managing APIs, ensuring that only authorized users and applications can access sensitive data and functionalities. In this section, we’ll explore the various mechanisms and best practices for implementing robust security measures in Azure API Management (APIM).</p><h4>Authentication and Authorization Mechanisms in Azure APIM</h4><p><strong><em>1. Authentication</em></strong></p><ul><li>Microsoft Entra ID (old Azure Active Directory or AAD) Integration — Leverage Entra ID for centralized authentication, enabling single sign-on (SSO) and seamless integration with Azure services.</li><li>OAuth 2.0 — Implement OAuth 2.0 authentication to enable delegated access control and token-based authorization for API consumers.</li><li>API Key — Issue API keys to authorized developers and applications, allowing them to access protected APIs securely.</li></ul><p><strong><em>2. Authorization</em></strong></p><ul><li>Role-Based Access Control (RBAC) — Define roles and permissions within Azure API Management to control access to APIs, products, and other resources based on user roles. This also can be achieved with Microsoft Entra ID.</li><li>OAuth 2.0 Scopes — Define scopes to granularly control access to API endpoints and functionalities, ensuring that only authorized users can access specific resources.</li></ul><h4>Setting up API Keys, OAuth, and Other Security Protocols</h4><p><strong><em>1. API Keys</em></strong></p><ul><li>Generate API keys for API consumers and associate them with subscriptions to control access to APIs.</li><li>Configure API key policies in Azure API Management to enforce API key validation and usage quotas.</li></ul><p><strong><em>2. OAuth</em></strong></p><ul><li>Configure OAuth 2.0 authorization servers within Azure API Management to enable token-based authentication and authorization.</li><li>Define OAuth 2.0 policies to enforce token validation, token expiration, and scope-based access control.</li></ul><p><strong><em>3. Other Security Protocols</em></strong></p><ul><li>Implement Transport Layer Security (TLS) to encrypt data in transit and protect against eavesdropping and man-in-the-middle attacks.</li><li>Enforce HTTPS-only communication to ensure data confidentiality and integrity between clients and APIs.</li><li>Implement IP filtering and whitelisting to restrict access to APIs based on IP addresses and network boundaries.</li></ul><h4>Implementing Rate Limiting and Throttling</h4><p><strong><em>1. Rate Limiting</em></strong></p><ul><li>Set rate limits on API usage to prevent abuse and ensure fair usage of resources.</li><li>Define rate limit policies in Azure API Management to restrict the number of requests per second, minute, or hour for each API consumer.</li></ul><p><strong>2. <em>Throttling</em></strong></p><ul><li>Implement throttling policies to limit the number of concurrent requests or transactions from individual API consumers.</li><li>Configure throttling thresholds and limits based on API usage patterns and resource availability.</li></ul><h3>Best Practices for Security in Azure API Management</h3><ol><li><strong>Principle of Least Privilege </strong>— Follow the principle of least privilege to grant only the minimum permissions necessary for users and applications to access APIs and resources.</li><li><strong>Data Encryption </strong>— Encrypt sensitive data at rest and in transit using industry-standard encryption algorithms and protocols to protect against data breaches and unauthorized access.</li><li><strong>Regular Auditing and Monitoring </strong>— Monitor API usage, access patterns, and security events using Azure API Management’s analytics and monitoring features. Conduct regular security audits and assessments to identify and mitigate potential vulnerabilities.</li><li><strong>Security Patching and Updates </strong>— Keep Azure API Management and underlying infrastructure up to date with the latest security patches and updates to address known vulnerabilities and security threats.</li></ol><h3>API Analytics and Monitoring</h3><p>API analytics and monitoring play a crucial role in gaining insights into API usage, performance, and health, enabling organizations to optimize their API strategy, troubleshoot issues, and make data-driven decisions. In this section, we’ll explore how Azure API Management (APIM) offers robust analytics and monitoring capabilities to track and analyze API usage effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4Rj2bDiY_burXLnK-A-hw.png" /></figure><h4>Monitoring API Usage and Performance</h4><ol><li><strong>Traffic Monitoring </strong>— Monitor incoming and outgoing API traffic to track the volume, patterns, and trends of API usage over time. Azure API Management provides comprehensive traffic monitoring features to visualize API usage metrics and identify usage spikes or anomalies.</li><li><strong>Performance Monitoring </strong>— Monitor API performance metrics such as response time, latency, and throughput to assess the health and responsiveness of APIs. Analyze performance trends and identify bottlenecks or performance issues that may impact the user experience.</li><li><strong>Error Monitoring </strong>— Monitor API error rates, status codes, and error patterns to identify and troubleshoot issues proactively. Set up alerts and notifications to be notified of critical errors or anomalies in API behavior.</li></ol><h4>Using Analytics Dashboards to Gain Insights</h4><ol><li><strong>API Analytics Dashboard </strong>— Azure API Management offers built-in analytics dashboards to visualize API usage, performance, and error metrics. Explore interactive charts, graphs, and reports to gain insights into API consumption patterns and behavior.</li><li><strong>Custom Analytics Queries </strong>— Create custom analytics queries using Azure Monitor Logs (formerly known as Log Analytics) to analyze API logs and metrics in-depth. Query and filter data based on specific criteria to uncover insights and trends relevant to your API strategy.</li><li><strong>Integration with Azure Monitor </strong>— Integrate Azure API Management with Azure Monitor to consolidate API analytics and monitoring data with other Azure services. Leverage Azure Monitor’s advanced capabilities for log aggregation, alerting, and anomaly detection to enhance API monitoring and troubleshooting.</li></ol><h4>Troubleshooting and Debugging APIs</h4><ol><li><strong>Log Analysis </strong>— Analyze API logs and traces to troubleshoot issues, debug errors, and investigate API behavior. Azure API Management provides detailed logs and diagnostics to track request/response payloads, headers, and metadata for debugging purposes.</li><li><strong>Live Metrics Stream </strong>— Use the Live Metrics Stream feature in Azure API Management to monitor API performance and health in real time. Visualize live metrics such as request rate, response time, and error count to identify issues as they occur and take immediate corrective actions.</li></ol><h3>Developer Experience</h3><p>The developer experience plays a critical role in driving API adoption and developer satisfaction, ultimately contributing to the success of your API program. In this section, we’ll explore how Azure API Management (APIM) enhances the developer experience through customizable developer portals, comprehensive documentation, and streamlined onboarding processes.</p><h4>Developer Portal Customization</h4><p>Customize the look and feel of your developer portal to align with your organization’s branding and visual identity. Customize colors, fonts, logos, and themes to create a cohesive and branded experience for developers. Organize content and navigation within the developer portal to provide intuitive access to APIs, documentation, tutorials, and support resources. Create clear and structured navigation menus and categories to help developers find relevant information quickly. Add widgets and components to the developer portal to enhance functionality and interactivity. Include features such as API search, code samples, interactive API explorers, and community forums to engage developers and facilitate collaboration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ES8e9fHUZsgUCAb2f3ERjQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9WMHR690RPvv-3ST-7bSA.png" /></figure><h4>Documentation Generation and Management</h4><ol><li><strong>API Documentation </strong>— Provide comprehensive and up-to-date documentation for your APIs within the developer portal. Include details such as API endpoints, request/response schemas, authentication mechanisms, usage examples, and code snippets to guide developers in using your APIs effectively.</li><li><strong>Interactive Documentation </strong>— Generate interactive API documentation using tools like OpenAPI (formerly Swagger) to enable developers to explore and interact with APIs directly within the developer portal. Include interactive API consoles and sandboxes for testing and experimentation.</li><li><strong>Versioning and Change Management </strong>— Manage API documentation versions and changes systematically within Azure API Management. Document API changes, deprecations, and version upgrades to keep developers informed and ensure backward compatibility.</li></ol><h4>Onboarding Developers and Managing Subscriptions</h4><ol><li><strong>Self-Service Registration </strong>— Enable self-service registration for developers to sign up and create accounts within the developer portal. Simplify the onboarding process by allowing developers to register using social login, email verification, or OAuth authentication.</li><li><strong>Subscription Management </strong>— Provide developers with self-service capabilities to manage their API subscriptions within the developer portal. Allow developers to subscribe to APIs, view usage quotas, renew subscriptions, and manage access keys and credentials.</li><li><strong>Developer Support and Assistance </strong>— offer developer support and assistance through knowledge bases, FAQs, tutorials, and community forums within the developer portal. Provide documentation feedback mechanisms and support channels to address developer queries and issues promptly.</li></ol><h4>Enhancing Developer Experience with Azure API Management</h4><ol><li><strong>Code Samples and SDKs </strong>— Provide code samples, SDKs, and client libraries to accelerate developer onboarding and integration with your APIs. Include code snippets in popular programming languages and frameworks to simplify API integration for developers.</li><li><strong>API Testing and Debugging Tools </strong>— Offer API testing and debugging tools within the developer portal to help developers validate API requests, troubleshoot issues, and test API functionality. Integrate with tools like Postman or Swagger Inspector for comprehensive API testing capabilities.</li><li><strong>Developer Analytics </strong>— Track developer engagement and usage metrics within Azure API Management to gain insights into developer behavior, preferences, and challenges. Use analytics data to optimize the developer experience and identify areas for improvement.</li></ol><h3>Integration and Extensibility</h3><p>Integration and extensibility are key aspects of Azure API Management (APIM) that enable organizations to seamlessly integrate with other Azure services and extend the functionality of their API management solution. In this section, we’ll explore how APIM facilitates integration with Azure services, custom policies, and Azure Functions for enhanced flexibility and extensibility.</p><h4>Integrating Azure APIM with Other Azure Services</h4><ol><li><strong>Azure Functions </strong>— Azure API Management integrates seamlessly with Azure Functions, allowing organizations to leverage serverless computing for custom logic, data processing, and integration with backend systems. Azure Functions can be used within APIM policies to execute custom code, implement dynamic transformations, and enrich API responses.</li><li><strong>Azure App Service </strong>— APIM can be integrated with Azure App Service to host backend APIs, web applications, and microservices. This enables organizations to manage and secure their APIs and applications in a unified environment, leveraging the scalability, reliability, and management capabilities of Azure App Service.</li><li><strong>Microsoft Entra ID (Azure Active Directory or AAD) </strong>— APIM integrates tightly with Azure Active Directory for authentication and authorization, enabling organizations to enforce identity-based access control, single sign-on (SSO), and multi-factor authentication (MFA) for their APIs. This ensures that only authorized users and applications can access protected APIs securely.</li><li><strong>Azure Logic Apps </strong>— APIM can be integrated with Azure Logic Apps to orchestrate complex workflows, automate business processes, and integrate with external services and systems. This enables organizations to extend the functionality of their APIs with event-driven workflows, data transformations, and integrations with SaaS applications.</li></ol><h4>Custom Policies and Extensions</h4><ol><li><strong>Policy Expressions </strong>— APIM allows organizations to define custom policies using policy expressions, enabling fine-grained control over API behavior and interactions. Policy expressions can be used to implement advanced routing, transformation, validation, and security logic within API pipelines.</li><li><strong>Policy Snippets </strong>— APIM provides a library of policy snippets for common scenarios such as rate limiting, caching, transformation, and authentication. Organizations can leverage these pre-built policy snippets to accelerate policy configuration and implementation, reducing development time and effort.</li><li><strong>Custom Policy Assembl </strong>— For scenarios requiring custom logic or functionality not covered by built-in policies, organizations can develop custom policy assemblies using .NET or C# extensions. This enables organizations to implement complex business rules, data transformations, and integration logic within API pipelines.</li></ol><h4>Using Azure Functions for Custom Logic</h4><ol><li><strong>Serverless Computing </strong>— Azure Functions offer serverless computing capabilities, allowing organizations to execute custom logic in response to API requests or events without managing infrastructure. This enables organizations to scale their API management solution dynamically based on demand and reduce operational overhead.</li><li><strong>Integration with APIM Policies </strong>— Azure Functions can be invoked from APIM policies to execute custom logic, perform data transformations, and integrate with external systems. This enables organizations to implement dynamic routing, content-based transformations, and conditional processing within API pipelines.</li><li><strong>Event-Driven Architecture </strong>— Azure Functions can be integrated with Azure Event Grid or Azure Service Bus to implement event-driven architectures for API management. This enables organizations to trigger functions based on API events, message queues, or external events, facilitating real-time processing and asynchronous communication.</li></ol><h3>Conclusion</h3><p>In conclusion, Azure API Management (APIM) empowers organizations to streamline API management, enhance security, and drive developer engagement effectively. Throughout this blog series, we’ve explored the diverse capabilities of Azure API Management, from API lifecycle management to security, analytics, developer experience, integration, and extensibility. By leveraging APIM, organizations can orchestrate complex API ecosystems, deliver consistent and reliable API experiences, and accelerate digital initiatives with confidence.</p><p>With APIM, organizations can design, publish, secure, monitor, and analyze APIs seamlessly, unlocking new opportunities for innovation, collaboration, and growth. By following best practices, optimizing performance, and aligning with industry standards and regulations, organizations can harness the full potential of Azure API Management to drive business outcomes, enhance customer experiences, and stay ahead in today’s competitive landscape.</p><p>As organizations continue to embrace APIs as the building blocks of modern applications and digital ecosystems, Azure API Management emerges as a strategic enabler, empowering organizations to unlock the value of their APIs and drive digital transformation at scale. Whether you’re a developer, IT professional, or business leader, Azure API Management offers a comprehensive platform to accelerate your API strategy, deliver value to stakeholders, and shape the future of digital innovation.</p><p>Thank you for joining this journey through Azure API Management. We hope this blog has equipped you with valuable insights and practical guidance for managing APIs effectively. Remember, the power of APIs lies in their ability to drive innovation and enable seamless digital experiences. As you embark on your API management endeavors, may Azure API Management serve as your trusted companion, empowering you to unlock the full potential of your APIs. For further exploration and collaboration, visit <a href="https://www.isuruariyarathna.me/"><strong>my website</strong></a><strong> </strong>and consider supporting us through <a href="https://www.buymeacoffee.com/isuruariyarathna"><strong>Buy Me a Coffee</strong></a>. Here’s to a future filled with endless possibilities through APIs!</p><p>Catch you on the flip side!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f357d0cab13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive into Micro Frontend Architecture with React.js]]></title>
            <link>https://medium.com/@isuruariyarathna2k00/a-deep-dive-into-micro-frontend-architecture-with-react-js-264ca6edca6b?source=rss-f92ef40b6108------2</link>
            <guid isPermaLink="false">https://medium.com/p/264ca6edca6b</guid>
            <category><![CDATA[implement-microfrontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-microfrontend]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[module-federation]]></category>
            <dc:creator><![CDATA[Isuru Ariyarathna]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 16:34:06 GMT</pubDate>
            <atom:updated>2024-04-11T16:34:06.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYpC9Cn7XNeVNpT_aFSsVQ.png" /></figure><h3>Introduction</h3><p>In the realm of web development, where innovation thrives on the continuous pursuit of scalability, maintainability, and agility, traditional monolithic architectures often hit roadblocks in large-scale applications. The constraints of monolithic architecture, characterized by tightly coupled components and a single, monolithic codebase, pose significant challenges as applications grow in complexity and user base. As developers grapple with the limitations of this approach, a paradigm shift towards micro frontend architecture emerges as a compelling solution.</p><p>Micro frontend architecture, inspired by the success of microservices on the backend, presents a revolutionary approach to frontend development. By breaking down monolithic frontend applications into smaller, self-contained units, known as micro frontends, this architectural style offers a pathway to overcome the constraints of monolithic architecture. Each micro frontend operates independently, focusing on a specific feature or functionality, yet seamlessly integrates with other micro frontends to form a cohesive user experience. This modular and decentralized approach not only enhances scalability and maintainability but also fosters a culture of innovation, empowering development teams to iterate rapidly and deliver value to users with greater efficiency. As we embark on this exploration of micro frontend architecture with React.js, we unravel the principles, techniques, and practical insights that underpin this transformative approach to frontend development.</p><h3>Challenges with Monolithic Architecture</h3><p>Monolithic architecture, once a cornerstone of web development, now presents a myriad of challenges in the era of modern, complex applications. While suitable for smaller projects, the inherent limitations of monolithic architecture become increasingly pronounced as applications scale and evolve. Let’s delve into some of the key challenges posed by monolithic architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRQg9A1XoFbPd8co-Uh5bg.png" /></figure><ol><li><strong>Scalability Concerns.</strong> Monolithic applications often face scalability bottlenecks due to their tightly coupled nature. As the application grows, scaling becomes a daunting task, requiring the entire monolith to be scaled up or duplicated. This approach not only increases resource consumption but also introduces challenges in managing dependencies and ensuring consistency across scaled instances.</li><li><strong>Limited Development Velocity.</strong> In monolithic architectures, developers are constrained by the monolithic codebase, which often leads to slower development velocity. Changes or updates to one part of the application may inadvertently affect other components, requiring thorough testing and coordination. This tight coupling hampers agility and innovation, making it challenging to introduce new features or iterate quickly.</li><li><strong>Complexity and Maintenance Burden.</strong> As monolithic applications grow in size and scope, they become increasingly complex and unwieldy to maintain. The interdependencies between different components make it difficult to isolate issues or debug problems, resulting in longer maintenance cycles and higher technical debt. Moreover, the monolithic codebase often lacks clear boundaries, making it challenging for teams to collaborate effectively and understand the overall system architecture.</li></ol><p>Consider a hypothetical e-commerce platform built on a monolithic architecture. As the platform gains popularity, the development team faces scalability challenges during peak traffic periods, such as holiday sales. With the monolithic architecture tightly coupling frontend and backend components, scaling becomes a cumbersome task, requiring additional resources to be allocated across the entire application stack. This not only increases infrastructure costs but also introduces complexities in maintaining consistency and ensuring seamless user experience. Moreover, when the team attempts to introduce a new checkout feature to improve user experience, they encounter difficulties due to the interconnected nature of the monolithic codebase. Changes made to the checkout module inadvertently impact other parts of the application, leading to prolonged development cycles and delayed feature rollouts. As a result, the team struggles to keep pace with evolving user demands, highlighting the limitations of monolithic architecture in fostering scalability and agility in a rapidly changing environment.</p><h3>Introduction to Micro Frontend Techniques</h3><p>As developers seek to overcome the limitations of monolithic architecture and embrace a more flexible, scalable approach to frontend development, micro-frontend techniques have emerged as a beacon of innovation. These techniques, inspired by the principles of microservices on the backend, advocate for breaking down monolithic frontend applications into smaller, self-contained units, known as micro frontends. Let’s explore some of the key micro frontend techniques that empower developers to build modular, maintainable, and scalable frontend architectures.</p><p><strong>01. Asset Store.</strong> The Asset Store approach involves decoupling frontend components and assets, such as JavaScript bundles, CSS files, and images, from the main application. By externalizing these assets to a central repository or CDN (Content Delivery Network), developers can share and reuse them across multiple applications or micro frontends. This approach promotes code reuse, simplifies maintenance, and improves performance by leveraging browser caching mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLQZDz-NKNtPSw2jfP10nQ.png" /></figure><p><strong>02. Module Federation.</strong> Module Federation, a powerful technique introduced in webpack 5, enables dynamic loading and sharing of JavaScript modules between micro frontends at runtime. This approach allows developers to build independently deployable micro frontends that can seamlessly integrate. By dynamically importing remote modules, Module Federation fosters a modular architecture where micro frontends can evolve and scale independently, without sacrificing interoperability.</p><p><strong>03. iFrames and Web Components.</strong> While not strictly considered micro frontend techniques, iFrames and Web Components offer alternative approaches to achieve frontend modularity and encapsulation. iFrames enable developers to embed isolated HTML documents within a parent document, allowing for independent rendering and execution. Web Components, on the other hand, provide a standardized way to encapsulate and reuse UI components across different web applications. While these approaches come with their own set of trade-offs and considerations, they can be valuable tools in certain scenarios.</p><h3>Deep Dive into Module Federation</h3><p>Among the pantheon of micro frontend techniques, Module Federation stands out as a game-changer, offering unprecedented flexibility and interoperability in building modular frontend architectures. Introduced in webpack 5, Module Federation reimagines frontend development by enabling dynamic loading and sharing of JavaScript modules between micro frontends at runtime. Let’s embark on a deep dive into Module Federation, unraveling its intricacies and exploring its transformative potential in modern web development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tADx4bViUt3MKjfmYkDNSg.png" /></figure><h4>Understanding Module Federation</h4><p>At its core, Module Federation enables micro frontends to dynamically import and share JavaScript modules across application boundaries. Unlike traditional static imports, Module Federation allows modules to be loaded asynchronously at runtime, facilitating seamless integration between micro frontends. This dynamic module loading capability empowers developers to build independently deployable micro frontends that can interact and collaborate, fostering a modular and composable frontend architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoZSv9tY6e5RRCn7RVttsQ.png" /></figure><h3>Key Concepts and Benefits</h3><ol><li><strong>Decentralized Architecture -</strong> Module Federation promotes a decentralized architecture, where each micro frontend is responsible for its own set of features and dependencies. This decentralization allows teams to work autonomously, independently deploying and scaling their micro frontends without impacting other parts of the application.</li><li><strong>Dynamic Module Loading -</strong> One of the hallmark features of Module Federation is its support for dynamic module loading. By dynamically importing remote modules at runtime, micro frontends can fetch and integrate functionality on-demand, reducing initial loading times and improving performance.</li><li><strong>Shared Dependencies -</strong> Module Federation facilitates the sharing of dependencies between micro frontends, minimizing duplication and optimizing resource utilization. Shared dependencies are loaded once and cached across micro frontends, ensuring consistency and reducing overhead.</li></ol><h3>Implementing Micro Frontend App with Module Federation</h3><p>Now that we’ve gained a deeper understanding of Module Federation and its transformative potential, it’s time to roll up our sleeves and dive into the practical aspects of implementing a micro frontend application using this groundbreaking technique. In this section, we’ll walk through a step-by-step guide to building a sample micro frontend application with Module Federation in React.js. From setting up the webpack configuration to dynamically importing and sharing modules between micro frontends, we’ll cover everything you need to know to get started on your micro frontend journey.</p><p>To kickstart our micro frontend project, we’ll use <strong>pnpx </strong>(part of the <strong>pnpm </strong>package manager) to scaffold a new application. Open your terminal and run the following command to install <strong>pnpm </strong>if you don’t have one.</p><pre>npm i -g pnpm</pre><p>Now you can create a Module Federation app using <strong>pnpm</strong>. Open your terminal and run the following command. It will create a boilerplate for your micro-frontend app. And give the required names, frameworks, and ports to start creating your template.</p><pre>pnpx create-mf-app</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nspDRWtHXfsmCNGQd7nCLw.png" /></figure><p>Then let&#39;s create the <strong>Header.jsx</strong> and <strong>Footer.jsx</strong> for our application. After creating the Header and the Footer we can import them to <strong>App.jsx</strong> and use it. Now let&#39;s bring our header and the footer to our Products app. Now let&#39;s start the magic. First, we need to edit the webpack.config.js file. We need to expose our Header and the Footer from our Home application. After exposing them we should restart our Home server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7NsPbZjuWmPKaiI-u1Zbw.png" /></figure><p>Now we can find our <strong>remoteEntery.js</strong> file from the Home app URL. <strong>RemoteEntery.js</strong> is the manifest of all of the modules that are exposed by the Home page application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIEok79AkhKRAEnSeVR5kw.png" /></figure><p>We should copy that URL and bring it to the products page application. Inside the <strong>webpack.config.js</strong> file, we can find the place to put our remote URLs. Past the copied URL into the remotes section and restart the server. Now you have access to all the exposed Components from the Home page application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bxk86OgCQuT6S864o4xhBA.png" /></figure><p>Now we can use the header and the footer.</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br><br>import &quot;./index.css&quot;;<br><br>import Header from &quot;home/Header&quot;;<br>import Footer from &quot;home/Footer&quot;;<br><br>const App = () =&gt; (<br>  &lt;div className=&quot;container&quot;&gt;<br>    &lt;Header /&gt;<br>    &lt;div&gt;<br>      &lt;h5&gt;Products&lt;/h5&gt;<br>      &lt;p&gt;Welcome to the Products page&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;Footer /&gt;<br>  &lt;/div&gt;<br>);<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MCMT7URq0AA8vd3DHjBZA.png" /></figure><p>Congratulations your micro-frontend app is now working perfectly. Now let&#39;s dive into some good practices that we have to use in micro-frontend architecture.</p><h3>Asynchronous Loading</h3><p>Asynchronous loading is utilized in the <strong>import()</strong> function calls within the <strong>lazy()</strong> function to enable dynamic and non-blocking loading of modules at runtime. By employing asynchronous loading, the browser can continue rendering the main application interface without waiting for the remote modules to be fetched and loaded. This approach enhances the user experience by reducing initial loading times and improving performance, particularly in scenarios where the application relies on external resources or micro frontends. As a result, users can interact with the application more quickly, while also benefiting from the modular and scalable architecture enabled by micro frontend techniques such as Module Federation.</p><pre>import React, { Suspense } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br><br>import &quot;./index.css&quot;;<br><br>const Header = React.lazy(() =&gt; import(&quot;home/Header&quot;));<br>const Footer = React.lazy(() =&gt; import(&quot;home/Footer&quot;));<br><br>const App = () =&gt; (<br>  &lt;div className=&quot;container&quot;&gt;<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;Header /&gt;<br>      &lt;div&gt;<br>        &lt;h5&gt;Products&lt;/h5&gt;<br>        &lt;p&gt;Welcome to the Products page&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;Footer /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/div&gt;<br>);<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><p>The <strong>&lt;Suspense&gt;</strong> component with the fallback prop is used to provide a loading indicator or placeholder content while asynchronous operations, such as fetching remote modules, are in progress. In the given example, when the <strong>lazy()</strong> function triggers the asynchronous loading of remote components (Header and Footer), the <strong>&lt;Suspense&gt;</strong> component ensures that the specified fallback content (in this case, a simple “Loading…” message wrapped in a &lt;div&gt;) is displayed to the user until the asynchronous loading completes. This mechanism helps maintain a smooth and cohesive user experience by giving feedback to users that content is being loaded, thereby reducing perceived latency and preventing abrupt UI changes. Once the remote components are successfully loaded, the <strong>&lt;Suspense&gt;</strong> component switches to rendering the actual content, seamlessly transitioning from the loading state to the fully rendered state of the application.</p><h3>Error Handling</h3><p>In the realm of micro frontend architecture, where independently deployable micro frontends collaborate to form a cohesive user experience, robust error-handling mechanisms are essential to ensure the resilience and reliability of the application. Enter SafeComponent — a pattern that provides a systematic approach to gracefully handling errors within micro frontend applications. Unlike traditional error-handling techniques that may result in cascading failures or abrupt UI disruptions, SafeComponent offers a proactive solution to detect and mitigate errors, thereby safeguarding the user experience. Let’s explore how SafeComponent works and its significance in the context of micro frontend architecture.</p><h4>SafeComponent</h4><p><strong>SafeComponent</strong> is a design pattern that encapsulates potentially error-prone components or modules within a protective wrapper, allowing for controlled error propagation and graceful degradation of functionality in the event of errors. By isolating error-prone code within SafeComponent boundaries, developers can prevent errors from propagating to higher-level components or disrupting the entire application. Moreover, SafeComponent provides mechanisms for error detection, logging, and recovery, enabling developers to respond to errors proactively and maintain application stability.</p><p>In React.js, <strong>SafeComponent</strong> can be implemented using error boundaries — special components that catch JavaScript errors anywhere within their child component tree and display a fallback UI instead. Let’s see how we can create a SafeComponent wrapper in React.js.</p><pre>import React, { Component } from &#39;react&#39;;<br><br>class SafeComponent extends Component {<br>    constructor(props) {<br>        super(props);<br>        this.state = { hasError: false };<br>    }<br><br>    static getDerivedStateFromError(error) {<br>        return { hasError: true };<br>    }<br><br>    componentDidCatch(error, errorInfo) {<br>        // Log error to error monitoring service<br>        console.error(&#39;Error caught by SafeComponent:&#39;, error, errorInfo);<br>        // Perform additional error handling (e.g., notify user, recover gracefully)<br>        // Optionally, set state to trigger UI updates<br>    }<br><br>    render() {<br>        if (this.state.hasError) {<br>            // Render fallback UI<br>            return &lt;div&gt;Something went wrong. Please try again later.&lt;/div&gt;;<br>        }<br><br>        // Render child components<br>        return this.props.children;<br>    }<br>}<br><br>export default SafeComponent;</pre><p>Now we can wrap our Remote components with <strong>SafeComponent</strong>.</p><pre>import React, { Suspense } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br><br>import &quot;./index.css&quot;;<br>import SafeComponent from &quot;./SafeComponent&quot;;<br><br>const Header = React.lazy(() =&gt; import(&quot;home/Header&quot;));<br>const Footer = React.lazy(() =&gt; import(&quot;home/Footer&quot;));<br><br>const App = () =&gt; (<br>  &lt;div className=&quot;container&quot;&gt;<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;SafeComponent&gt;<br>        &lt;Header /&gt;<br>      &lt;/SafeComponent&gt;<br><br>      &lt;div&gt;<br>        &lt;h5&gt;Products&lt;/h5&gt;<br>        &lt;p&gt;Welcome to the Products page&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;Footer /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/div&gt;<br>);<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><p>Now our application is safe. If there is any error in <strong>&lt;Header /&gt;</strong> Remote component our page is still working without crashing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Yi2gfXrAhw8LlBVzAbitw.png" /></figure><h3>Sharing Functions and States</h3><h4>Sharing Functions</h4><p>Sharing functions between micro frontends enables code reuse and promotes a modular approach to frontend development. Here’s an example demonstrating how to share a utility function across multiple micro frontends. Create utils.js in your Home application’s src directory. Then you have to expose it from <strong>webpack.config.js</strong>.</p><pre>export function capitalize(str) {<br>    return str.charAt(0).toUpperCase() + str.slice(1);<br>}</pre><pre>exposes: {<br>        &quot;./Header&quot;: &quot;./src/Header.jsx&quot;,<br>        &quot;./Footer&quot;: &quot;./src/Footer.jsx&quot;,<br>        &quot;./utils&quot;: &quot;./src/utils.js&quot;,<br>      },</pre><p>Now you can your Remote utilities from the Products page application.</p><pre>import React, { Suspense } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br><br>import &quot;./index.css&quot;;<br>import SafeComponent from &quot;./SafeComponent&quot;;<br><br>import { capitalize } from &#39;home/utils&#39;;<br><br>const Header = React.lazy(() =&gt; import(&quot;home/Header&quot;));<br>const Footer = React.lazy(() =&gt; import(&quot;home/Footer&quot;));<br><br>const App = () =&gt; (<br>  &lt;div className=&quot;container&quot;&gt;<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;SafeComponent&gt;<br>        &lt;Header /&gt;<br>      &lt;/SafeComponent&gt;<br>      { }<br>      &lt;div&gt;<br>        &lt;h5&gt;{<br>          capitalize(&quot;products&quot;)<br>        }&lt;/h5&gt;<br>        &lt;p&gt;Welcome to the Products page&lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;Footer /&gt;<br>    &lt;/Suspense&gt;<br>  &lt;/div&gt;<br>);<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><h4>Sharing States</h4><p>Sharing states between micro frontends facilitates <strong>synchronized</strong> data management and enables components to communicate and coordinate effectively. Here’s an example demonstrating how to share state using a shared context in React.js. Create SharedContext.js in your Home application’s src directory. Then you have to expose it from <strong>webpack.config.js</strong>.</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>const SharedContext = createContext();<br><br>export function useSharedContext() {<br>    return useContext(SharedContext);<br>}<br><br>export function SharedProvider({ children }) {<br>    const [count, setCount] = useState(0);<br><br>    const incrementCount = () =&gt; {<br>        setCount(prevCount =&gt; prevCount + 1);<br>    };<br><br>    return (<br>        &lt;SharedContext.Provider value={{ count, incrementCount }}&gt;<br>            {children}<br>        &lt;/SharedContext.Provider&gt;<br>    );<br>}</pre><pre>exposes: {<br>        &quot;./Header&quot;: &quot;./src/Header.jsx&quot;,<br>        &quot;./Footer&quot;: &quot;./src/Footer.jsx&quot;,<br>        &quot;./utils&quot;: &quot;./src/utils.js&quot;,<br>        &#39;./SharedContext&#39;: &#39;./src/SharedContext.js&#39;,<br>      },</pre><p>In this example, we define a shared context (<strong>SharedContext</strong>) and a provider component (<strong>SharedProvider</strong>) to manage a shared state (<strong>count</strong>). We also define a custom hook (<strong>useSharedContext</strong>) to access the shared state and functions.</p><p>Now you can use the counter application in your micro frontend apps. I integrated this counter to our Products page application.</p><pre>import React, { Suspense } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br><br>import &quot;./index.css&quot;;<br>import SafeComponent from &quot;./SafeComponent&quot;;<br><br>import { useSharedContext, SharedProvider } from &#39;home/SharedContext&#39;;<br>import { capitalize } from &#39;home/utils&#39;;<br><br>const Header = React.lazy(() =&gt; import(&quot;home/Header&quot;));<br>const Footer = React.lazy(() =&gt; import(&quot;home/Footer&quot;));<br><br>function SomeComponent() {<br>  const { count, incrementCount } = useSharedContext();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={incrementCount}&gt;Increment count&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;SafeComponent&gt;<br>          &lt;Header /&gt;<br>        &lt;/SafeComponent&gt;<br>        { }<br>        &lt;SharedProvider&gt;<br>          &lt;SomeComponent /&gt;<br>        &lt;/SharedProvider&gt;<br>        &lt;div&gt;<br>          &lt;h5&gt;{<br>            capitalize(&quot;products&quot;)<br>          }&lt;/h5&gt;<br>          &lt;p&gt;Welcome to the Products page&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;Footer /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><p>To use this count I created another Module Federation application called Cart page. and use the count inside the cart page.</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br><br>import &quot;./index.css&quot;;<br>import { useSharedContext, SharedProvider } from &#39;home/SharedContext&#39;;<br><br>function ComponentCount() {<br>  const { count } = useSharedContext();<br><br>  console.log(&#39;count:&#39;, count)<br><br>  return &lt;p&gt;Count: {count}&lt;/p&gt;;<br>}<br><br>const App = () =&gt; (<br>  &lt;div className=&quot;container&quot;&gt;<br>    &lt;div&gt;Name: cart&lt;/div&gt;<br>    &lt;SharedProvider&gt;<br>      &lt;ComponentCount /&gt;<br>    &lt;/SharedProvider&gt;<br>  &lt;/div&gt;<br>);<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><h3>Conclusion</h3><p>In the realm of frontend development, micro frontend architecture stands as a beacon of innovation, offering a modular, scalable, and collaborative approach to building modern web applications. By breaking down monolithic frontend applications into smaller, independently deployable micro frontends, developers can overcome the limitations of traditional architectures and unlock new possibilities for innovation and agility. Throughout this journey, we’ve explored the core principles and techniques of micro frontend architecture, from Module Federation and asynchronous loading to error handling with SafeComponent and sharing functions and states. Armed with these insights and practical examples, you’re empowered to embark on your micro frontend adventures, revolutionizing how you conceptualize, build, and evolve frontend applications in the digital age.</p><p>Explore the complete codebase and dive deeper into the demonstration of micro frontend architecture with React.js using Module Federation and other techniques in my <a href="https://github.com/Isw200/micro-frontend-architecture-react.js.git"><strong>GitHub repository</strong></a><strong>.</strong></p><p>If you found this article helpful or insightful, consider supporting my efforts by <a href="https://www.buymeacoffee.com/isuruariyarathna"><strong>buying me a coffee</strong></a>. Together, let’s shape the future of front-end development and create remarkable experiences for users around the world. Happy coding!</p><p>Catch you on the flip side!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=264ca6edca6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a CI/CD Pipeline for Your React.js App Using Azure DevOps]]></title>
            <link>https://medium.com/@isuruariyarathna2k00/create-a-ci-cd-pipeline-for-your-react-js-app-using-azure-devops-06e3fb153b10?source=rss-f92ef40b6108------2</link>
            <guid isPermaLink="false">https://medium.com/p/06e3fb153b10</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[cicd-react-app]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Isuru Ariyarathna]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 14:03:51 GMT</pubDate>
            <atom:updated>2024-04-03T14:03:51.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PblEe2nLPRsKeOxSFF3SUw.png" /></figure><p>In the dynamic landscape of web development, deploying React.js applications efficiently and reliably has become paramount. Developers have a plethora of options for deploying their React apps, ranging from traditional server hosting to modern serverless architectures. Amidst this diversity, Azure DevOps emerges as a compelling choice for streamlining deployment workflows.</p><p>Azure DevOps offers a comprehensive suite of tools and services that empower developers to manage their application lifecycle seamlessly. From version control with Azure Repos to robust CI/CD capabilities, Azure DevOps provides a unified platform for building, testing, and deploying applications with ease.</p><p>Before delving into the specifics of deploying React.js applications with Azure DevOps, let’s first understand the significance of CI/CD. Continuous Integration (CI) and Continuous Deployment (CD) represent fundamental practices in modern software development methodologies. CI involves automating the process of merging code changes into a shared repository, followed by automated builds and tests to detect integration errors early in the development cycle. CD extends this automation further by automating the deployment of validated code changes to production or staging environments, ensuring rapid and reliable delivery of software updates.</p><p>The adoption of CI/CD brings several compelling benefits to development teams. Firstly, CI/CD accelerates the software delivery process by automating time-consuming and error-prone tasks, such as manual testing and deployment. This acceleration translates into shorter release cycles, enabling organizations to respond rapidly to changing market demands and user feedback. Additionally, CI/CD enhances the overall quality of software by facilitating continuous testing and validation throughout the development lifecycle. By detecting and addressing issues early in the process, CI/CD minimizes the risk of introducing defects into production environments, thus improving the reliability and stability of deployed applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsUyKyDQ4OD0nkJe-MtLOQ.png" /></figure><p>In light of these advantages, the integration of CI/CD pipelines into the deployment workflow has become a standard practice for modern development teams. Azure DevOps, with its robust CI/CD capabilities, provides a compelling solution for automating the deployment of React.js applications, enabling developers to focus on innovation and delivering value to their users. In the following sections, we’ll explore the step-by-step process of creating a CI/CD pipeline for deploying React.js applications using Azure DevOps, leveraging its intuitive interface and powerful features to streamline the development and deployment process.</p><h3>Prerequisites</h3><h4>01. Microsoft Azure DevOps Account</h4><p>Ensure you have access to an Azure DevOps account. If you don’t have one, you can sign up for free at <a href="http://dev.azure.com/">dev.azure.com</a>. Azure DevOps provides a comprehensive set of tools for managing your application lifecycle, including version control, project management, and CI/CD pipelines. Find the resource Azure DevOps from your Azure Portal Home. Then navigate to My Azure DevOps Organizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWpDvNx1xDZs6VGEcPTxqA.png" /></figure><h4>02. React.js Application</h4><p>You should have a React.js application that you want to deploy. If you haven’t already developed your React.js application, you can create one using tools like Create React App or manually set up your React project. Make sure your React application is hosted in a Git repository, whether it’s Azure Repos, GitHub, Bitbucket, or any other Git-based repository hosting service.</p><h4>03. Azure App service.</h4><p>Azure App Service is a fully managed platform-as-a-service (PaaS) offering from Microsoft Azure that simplifies the process of building, deploying, and scaling web applications and APIs. With Azure App Service, developers can focus on writing code without worrying about managing the underlying infrastructure. It supports a wide range of programming languages and frameworks, including .NET, Node.js, Java, PHP, Python, and Ruby, making it versatile for various development scenarios.</p><p>When creating an Azure App Service, developers start by signing in to the Azure Portal and navigating to the resource creation section. From there, they select “App Service” and configure essential settings such as subscription, resource group, and app name. The app name chosen will form part of the URL used to access the application, ensuring uniqueness is maintained. Developers also specify the runtime stack, choosing the programming language and framework that best suits their application. For The runtime stack, I Select Node 18 LTS and for the OS I select Linux. After selecting the necessary fields you can create an App Service by clicking the <strong>“Review + Create”</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LB5rKPi3CihGwLsjnl1eVA.png" /></figure><p>After creating the resource you can access to your web app using the Default domain. If you want to add custom domains to your web app. You can navigate to the Custom Domains tab from the left side menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uc_mIILQxD0gCri6IDz5mA.png" /></figure><h3>Creating a Build Pipeline (CI)</h3><p><strong>Step 1:</strong> After login to your Azure DevOps Organizations you have to create a new project inside your Organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrYp13mtxL2cZz_GO2DggA.png" /></figure><p><strong>Step 2:</strong> Then you have to navigate to the Pipelines section on your project dashboard. After that click on <strong>“Create Pipeline”</strong> to create a new CI pipeline for your project.</p><p><strong>Step 3:</strong> To create the pipeline we are going to use The <strong>classic editor</strong> in Azure DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nn4IJxker35P8Mk84eqMiw.png" /></figure><p>If this is unavailable in your dashboard you have to go to the DevOps Organizations Settings and turn off the <strong>“Disable creation of classic build pipelines”</strong> and turn off the <strong>“Disable creation of classic release pipelines”</strong>. After that, you will be able to create classic pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tkmZK4su2SL7YHe9VxQ4w.png" /></figure><p><strong>Step 4:</strong> Then you need to select your Git Repository to get the source code to the pipeline. For this demonstration, I’m using a <strong>GitHub</strong> codebase. Here we have to select the correct repository and branch to create the CI pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axIIC4RF_--SwaFdcNGT2A.png" /></figure><p><strong>Step 5:</strong> Then we have to select a template to start our jobs. In this stage, I’m creating an <strong>“Empty Job”</strong> and creating the template on the empty job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ql4YoWxfnLDY5Dc1SzSzgA.png" /></figure><p>Then we have to Add tasks to Agent Job 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBUs0DKAQkpQhT8zAONXug.png" /></figure><p>Then you have to add three tasks. Two of them are <strong>“npm”</strong> tasks and the other one is the <strong>“Publish Artifact”</strong> task.</p><ol><li>npm install</li><li>npm run build — Select custom from <strong>Commands</strong> and add the command <strong>“rub build”</strong> to Command and arguments.</li><li>Publish Artifact: drop — Here add the “<strong>build”</strong> folder to the <strong>Path to publish</strong> menu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rk8nP3FNI6LAoWDA3uG1Tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YC9IVXde64NhQIrJJzOgxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIXXTJTWUbdv2EL-CQ-5mw.png" /></figure><p>After all of these configurations, you have to enable continuous integration. navigate to <strong>“Triggers”</strong> and Enable continuous integration. Select the branch that you need to trigger the CI pipeline when the code change is merged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gfsSUuL39zHM9s3tznpRmQ.png" /></figure><p>Congratulations! You have created your CI Pipeline successfully. To run the pipeline click on “Save &amp; queue”. If you end up with an error “Build failure with Parallelism” you have to submit an Azure DevOps Parallelism Request to request increased parallelism. It will take 2–3 business days to approve your request. <a href="http://aka.ms/azpipelines-parallelism-request">Fill this in to request increased parallelism.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*6iARAboWcE4mhXsT1fUNPA.png" /></figure><p>If your CI pipeline is successfully executed now we can head up to the Release Pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-Kfon3QumoEon-ZHaI_7A.png" /></figure><h3>Setting Up Continuous Deployment (CD)</h3><p>Once your build pipeline is set up, you can configure continuous deployment to automatically deploy your application. Go to the Pipelines tab and select <strong>“Releases.”</strong> Click on <strong>“New pipeline”</strong> to create a new release pipeline. Choose the <strong>“Azure App Service deployment”</strong> from the templates menu. And you can start with the artifacts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBmYHW-W6LEp9bz-mhKChw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHJcDOqWWqrVUYtgakCUmQ.png" /></figure><p><strong>Artifacts</strong> play a crucial role in the continuous deployment (CD) pipeline by encapsulating the output of the build process. These output files typically include compiled code, executables, configuration files, and other resources necessary for deploying the application. Think of artifacts as deployable units that contain everything needed to run the application in a specific environment. In the context of Azure DevOps, artifacts are generated by the build pipeline and stored in a designated artifact repository. This centralized storage ensures easy access to artifacts and facilitates their transfer to the release pipeline for deployment. By leveraging artifacts, organizations can streamline the deployment process and ensure consistency across different environments.</p><p><strong>Stages</strong>, on the other hand, represent the various phases or environments through which an application progresses during the deployment process. Each stage typically corresponds to a specific environment, such as development, staging, or production. Stages help organize and control the deployment workflow by dividing it into logical units. For example, in a typical CD pipeline, changes may be deployed to a development environment first for testing and validation by developers. Once validated, the changes may progress to a staging environment for further testing in an environment that closely resembles production. Finally, the changes are deployed to the live production environment for public use.</p><p>Each stage in the CD pipeline is configured with specific actions, conditions, and approvals. For instance, deployment tasks, such as deploying artifacts, running tests, and validating changes, are defined within each stage. Stages can be configured to run sequentially, where each stage waits for the previous one to complete successfully before starting, or in parallel, where multiple stages can run concurrently. Additionally, stages can incorporate approval gates, requiring manual approval before proceeding with deployment to certain environments. This level of control afforded by stages ensures that changes are deployed methodically and with confidence, minimizing the risk of introducing errors or disruptions to the application.</p><p><strong>Step 01:</strong> Now you have to <strong>“Add an artifact“.</strong> Your source type should be <strong>Build.</strong> Then select the Source (build pipeline). Then you can add the artifact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUOPp86UC6N-Cx2b6bU8Bw.png" /></figure><p><strong>Step 02:</strong> After that, you have to enable the “Continuous deployment trigger”. You can enable it from the artifacts and select the branch to trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4B4XtOLyuxUO1BN6ACYsOw.png" /></figure><p><strong>Step 03:</strong> Then you have to add jobs to the Stage. You can rename the stage as you want. I renamed it as Production for this demo. Then you should Authorise your Azure subscription. After Authorising the Subscription you should select the App type and your app service name. For this demonstration, I selected the App type “Web App on Linux” because the App Service that we created in the Prerequisites section used Linux as the OS. Then select the App Service that we created before. And for the startup command, we should use the below command because we are using Linux OS for our App Service.</p><pre>npx serve -s</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDkrILiQNEcWTUZYMzao5g.png" /></figure><p>Now we can create a release for our web app. Congratulations your React.Js Web App is now live on the internet. You can visit your web app using the default domain in the App Service that you created previously.</p><h3>Testing Your CI/CD Pipeline</h3><p>Testing your CI/CD pipeline is crucial to ensure that it functions as expected and reliably automates the deployment process. Once you’ve configured your pipeline, make a small change to your React.js application code, commit it to your repository, and trigger the pipeline. Monitor the pipeline’s execution in Azure DevOps to verify that it builds the application, runs tests, and deploys changes to the designated environments successfully. Pay close attention to any errors or warnings encountered during the process and troubleshoot them accordingly. Additionally, visit the deployed application in each environment to verify that the changes are reflected accurately. By thoroughly testing your CI/CD pipeline, you can identify and address any issues early, ensuring smooth and reliable deployments in the future.</p><h3>Conclusion</h3><p>In conclusion, deploying a React.js application with Azure DevOps’ CI/CD pipelines offers a streamlined and automated approach to software delivery. By leveraging Azure DevOps’ robust features, developers can seamlessly build, test, and deploy their applications with confidence. The combination of artifacts and stages allows for efficient management of deployment workflows, while Azure App Service provides a scalable and reliable platform for hosting web applications. Continuous testing and monitoring of the CI/CD pipeline ensure that deployments are consistent, reliable, and error-free. Ultimately, by adopting Azure DevOps for CI/CD, teams can accelerate their release cycles, improve software quality, and deliver value to users more efficiently. With the power of Azure DevOps, deploying React.js applications becomes a seamless and reliable process, empowering developers to focus on innovation and delivering exceptional user experiences.</p><p>Thank you for taking the time to read through this guide on deploying React.js applications with Azure DevOps CI/CD pipelines. I hope you found the information valuable for your development projects. If you found this guide helpful and would like to support my work, please consider buying me a coffee through the following link: <a href="https://www.buymeacoffee.com/isuruariyarathna">Buy Me a Coffee</a>. Your support is greatly appreciated and helps me continue creating content and sharing knowledge. Thank you for your generosity!</p><p>Catch you on the flip side!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06e3fb153b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Azure Functions with Node.js]]></title>
            <link>https://medium.com/@isuruariyarathna2k00/a-comprehensive-guide-to-azure-functions-with-node-js-3ebfbd2d0341?source=rss-f92ef40b6108------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ebfbd2d0341</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[azure-services]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Isuru Ariyarathna]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 15:25:29 GMT</pubDate>
            <atom:updated>2024-03-26T19:31:48.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlc7d40Xb9pNqMVvTLXvrg.png" /></figure><h3>Introduction</h3><p>In today’s rapidly evolving digital landscape, the demand for scalable, efficient, and cost-effective backend solutions is higher than ever. Enter Azure Functions v4, a serverless computing service provided by Microsoft Azure that allows developers to build and deploy event-driven, scalable applications without the need to manage infrastructure.</p><p>Serverless architecture represents a paradigm shift in how applications are developed, deployed, and managed. Unlike traditional server-based approaches, where developers are responsible for provisioning, scaling, and maintaining servers, serverless computing abstracts away the underlying infrastructure, allowing developers to focus solely on writing code.</p><p>Azure Functions v4 embraces the principles of serverless architecture, enabling developers to write functions — small, single-purpose pieces of code — that are triggered by various events or triggers such as HTTP requests, timers, message queues, and more. These functions are automatically scaled and managed by the Azure platform, ensuring optimal performance and resource utilization without any manual intervention.</p><p>By adopting a serverless approach with Azure Functions v4, developers can benefit from several key advantages,</p><ol><li><strong>Scalability </strong>— Azure Functions v4 automatically scales up or down based on demand, ensuring that your application can handle sudden spikes in traffic without any downtime or performance degradation.</li><li><strong>Cost-efficiency </strong>— With serverless computing, you only pay for the resources consumed by your functions while they are running. There are no upfront costs or ongoing expenses for idle infrastructure, making it a cost-effective option for both small-scale and large-scale applications.</li><li><strong>Simplicity </strong>— Serverless architecture simplifies the development and deployment process by abstracting away the complexity of managing servers and infrastructure. Developers can focus on writing code that solves business problems, rather than worrying about infrastructure concerns.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*IOWqZkf7W7LC_rzMTA8dgQ.png" /></figure><p>This guide is designed to walk you through the process of deploying a Node.js backend to Azure Functions v4, leveraging the power and simplicity of serverless architecture. From setting up your development environment to deploying and scaling your functions in the cloud, we’ll cover everything you need to know to get started with serverless computing on Azure.</p><p>By the end of this guide, you’ll have a solid understanding of how serverless architecture works and how Azure Functions v4 can help you build responsive, scalable, and cost-effective applications in the cloud.</p><h3>Prerequisites</h3><p>Before we embark on our journey to deploy a Node.js backend to Azure Functions v4, there are a few prerequisites you’ll need to have in place:</p><p><strong>1. Node.js and npm </strong>— Azure Functions support Node.js, so you’ll need to have Node.js installed on your development machine. You can download and install Node.js from the official website <a href="https://nodejs.org/en/download">Node.js Downloads</a>. npm (Node Package Manager) will also be installed alongside Node.js.</p><p><strong>2. Azure Account </strong>— To deploy your functions to Azure, you’ll need an active Azure account. If you don’t already have an account, you can sign up for a free Azure subscription at <a href="https://azure.microsoft.com/en-us/free/">Azure Free Account</a>. Please note that some Azure services may incur charges, so be sure to review the pricing details.</p><p><strong>3. Azure Functions Core Tools </strong>— Azure Functions Core Tools is a command-line interface that you’ll use to create, debug, and deploy Azure Functions locally and in the cloud. If you are a Windows user you can download Azure Functions Core Tools from <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=windows%2Cisolated-process%2Cnode-v4%2Cpython-v2%2Chttp-trigger%2Ccontainer-apps&amp;pivots=programming-language-typescript">here</a>.</p><p>If you are a MacOS user you can use Homebrew to install Azure Functions Core Tools.</p><ol><li>Install <a href="https://brew.sh/"><strong>Homebrew</strong></a>, if it’s not already installed.</li><li>Using the below commands you can install Azure Functions Core Tools using Homebrew.</li></ol><pre>brew tap azure/functions<br>brew install azure-functions-core-tools@4</pre><p>If you are upgrading on a machine that has 2.x or 3.x installed use the below commands.</p><pre>brew link --overwrite azure-functions-core-tools@4</pre><p><strong>4. Development Environment</strong> — While not strictly required, using an integrated development environment (IDE) such as Visual Studio Code can greatly enhance your development experience with Azure Functions. Visual Studio Code provides built-in support for Azure Functions development through extensions, making it easy to create, test, and deploy functions directly from your editor.</p><h3>Creating a New Azure Function App</h3><p>Azure Function Apps provide a platform for hosting and running Azure Functions. Here’s a step-by-step guide to creating a new Azure Function App.</p><p><strong>1. </strong>Open your web browser and navigate to the <a href="https://portal.azure.com/">Azure Portal</a>. Sign in with your Azure account credentials.</p><p><strong>2. </strong>Once signed in, click on the “<strong>Create a Resource”</strong> button in the upper-left corner of the Azure portal. In the search bar, type <strong>“Function App”</strong> and press Enter. Select <strong>“Function App”</strong> from the search results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_ohIo4jGspTEdJlo85iAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWd_rLxTZqPB-54SPwewUg.png" /></figure><p><strong>3. Configure the Function App Settings.</strong></p><ul><li><strong>App Name </strong>— Enter a unique name for your Function App. This name will be used as part of the URL for accessing your functions (e.g., <a href="https://yourfunctionapp.azurewebsites.net)./"><strong>https://yourfunctionapp.azurewebsites.net</strong>).</a></li><li><strong>Subscription </strong>— Choose the Azure subscription you want to use for billing purposes.</li><li><strong>Resource Group </strong>— Select an existing resource group or create a new one. Resource groups are containers that hold related Azure resources for easy management.</li><li><strong>Runtime Stack </strong>— Choose the runtime stack for your functions. Since you’re deploying a Node.js backend, select the appropriate Node.js version. For this demo project, I’m using 20 LTS because the current stable Node.js version is v20.11.1 (LTS).</li><li><strong>Region </strong>— Choose the region where you want your Function App to be hosted. Select a region closest to your target audience for optimal performance.</li><li><strong>Operating System </strong>— Choose either Windows or Linux as the operating system for hosting your Function App. For this demo, I’m using Windows OS.</li><li><strong>Plan Type </strong>— Select the hosting plan for your Function App. I recommend using the Consumption plan if you are a beginner or if you use this backend for small or medium-scale applications.</li><li><strong>Application Insights </strong>— Enable Application Insights if you want to monitor and gain insights into the performance of your functions. Navigate to the Monitoring tab and enable Application Insights then you have to select an Application Insight. If you don’t have one you can create one.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFonUfpNDZ-SG1Rtd_GfhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_CaHETN3m5DGPEyAVsL7w.png" /></figure><p>Now you can click “<strong>Review + create”</strong> to create the resource. Azure will validate your settings. Once validation passes, click the “<strong>Create”</strong> button to create the Function App. After clicking the Create button Azure will deploy your Function App. This process may take a few minutes. Once the deployment is complete, navigate to your newly created Function App in the Azure portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ybft1GUwuSI_BQJigZKHA.png" /></figure><h3>Setting Up Your Development Environment</h3><p>Visual Studio Code has a rich ecosystem of extensions that enhance its functionality for various programming languages and frameworks, including Azure Functions development. To install plugins for Azure Functions development, follow these steps. Open VS Code and navigate to the Extensions tab. Then search for <strong>“Azure”</strong> in the search bar. You can find “<strong>Azure Tools”</strong> from the search results. Install the plugin and It will install all Azure tools that you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgxqwPVI1XPI8qGmZy3YQw.png" /></figure><p>Then navigate to the <strong>Azure</strong> tab on your Visual Studio Code. Then you have to sign in to Azure. After successful sign-in, it will show all available resources under your subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZAwDYENW7jjC4sdE_LSaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BND1-4EbakJLW1BFH_7Ouw.png" /></figure><h4>Initialize a New Azure Functions Project</h4><p><strong>Method 1 </strong>— Once you have your development environment set up, you can initialize a new Azure Functions project using Azure Functions Core Tools. Open your terminal or command prompt, navigate to the directory where you want to create your project and run the following command.</p><pre>func init MyProjFolder --worker-runtime javascript --model V4</pre><p>Replace <strong>“MyProjFolder”</strong> with the name of your Function App. This command initializes a new Azure Functions project with Node.js runtime and JavaScript as the default language.</p><p>Now you can run the following command to create a new Azure Function.</p><pre>func new</pre><p>This command will prompt you to choose a template for your new function. Select the appropriate template for your function. For example, choose “HTTP trigger” to create an HTTP-triggered function.</p><p><strong>Method 2</strong> — Navigate to Azure Tools in your Visual Studio Code. Now you can create a project from the <strong>WORKSPACE</strong> tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOz71NAxAHkNoeKS4boFhw.png" /></figure><ol><li>Select your project folder then select any language you prefer. Because we use Node.js I select JavaScript.</li><li>Then select Model V4 because of December 13, 2022, function apps running on versions 2.x and 3.x of the Azure Functions runtime have reached the end of extended support.</li><li>Then select the trigger type that you need for your backend function. I select the HTTP trigger for our first demo.</li><li>Then you have to give a trigger name. After that Azure tools will create a project and a HTTP trigger for you.</li></ol><h3>Creating a Simple Node.js Function</h3><p>Once you create an HTTP function let&#39;s dive in to understand it customize it and test it!</p><h4>Understand the Example Template Code</h4><p>After selecting the template, you’ll be provided with an example template code for your function. Let’s break down the example template code.</p><pre>const { app } = require(&#39;@azure/functions&#39;);<br><br>app.http(&#39;httpTrigger1&#39;, {<br>    methods: [&#39;GET&#39;, &#39;POST&#39;],<br>    authLevel: &#39;anonymous&#39;,<br>    handler: async (request, context) =&gt; {<br>        context.log(`Http function processed request for url &quot;${request.url}&quot;`);<br><br>        const name = request.query.get(&#39;name&#39;) || await request.text() || &#39;world&#39;;<br><br>        return { body: `Hello, ${name}!` };<br>    }<br>});</pre><ul><li>First, you should import the necessary modules from the <strong>@azure/functions</strong> package.</li><li>httpTrigger1 is the Function Name.</li><li><strong>methods: [&#39;GET&#39;, &#39;POST&#39;],</strong> Specifies that the function can be invoked via HTTP GET and POST requests.</li><li><strong>authLevel: &#39;anonymous&#39;,</strong>: Sets the authorization level for the function to &quot;anonymous&quot;, allowing public access without authentication.</li><li><strong>handler: async (request, context) =&gt; { ... }</strong>: Defines the function handler, which is an asynchronous function that receives the HTTP request and context objects as parameters.</li></ul><p>Now you can test it locally by running the Azure Functions runtime.</p><pre>func start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5sZZbqp3038qU6oahkS2w.png" /></figure><p>Once the Azure Functions runtime is running locally, you can send test requests to your function using tools like cURL, Postman, or your web browser.</p><p>Send test requests to your function to verify its behavior. For example, if you’re using an HTTP-triggered function, you can send HTTP GET or POST requests to the function’s URL (e.g., <strong>http://localhost:7071/api/httpTrigger1</strong>) and observe the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOaQKVtIGwOu7cxT2TO-vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kg3V_gneQ0dJUw9JgjDbPg.png" /></figure><p>Congratulations! You’ve created a simple Node.js function within your Azure Functions project, updated the example code to customize its behavior, and tested the function locally.</p><h3>Other Available Triggers</h3><p>While the example provided earlier demonstrates an HTTP trigger, Azure Functions supports a variety of triggers, allowing you to execute your code in response to different events or stimuli. Here’s an overview of some other available triggers.</p><p><strong>1. Blob Storage Trigger</strong></p><ul><li>Blob storage triggers execute your function in response to changes in Azure Blob Storage. This trigger can be configured to execute when a new blob is created or modified, or when a blob is deleted.</li><li>Use cases: Processing new or updated files uploaded to Azure Blob Storage, generating thumbnails for images, processing log files, etc.</li></ul><p><strong>2. Queue Trigger</strong></p><ul><li>Queue triggers execute your function in response to messages added to an Azure Storage queue. This trigger enables asynchronous message processing and can scale based on the volume of messages in the queue.</li><li>Use cases: Processing background jobs, implementing task queues, triggering actions based on events, etc.</li></ul><p><strong>3. Event Grid Trigger</strong></p><ul><li>Event Grid triggers allow your function to respond to events published by Azure Event Grid. Event Grid is a fully managed event routing service that enables you to react to events from various Azure services and custom sources.</li><li>Use cases: Reacting to resource changes (e.g., VM creation, storage account deletion), implementing event-driven architectures, integrating with third-party services, etc.</li></ul><p><strong>4. Timer Trigger</strong></p><ul><li>Timer triggers execute your function on a predefined schedule or timer interval. You can configure the trigger to run at specified time intervals (e.g., every 5 minutes, hourly, daily) or according to a cron expression.</li><li>Use cases: Scheduled tasks (e.g., data backups, report generation), recurring processes, time-based notifications, etc.</li></ul><p><strong>5. Cosmos DB Trigger</strong></p><ul><li>Cosmos DB triggers execute your function in response to changes in Azure Cosmos DB data. You can configure the trigger to listen for changes in specific collections or databases and react accordingly.</li><li>Use cases: Real-time data processing, data synchronization, triggering actions based on database changes, etc.</li></ul><p><strong>6. Service Bus Trigger</strong></p><ul><li>Service Bus triggers execute your function in response to messages sent to an Azure Service Bus queue or topic. This trigger enables reliable message-based communication between different components of your application.</li><li>Use cases: Asynchronous communication between microservices, integrating with enterprise messaging systems, implementing message-based workflows, etc.</li></ul><p>These are just a few examples of the triggers supported by Azure Functions. Each trigger provides a specific way to initiate the execution of your function, allowing you to build reactive, event-driven applications in the cloud.</p><h3>Deploying Your Azure Functions to Azure</h3><p>Once you’ve developed and tested your Azure Functions locally, it’s time to deploy them to Azure for production use. Here you can configure a Continuous Deployment using Deployment Center or you can deploy using Azure Tools Plugin in Visual Studio Code.</p><p>Continuous deployment proves advantageous for projects with frequent contributions, facilitating seamless integration. Employing this approach ensures a unified code repository, fostering effective team collaboration. In Azure Functions, continuous deployment can be configured using source code repositories such as Azure Repos, GitHub, and Bitbucket. You can find a complete decimation that explains how to configure <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-continuous-deployment"><strong>continuous deployment for Azure Functions here.</strong></a></p><p>Also, you can easily deploy your backend functions using the Azure Tools plugin in Visual Studio Code. Here I explain this method because this is a beginner-friendly blog.</p><p>You can navigate to the Azure tools tab in Visual Studio Code and then navigate to “<strong>WORKSPACE”</strong> which is on the left side. Then you should click on <strong>“Deploy to Function App…”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhAmJVwnZ51W5HjTNLJDWA.png" /></figure><p>Then you have to select the correct function app that you created previously. After confirm by you it will deploy your backend to the Azure Function App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpRI3Y0W90QHml3qy4o-kw.png" /></figure><h3>Best Practices and Considerations for Azure Functions with Serverless Framework</h3><h4><strong>1. Structuring Azure Functions Projects with Serverless Framework.</strong></h4><ul><li><strong>Modularization </strong>— Organize your Azure Functions project into separate modules or folders based on functionality or feature sets. This makes it easier to manage and maintain your codebase.</li><li><strong>Separation of Concerns </strong>— Follow the principle of separation of concerns to keep your functions focused on specific tasks. Separate business logic from infrastructure-related code (e.g., deployment configuration).</li><li><strong>Use of Configuration Files </strong>— Leverage configuration files (e.g., <strong>serverless.yml</strong> for Serverless Framework) to define function settings, triggers, and dependencies. Keep these files well-organized and version-controlled for easy management.</li><li><strong>Reusable Components</strong>: Encapsulate reusable code into separate functions or modules and reuse them across multiple functions within your project.</li></ul><h4><strong>2. Security Considerations.</strong></h4><ul><li><strong>Authentication and Authorization </strong>— Implement appropriate authentication and authorization mechanisms to control access to your Azure Functions. Use Azure Active Directory, OAuth, or API keys to authenticate users and restrict access based on roles and permissions.</li><li><strong>Secure Input Validation </strong>— Validate input parameters and payloads to prevent injection attacks and ensure data integrity. Use parameterized queries for database operations and sanitize user inputs to mitigate security risks.</li><li><strong>Secure Secrets Management </strong>— Avoid hardcoding sensitive information such as API keys, passwords, or connection strings directly in your code. Instead, use Azure Key Vault or environment variables to securely manage and access secrets.</li></ul><h4><strong>3. Performance Optimization.</strong></h4><ul><li><strong>Optimized Function Code </strong>— Write efficient and optimized code to minimize execution time and resource consumption. Use asynchronous programming techniques (e.g., async/await) for I/O-bound operations and optimize CPU-intensive tasks.</li><li><strong>Caching </strong>— Utilize caching mechanisms to reduce latency and improve performance. Cache frequently accessed data in memory or use Azure Cache for Redis for distributed caching.</li><li><strong>Horizontal Scaling </strong>— Design your Azure Functions to scale horizontally to handle increased workload and traffic. Use Azure Functions Consumption Plan or Azure Kubernetes Service (AKS) for automatic scaling based on demand.</li></ul><h4><strong>4. Maintenance Considerations:</strong></h4><ul><li><strong>Version Control </strong>— Use version control systems (e.g., Git) to manage your Azure Functions codebase and track changes over time. Maintain separate branches for development, staging, and production environments to facilitate code review and deployment workflows.</li><li><strong>Continuous Integration/Continuous Deployment (CI/CD) </strong>— Implement CI/CD pipelines to automate the deployment of your Azure Functions. Use tools like Azure DevOps, GitHub Actions, or Jenkins for seamless integration and deployment.</li><li><strong>Monitoring and Logging </strong>— Monitor the health and performance of your Azure Functions using Azure Monitor or Application Insights. Enable logging and tracing to capture runtime metrics, errors, and exceptions for troubleshooting and optimization.</li><li><strong>Regular Updates and Maintenance </strong>— Keep your Azure Functions up-to-date with the latest patches, security fixes, and feature updates. Schedule regular maintenance activities such as code reviews, performance tuning, and infrastructure optimization to ensure optimal functionality and security.</li></ul><p>By following these best practices and considerations, you can effectively structure, secure, optimize, and maintain your Azure Functions projects with the Serverless Framework, ensuring reliability, scalability, and performance in production environments.</p><h3>Conclusion</h3><p>And there you have it, fellow developers! We’ve taken quite the journey through the world of Azure Functions, haven’t we? From setting up our coding playground to diving deep into triggers, security, and performance optimizations, we’ve covered it all.</p><p>But before we part ways, I’ve got something special for you. How about we put all this theory into practice? I’ve prepared a GitHub repository chock-full of backend code for Basic CRUD operations using Azure Functions. Yep, you read that right! You can now see how everything we’ve discussed comes together in real-life scenarios.</p><p>Check out the <a href="https://github.com/Isw200/azure-functions-demo"><strong>GitHub Repository</strong></a> for a complete demonstration of basic CRUD operations using Azure Functions.</p><p>If you found this guide helpful and would like to support further development efforts, you can <a href="https://www.buymeacoffee.com/isuruariyarathna">Buy Me a Coffee.</a> Your support is greatly appreciated and will help fuel future tutorials, guides, and open-source contributions.</p><p>Catch you on the flip side!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ebfbd2d0341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure your React.Js web application with Azure AD authentication using MASL Library.]]></title>
            <link>https://medium.com/@isuruariyarathna2k00/secure-your-react-js-web-application-with-azure-ad-authentication-using-masl-library-7f578c65f209?source=rss-f92ef40b6108------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f578c65f209</guid>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure-ad-authentication]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[azure-active-directory]]></category>
            <dc:creator><![CDATA[Isuru Ariyarathna]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 04:46:20 GMT</pubDate>
            <atom:updated>2024-03-24T04:51:37.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVERPBtvT7cXu1vWWn2icA.png" /></figure><h3>Introduction</h3><p>Welcome, fellow developers, to our journey into the world of securing React.js web applications using Azure AD authentication with the MSAL library.</p><p>In today’s digital landscape, where data breaches and security threats loom large, safeguarding our web applications has become paramount. Whether you’re building a personal blog, a business tool, or a social media platform, ensuring that only authorized users can access your application is crucial for protecting sensitive information and maintaining trust with your users.</p><p>This is where Azure Active Directory (AD) and the Microsoft Authentication Library (MSAL) come into play. Azure AD provides a robust and scalable identity management solution, while MSAL offers a streamlined way to integrate authentication into our React.js applications.</p><p>But why Azure AD, you might ask? Well, besides being a trusted and widely used identity provider, Azure AD offers a plethora of features that make it an attractive choice for securing our applications. From single sign-on (SSO) capabilities to multi-factor authentication (MFA) support, Azure AD equips us with the tools we need to enhance the security of our applications without reinventing the wheel.</p><p>In this blog post, we’ll dive into the nitty-gritty of setting up Azure AD authentication in our React.js applications using the MSAL library. We’ll cover everything from registering our application in Azure AD to implementing authentication flows in our React.js codebase. By the end of this journey, you’ll have the knowledge and tools you need to fortify your React.js applications against unauthorized access and keep your users’ data safe and sound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdUZ5q1qAAirQvWEFX-dZg.png" /></figure><p>So, grab your favorite beverage, fire up your code editor, and let’s embark on this adventure together as we explore the exciting world of securing React.js web applications with Azure AD authentication using MSAL. Let’s get started!</p><h3>Background Information and Requirements</h3><p>Before we dive headfirst into securing our React.js web application with Azure AD authentication using the MSAL library, let’s take a moment to understand the fundamentals and what we’ll need for this journey.</p><h4>Understanding React.js and Azure AD</h4><p><strong>React.js</strong>: React.js has become the go-to JavaScript library for building user interfaces, known for its simplicity, reusability, and performance. Whether you’re building a small personal project or a large-scale enterprise application, React.js provides the tools you need to create dynamic and interactive user experiences.</p><p><strong>Azure Active Directory (AD)</strong>: Azure AD is Microsoft’s cloud-based identity and access management service, designed to help organizations manage user identities and control access to resources. With Azure AD, you can implement authentication and authorization mechanisms to protect your applications and data from unauthorized access.</p><h4>Why Azure AD Authentication?</h4><ul><li><strong>Robust Security</strong>: Azure AD offers enterprise-grade security features, including multi-factor authentication (MFA), conditional access policies, and identity protection, to help protect your applications and data from security threats.</li><li><strong>Single Sign-On (SSO)</strong>: Azure AD enables seamless single sign-on experiences for users, allowing them to access multiple applications with a single set of credentials, improving usability and productivity.</li><li><strong>Scalability and Reliability</strong>: Azure AD is built on Microsoft’s global infrastructure, ensuring high availability, scalability, and reliability for your authentication and authorization needs.</li></ul><h4>Requirements</h4><p>Before we proceed, let’s make sure we have everything we need:</p><ol><li><strong>Azure Account</strong>: You’ll need an Azure account to create an Azure AD tenant and register your application. You can sign up for a free Azure account if you don’t have one already.</li><li><strong>React.js Application</strong>: We’ll be working with a React.js application, so make sure you have a basic understanding of React.js and have a project set up.</li><li><strong>MSAL Library</strong>: We’ll be using the Microsoft Authentication Library (MSAL) to integrate Azure AD authentication into our React.js application. You can install the MSAL library using npm or yarn.</li><li><strong>Access to Azure AD Tenant</strong>: You’ll need access to an Azure AD tenant to register your application and configure authentication settings. If you don’t have access to an Azure AD tenant, you can create one in the Azure portal.</li></ol><p>Now that we have a good understanding of the background and requirements, let’s roll up our sleeves and start securing our React.js application with Azure AD authentication using the MSAL library. Let’s do this!</p><h3>Setting Up Azure Active Directory (Azure AD)</h3><p>To kickstart our journey towards securing our React.js web application with Azure AD authentication using the MSAL library, we first need to set up Azure Active Directory (Azure AD) and register our application. This process involves creating an Azure AD tenant, registering our application, and configuring authentication settings. Let’s dive in!</p><h4>Step 1: Create an Azure Account (If you haven’t already)</h4><p>If you don’t have an Azure account yet, you can sign up for a free account <a href="https://azure.microsoft.com/en-us/free/">here</a>. Once you have an account, sign in to the <a href="https://portal.azure.com/">Azure portal</a>.</p><h4>Step 2: Create an Azure AD Tenant</h4><p><strong>Step 1: </strong>In the Azure portal, navigate to “Home” and go to create resource.</p><p><strong>Step 2:</strong> Then search for “Azure AD B2C” and select the Azure Active Director B2C from the search results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*jAW_75KXniOWVSTKYH3UBA.png" /><figcaption>Create Azure Active Directory B2C Resource.</figcaption></figure><p><strong>Step 3:</strong> Now you have to create an Azure AD tenant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwBBEPxsSsEcjQW7B4r9nw.png" /><figcaption>Create Azure Active Directory B2C tenant.</figcaption></figure><p><strong>Step 4:</strong> Once the tenant is created, navigate to “<strong>Portal settings”</strong> and switch your Directory to the created directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xe_yzQeC0YjMBOgGRgFEZg.png" /><figcaption>Switch the current directory to the created directory.</figcaption></figure><h4>Step 3: Register Your Application in Azure AD</h4><p><strong>Step 1: </strong>Now you should navigate to <a href="https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Overview">Microsoft Entra ID</a> ( Previously it was called Azure AD ).</p><p><strong>Step 2: </strong>In the Entra ID dashboard, select “App registrations” from the left-hand menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VdKj35vwXfSUi2pibgvEQ.png" /><figcaption>New App regsitertion in Mincorosoft Entre ID.</figcaption></figure><p><strong>Step 3: </strong>Click on “New registration” and provide the following details:</p><ul><li><strong>Name</strong>: Enter a name for your application.</li><li><strong>Supported account types</strong>: Choose the appropriate option based on your requirements (e.g., “Accounts in this organizational directory only” for single tenant applications). I’m choosing Multitenant for this demonstration.</li><li><strong>Redirect URI</strong>: First, you should select the platform type to enter the redirect URI. I’m selecting Single-page-application (SPA) because React.JS is a Single-page-application framework. Then specify the URI where Azure AD should redirect users after authentication (e.g., <strong>http://localhost:3000</strong> for local development).</li></ul><p><strong>Step 4: </strong>Click on “Register” to create your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUv5j-Rk1QJafoNLpd1uqg.png" /><figcaption>Register the App.</figcaption></figure><h4>Step 4: Configure Authentication Settings</h4><p><strong>Step 1:</strong> After registering your application, navigate to the “Authentication” tab.</p><p><strong>Step 2:</strong> Under “Redirect URIs,” ensure that the appropriate URIs are listed for redirecting users after authentication.</p><p><strong>Step 3:</strong> Configure any additional authentication settings as needed, such as enabling ID tokens or access tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHmnaA_dwJ__wY_UmSQRSA.png" /></figure><p><strong>Step 4:</strong> Then navigate to API permissions, select “Add permission”, and select the Microsoft Graph. Then Select the Delegated permissions and search for “User.ReadWrite.All”. Then add the permission and select “Grant admin consent to YOUR_TENENT_NAME”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iKDLz2upIyPEU4lTxwfbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oP07RLsqjDIaUBmdTgC4Cg.png" /></figure><h4>Step 5: Note Application Details</h4><p>Once you’ve registered your application and configured authentication settings, make note of the following details:</p><ul><li><strong>Application (client) ID</strong>: This is the unique identifier for your application.</li><li><strong>Directory (tenant) ID</strong>: This is the unique identifier for your Azure AD tenant.</li><li><strong>Redirect URI</strong>: The URI where Azure AD should redirect users after authentication.</li></ul><p>Keep these details handy as we’ll need them when integrating Azure AD authentication into our React.js application using the MSAL library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdVh8X8Bk0_LciuYFqAzcQ.png" /></figure><p>Congratulations! You’ve successfully set up Azure Active Directory (Azure AD) and registered your application. In the next steps, we’ll dive into integrating Azure AD authentication into our React.js application using the MSAL library.</p><h3>Integrating MSAL into React.js</h3><p>Now that we’ve set up Azure Active Directory (Azure AD) and registered our application, it’s time to integrate the Microsoft Authentication Library (MSAL) into our React.js application. MSAL will enable us to authenticate users against Azure AD and manage their access tokens securely. Let’s get started!</p><h4>Step 1: Install MSAL Library</h4><p>Open your terminal and navigate to your React.js project directory. Install the MSAL library using npm or yarn:</p><pre>npm install @azure/msal-browser</pre><p>or</p><pre>yarn add @azure/msal-browser</pre><h4>Step 2: Create MSAL Configuration</h4><p>Create a file named <strong>msalConfig.js </strong>in your project’s src directory. This file will contain the configuration settings for MSAL. Here’s an example configuration:</p><pre>import { PublicClientApplication } from &quot;@azure/msal-browser&quot;;<br><br>const MSAL_CONFIG = {<br>    auth: {<br>        clientId: &quot;YOUR_CLIENT_ID&quot;,<br>        authority: &quot;https://login.microsoftonline.com/YOUR_TENANT_NAME.onmicrosoft.com&quot;,<br>        redirectUri: &quot;http://localhost:3000&quot;,<br>    },<br>    cache: {<br>        cacheLocation: &quot;localStorage&quot;,<br>        storeAuthStateInCookie: false,<br>    },<br>};<br><br>const LOGIN_REQUEST = {<br>    scopes: [&quot;openid&quot;, &quot;offline_access&quot;]<br>};<br><br>const TOKEN_REQUEST = {<br>    scopes: [&quot;User.ReadWrite.All&quot;]<br>};<br><br>const GRAPH_CONFIG = {<br>    graphUsersEndpoint: &quot;https://graph.microsoft.com/v1.0/users&quot;<br>};<br><br>const PUBLIC_CLIENT_APPLICATION = new PublicClientApplication(MSAL_CONFIG);<br>async function initializeMsal() {<br>    await PUBLIC_CLIENT_APPLICATION.initialize();<br>}<br>initializeMsal();<br><br>export {<br>    MSAL_CONFIG,<br>    LOGIN_REQUEST,<br>    TOKEN_REQUEST,<br>    GRAPH_CONFIG,<br>    PUBLIC_CLIENT_APPLICATION<br>};</pre><p>Replace <strong>‘YOUR_CLIENT_ID’ </strong>with your Azure AD application’s client ID and ‘<strong>YOUR_TENANT_NAME’</strong> with your Azure AD tenant ID.</p><h4>Step 3: Authenticate Users &amp; Get Access Token</h4><p>Now, let’s implement user authentication in our React.js application. Create a component or a utility file where you’ll handle authentication logic. Here’s a basic example of sign-in and sign-out functions:</p><pre>const handleSignIn = async () =&gt; {<br>    const loginResponse = await PUBLIC_CLIENT_APPLICATION.loginPopup(LOGIN_REQUEST);<br>    if (loginResponse.account) {<br>      PUBLIC_CLIENT_APPLICATION.setActiveAccount(loginResponse.account);<br>    }<br>    const tokenResponse = await PUBLIC_CLIENT_APPLICATION.acquireTokenSilent(TOKEN_REQUEST);<br>    setToken(tokenResponse.accessToken);<br>  }<br><br>const handleSignOut = async () =&gt; {<br>    if (!interactionInProgress) {<br>      setInteractionInProgress(true);<br>      PUBLIC_CLIENT_APPLICATION.logout();<br>      setToken(null);<br>      setInteractionInProgress(false);<br>    }<br>  }</pre><p>And also you can create a function to refresh the Access token. Here’s a basic example of the refresh access token function.</p><pre>const handleRefreshToken = async () =&gt; {<br>    const tokenResponse = await PUBLIC_CLIENT_APPLICATION.acquireTokenSilent(TOKEN_REQUEST);<br>    setToken(tokenResponse.accessToken);<br>  }</pre><p>You’ve successfully integrated the Microsoft Authentication Library (MSAL) into your React.js application! Users can now sign in using their Azure AD credentials, and your application can securely obtain access tokens for calling protected APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaMQ-V8BRnfaadsVjamFhg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5l7Lynd6JK-aGXEjASTc2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFmVuxfSM9K1rPB3Fk6O3Q.png" /></figure><h3>Conclusion</h3><p>Congratulations on completing the integration of the Microsoft Authentication Library (MSAL) into your React.js application! By leveraging Azure Active Directory (Azure AD) for authentication, you’ve taken a significant step towards enhancing the security of your web application.</p><p>Throughout this journey, we’ve covered the following key points:</p><ol><li><strong>Setting Up Azure AD</strong>: We created an Azure AD tenant, registered our application, and configured authentication settings to enable secure authentication with Azure AD.</li><li><strong>Integrating MSAL into React.js</strong>: We installed the MSAL library, initialized the MSAL instance, and implemented authentication logic to enable users to sign in and acquire access tokens securely.</li></ol><p>By following these steps, you’ve empowered your React.js application with robust authentication capabilities, ensuring that only authorized users can access your application’s resources.</p><h3>Demo Project and Support</h3><p>To see a complete demonstration of the integration of MSAL into a React.js application, you can check out the <a href="https://github.com/Isw200/React-AzureAD-MASL-authentication-demo"><strong>Demo Project Repository</strong></a><strong>.</strong></p><p>Feel free to explore the code, run the application locally, and experiment with different authentication scenarios.</p><p>If you found this guide helpful and would like to support further development efforts, you can <a href="https://www.buymeacoffee.com/isuruariyarathna">Buy Me a Coffee.</a> Your support is greatly appreciated and will help fuel future tutorials, guides, and open-source contributions.</p><p>Thank you for joining us on this journey to secure our React.js web application with Azure AD authentication using the MSAL library. We hope you found this guide informative and valuable. Happy coding, and may your applications remain safe and secure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f578c65f209" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>