<?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 Nawaz Pasha on Medium]]></title>
        <description><![CDATA[Stories by Nawaz Pasha on Medium]]></description>
        <link>https://medium.com/@nawaz-np?source=rss-94b65675c7d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nH3wDr6-sLSJlmtV.jpg</url>
            <title>Stories by Nawaz Pasha on Medium</title>
            <link>https://medium.com/@nawaz-np?source=rss-94b65675c7d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:21:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nawaz-np/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[Seamless Context Management in NodeJs apps with AsyncLocalStorage]]></title>
            <link>https://medium.com/@nawaz-np/seamless-context-management-in-nodejs-apps-with-asynclocalstorage-69ede3e524a9?source=rss-94b65675c7d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/69ede3e524a9</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[context-management]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Nawaz Pasha]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 17:23:13 GMT</pubDate>
            <atom:updated>2024-04-18T06:30:33.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNNB_SrHESt07GtI" /><figcaption>Context Management</figcaption></figure><h3>Introduction:</h3><p>Node.js is known for its non-blocking, event-driven architecture that makes it an excellent choice for building scalable and high-performance applications. However, as applications grow in complexity, managing context across asynchronous operations can become a challenge. Enter AsyncLocalStorage, a powerful feature introduced in Node.js to simplify the handling of contextual information throughout the lifecycle of a request. In this blog post, we will explore how to effectively use AsyncLocalStorage to set up and manage the request context in your Node.js applications.</p><h3>Understanding the Need for Request Context:</h3><p>In a typical web application, a single HTTP request often triggers multiple asynchronous operations, such as database queries, HTTP calls, or file system operations. Maintaining contextual information, such as user authentication details or request-specific data, across these asynchronous operations is crucial. AsyncLocalStorage provides a solution to this problem by allowing you to store and retrieve data that is local to the execution of a function.</p><h3>Setting Up AsyncLocalStorage:</h3><p>Before diving into practical examples, let’s set up AsyncLocalStorage in your Node.js application. The async_hooks module is used to create and manage asynchronous resources, and AsyncLocalStorage is built on top of it. Here&#39;s a simple setup:</p><pre>import { AsyncLocalStorage } from &#39;async_hooks&#39;;<br><br>export const asyncLocalStorage = new AsyncLocalStorage();</pre><p>Now, <strong>you have an instance of AsyncLocalStorage that can be used to store and retrieve data within the context of an asynchronous operation</strong>.</p><p>Using AsyncLocalStorage for Request Context:</p><p>Let’s consider a scenario where you want to track user information throughout the processing of an HTTP request. You can use AsyncLocalStorage to set and get user details seamlessly.</p><pre>const http = require(&#39;http&#39;);<br>const server = http.createServer((req, res) =&gt; {<br>  // Assume user information is obtained from the request headers<br>  const user = extractUserFromRequest(req);<br>  // Set the user information in the AsyncLocalStorage context<br>  asyncLocalStorage.run(user, () =&gt; {<br>    // Now, any asynchronous operation within this callback can access the user information<br>    processRequest();<br>  });<br>  res.end(&#39;Request processed successfully&#39;);<br>});<br>function processRequest() {<br>  // Asynchronously retrieve user information from the context<br>  const user = asyncLocalStorage.getStore();<br>  // Perform operations using the user information<br>  console.log(`Processing request for user: ${user.username}`);<br>}<br>function extractUserFromRequest(req) {<br>  // Logic to extract user information from the request headers<br>  // ...<br>  // For example purposes, let&#39;s assume a user object is created<br>  return { username: &#39;john_doe&#39; };<br>}<br>server.listen(3000, () =&gt; {<br>  console.log(&#39;Server listening on port 3000&#39;);<br>});</pre><p>In this example, the asyncLocalStorage.run() method is used to set the user information within the context of the HTTP request. The asyncLocalStorage.getStore() method is then used to retrieve the user information asynchronously within the processRequest function.</p><h3>Benefits of Using AsyncLocalStorage:</h3><ol><li>Simplicity: AsyncLocalStorage provides a straightforward way to manage context without resorting to complex solutions.</li><li>Isolation: Each request gets its own context, preventing interference between different requests.</li><li>Accessibility: The stored context is easily accessible within the callback functions, making it seamless to pass data across asynchronous operations.</li></ol><h3>Conclusion:</h3><p>AsyncLocalStorage in Node.js offers a powerful and elegant solution for managing context in asynchronous operations. By incorporating it into your application, you can simplify the handling of request-specific data and enhance the maintainability and readability of your code. As you continue to explore and leverage the capabilities of Node.js, AsyncLocalStorage becomes an indispensable tool for building scalable and efficient applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69ede3e524a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>