<?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 Abubakar Balogun on Medium]]></title>
        <description><![CDATA[Stories by Abubakar Balogun on Medium]]></description>
        <link>https://medium.com/@abubalogun?source=rss-703e978f4870------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*44_u3TuC513rQU4lo1jMxw.jpeg</url>
            <title>Stories by Abubakar Balogun on Medium</title>
            <link>https://medium.com/@abubalogun?source=rss-703e978f4870------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:53:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abubalogun/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[Exploring IndexedDB: An Underrated Browser API]]></title>
            <link>https://abubalogun.medium.com/exploring-indexeddb-an-underrated-browser-api-5deac2bf913b?source=rss-703e978f4870------2</link>
            <guid isPermaLink="false">https://medium.com/p/5deac2bf913b</guid>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[browser-api]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Abubakar Balogun]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 20:31:04 GMT</pubDate>
            <atom:updated>2025-08-16T20:31:04.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpfyRfBA4xNE0B5C76RDDw.jpeg" /></figure><p>IndexedDB is one of those cool browser APIs that doesn’t receive much spotlight in web development discussions, and there is a valid reason for that; its use cases are not frequent, but it is incredibly indispensable when the need arises. Many frontend developers might go years without encountering it, or perhaps they have seen the name but had no idea what it meant for. However, with the growing importance of Progressive Web Applications (PWA) and the shift toward offline-mode web applications, IndexedDB is becoming increasingly relevant.</p><p>Modern web applications are expected to handle huge amounts of data seamlessly and sometimes must work entirely or partially offline. Traditional client-side storage, such as localStorage, can reach its maximum capacity quickly. Also, with the phasing out of support for WebSQL in major browsers, IndexedDB emerged as one of the reliable and convenient ways to cache data on the client-side.</p><p>If you are curious about IndexedDB, consider this article your introductory guide to this browser API. We will explore what it is, how to use it, and why companies like Google, Figma, Discord, and others rely heavily on it to power web applications.</p><h3>What is IndexedDB?</h3><p>IndexedDB is an asynchronous, transactional-based client-side database system designed specifically for storing and retrieving large amounts of structured or unstructured data. It is available across major browsers. Unlike localStorage which is limited to storing key-value strings and has a capacity of just 5MB, IndexedDB can store a large amount of data and is flexible in terms of data types. It supports Blobs, ArrayBuffers, dates, binary data, booleans, JavaScript objects, Maps, Sets, etc.</p><h3>Key features of IndexedDB</h3><ul><li><strong>Large storage capacity</strong>: IndexedDB can store up to gigabytes of data</li><li><strong>Transactional database system</strong>: All operations in IndexedDB are executed within transactions, which ensures data integrity even if some operations fail during the process.</li><li><strong>Asynchronous API</strong>: It keeps the application responsive as operations don’t block the main thread.</li><li><strong>Indexed data</strong>: As the name suggests, you can create indexes on your data for faster searching and querying, like you would in a traditional database.</li><li><strong>Structured storage</strong>: You can organise data in object stores, similar to tables in traditional databases.</li></ul><h3>When Should You Use IndexedDB?</h3><p>IndexedDB can be extremely useful in scenarios such as:</p><ul><li><strong>Offline-first applications</strong>: When a web application needs to work without an internet connection.</li><li><strong>Performance-sensitive applications</strong>: When you need to store and retrieve large amounts of data without network latency.</li><li><strong>Caching large datasets</strong>: When you need to store API responses locally for quick access.</li><li><strong>Storing complex data structures</strong>: When simple key-value storage is not sufficient for your needs.</li><li><strong>Handling binary data</strong>: When you need to store files, images, or other binary blobs client-side.</li></ul><h3>When Should You Not Use IndexedDB?</h3><p>IndexedDB has specific use cases and is not always the right choice for every situation. For many simple web applications, it can be overkill and add unnecessary complexity.</p><ul><li>If you’re only storing small amounts of data like user preferences or settings, localStorage or sessionStorage are simpler and more appropriate. IndexedDB’s setup overhead and transaction-based operations become burdensome when you just need to save a few key-value pairs.</li><li>Never store sensitive information like passwords, API keys, or personal data in IndexedDB. It’s client-side storage, meaning users can access and modify the data through browser developer tools. Any sensitive data should stay on the server or use proper encryption if it must be stored locally.</li><li>If your application doesn’t need offline functionality, you might not need IndexedDB at all. Most web apps can fetch data from the server as needed. IndexedDB is only ideal when you need to cache large amounts of structured data for offline access, but if your app always requires an internet connection, server-side storage is often simpler.</li></ul><h3>Basic Concepts of IndexedDB</h3><p>Before diving into code, let’s understand the key concepts that make IndexedDB work.</p><ul><li><strong>Database</strong>: The top-level container for your data. Each website can have multiple named databases, like having separate databases for user data, application settings, and cached content.</li><li><strong>Object Store</strong>: works like a table in a relational database. It’s where you actually store your data objects. Each object store holds records of a similar type, like all your user records or all your product records.</li><li><strong>Index</strong>: Lets you search for records using properties other than the primary key. Without indexes, you’d have to scan through every record to find what you need, which gets slow with large datasets.</li><li><strong>Transaction</strong>: Groups multiple operations together so they either all succeed or all fail. This prevents your data from getting into an inconsistent state if something goes wrong partway through an operation.</li><li><strong>Key Range</strong>: It defines a continuous range of values to filter your search results, like finding all users between ages 25 and 35.</li><li><strong>Versioning</strong>: Handles database schema changes. When you need to add new object stores or indexes, you increment the version number, which triggers the upgrade process.</li></ul><h3>Getting Started with IndexedDB</h3><p>First, create an index.html file in your code editor.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;My IndexedDB App&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;script&gt;<br>        <br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Open the file in your browser. All our IndexedDB code will go inside the script tags. To view the database as we build it, open the browser’s developer tools. In Chrome, right-click on the page, select “Inspect,” then click on the “Application” tab. You’ll see IndexedDB listed in the left sidebar, where you can browse your databases and object stores as you create them. In Firefox, the process is similar but the database viewer is under the “Storage” tab in developer tools. This setup gives us a simple testing environment and lets us see our database operations in real-time as we work through the examples. Now that we have the index.html file running, let’s begin by creating/opening a database</p><h3>Opening a Database</h3><pre>function openDatabase() {<br>  return new Promise((resolve, reject) =&gt; {<br>    const request = indexedDB.open(&quot;MyAppDatabase&quot;, 1);<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error opening database: &quot; + event.target.error);<br>    };<br>    <br>    request.onsuccess = (event) =&gt; {<br>      const db = event.target.result;<br>      resolve(db);<br>    };<br>    <br>    request.onupgradeneeded = (event) =&gt; {<br>      const db = event.target.result;<br>      <br>      if (!db.objectStoreNames.contains(&quot;users&quot;)) {<br>        const usersStore = db.createObjectStore(&quot;users&quot;, { keyPath: &quot;id&quot;, autoIncrement: true });<br>        <br>        usersStore.createIndex(&quot;name&quot;, &quot;name&quot;, { unique: false });<br>        usersStore.createIndex(&quot;email&quot;, &quot;email&quot;, { unique: true });<br>      }<br>    };<br>  });<br>}</pre><p>The openDatabase function opens an IndexedDB database called &quot;MyAppDatabase&quot;. If the database doesn&#39;t exist, it creates one. The function handles three different scenarios that can happen during this process. When something goes wrong during the database opening, the onerror event catches the problem and returns an error message. If the database opens successfully, the onsuccess event retrieves the database instance and returns it to whoever called the function.</p><p>The most interesting part happens with onupgradeneeded, which runs when the database is created for the first time or needs updating. This event sets up a &quot;users&quot; object store, which works like a table in a regular database. The object store uses an auto-incrementing id as the primary key, meaning each new user gets a unique number automatically. The function also creates two indexes on the name and email fields to make searches faster later. The email index is marked as unique, so no two users can have the same email address. Since the function returns a Promise, we can use .then() or await to get the database once it&#39;s ready to use. If you open the browser, you will see the database created. Now let’s move on to adding add data to users store.</p><h3>Adding Data</h3><pre>async function addUser(user) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readwrite&quot;);<br>    <br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    <br>    const request = usersStore.add(user);<br>    <br>    request.onsuccess = () =&gt; {<br>      resolve(request.result);<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error adding user: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}<br><br>// Usage<br>addUser({ name: &quot;John Doe&quot;, email: &quot;john@example.com&quot;, age: 30 })<br>  .then(userId =&gt; console.log(&quot;Added user with ID:&quot;, userId))<br>  .catch(error =&gt; console.error(error));</pre><p>The addUser demonstrates how to add data to the user store. This function adds a new user to the database. It opens the database, creates a transaction with write permissions on the “users” store, and calls add() with the user data. If successful, it returns the new user&#39;s auto-generated ID. If something fails, it returns an error. The transaction automatically closes the database when finished.</p><h3>Retrieving Data</h3><pre>async function getUserById(id) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readonly&quot;);<br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    <br>    const request = usersStore.get(id);<br>    <br>    request.onsuccess = () =&gt; {<br>      resolve(request.result);<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error retrieving user: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}<br><br><br>// Usage<br>getUserById(1)<br>  .then(user =&gt; {<br>    if (user) {<br>      console.log(&quot;Found user:&quot;, user);<br>    } else {<br>      console.log(&quot;User not found&quot;);<br>    }<br>  })<br>  .catch(error =&gt; console.error(error));</pre><p>The usage example shows how to check if a user was found. If the result exists, we get the user data. If not, the user wasn’t in the database. The database closes automatically when the operation finishes.</p><h3>Querying with Indexes</h3><p>One of the powerful features of IndexedDB is the ability to efficiently query data using indexes. Because we already created indexes on name and email, we can use them to find users by email instead of their ID.</p><pre>async function getUserByEmail(email) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readonly&quot;);<br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    const emailIndex = usersStore.index(&quot;email&quot;);<br>    <br>    const request = emailIndex.get(email);<br>    <br>    request.onsuccess = () =&gt; {<br>      resolve(request.result);<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error retrieving user by email: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}<br><br><br>// Usage<br>getUserByEmail(&quot;john@example.com&quot;)<br>  .then(user =&gt; {<br>    if (user) {<br>      console.log(&quot;Found user by email:&quot;, user);<br>    } else {<br>      console.log(&quot;User not found&quot;);<br>    }<br>  })<br>  .catch(error =&gt; console.error(error));</pre><p>This function works similarly to getting a user by ID, but instead of searching the main object store, it uses the “email” index we created earlier. The usersStore.index(&quot;email&quot;) gets access to that index, then the get method searches through it to find a user with the matching email address.</p><p>Since we made the email index unique when we set up the database, this search will return either one user object or undefined if no user has that email. The rest works the same as the ID lookup - the database closes when the operation finishes.</p><h3>Updating Data</h3><pre>async function updateUser(user) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readwrite&quot;);<br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    <br>    const request = usersStore.put(user);<br>    <br>    request.onsuccess = () =&gt; {<br>      resolve(request.result);<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error updating user: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}<br><br><br>// Usage<br>updateUser({ id: 1, name: &quot;John Doe&quot;, email: &quot;john@example.com&quot;, age: 31 })<br>  .then(() =&gt; console.log(&quot;User updated&quot;))<br>  .catch(error =&gt; console.error(error));</pre><p>To update data in the user store, we use the put method. The put method updates an existing record if the ID matches, or creates a new one if no record with that ID exists.</p><p>The key difference from add is that put overwrites the entire record. If you only want to change the age from 30 to 31, you still need to provide the complete user object with all fields. Missing properties will be removed from the stored record.</p><h3>Deleting Data</h3><pre>async function deleteUser(id) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readwrite&quot;);<br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    <br>    const request = usersStore.delete(id);<br>    <br>    request.onsuccess = () =&gt; {<br>      resolve();<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error deleting user: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}<br><br>// Usage<br>deleteUser(1)<br>  .then(() =&gt; console.log(&quot;User deleted&quot;))<br>  .catch(error =&gt; console.error(error));</pre><p>To delete a user, we call the delete method with the user&#39;s ID. The operation removes the entire record from the store permanently. Unlike some databases, IndexedDB doesn&#39;t warn you if the ID doesn&#39;t exist. The delete operation succeeds whether or not there was actually a record to delete. If you need to know whether something was actually removed, you&#39;d have to check for the record&#39;s existence first.</p><h3>Advanced IndexedDB Features</h3><h3>Working with Cursors</h3><p>Cursors let you iterate through all records in an object store, similar to a for-loop but designed for IndexedDB’s asynchronous nature. The openCursor() method starts the iteration. Each time onsuccess fires, you get access to one record through cursor.value. The cursor.continue() call moves to the next record, which triggers another onsuccess event. When there are no more records, the cursor becomes null to signal it has reached the end of the loop.</p><pre>async function getAllUsers() {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readonly&quot;);<br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    const users = [];<br>    <br>    const request = usersStore.openCursor();<br>    <br>    request.onsuccess = (event) =&gt; {<br>      const cursor = event.target.result;<br>      <br>      if (cursor) {<br>        users.push(cursor.value);<br>        <br>        cursor.continue();<br>      } else {<br>        resolve(users);<br>      }<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error retrieving users: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}</pre><h3>Using Key Ranges</h3><p>Key ranges allow us to filter data based on specific value ranges instead of iterating through everything.</p><pre>async function getUsersByAgeRange(minAge, maxAge) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const transaction = db.transaction([&quot;users&quot;], &quot;readonly&quot;);<br>    const usersStore = transaction.objectStore(&quot;users&quot;);<br>    const ageIndex = usersStore.index(&quot;age&quot;);<br>    const users = [];<br>    <br>    const ageRange = IDBKeyRange.bound(minAge, maxAge);<br>    <br>    const request = ageIndex.openCursor(ageRange);<br>    <br>    request.onsuccess = (event) =&gt; {<br>      const cursor = event.target.result;<br>      <br>      if (cursor) {<br>        users.push(cursor.value);<br>        cursor.continue();<br>      } else {<br>        resolve(users);<br>      }<br>    };<br>    <br>    request.onerror = (event) =&gt; {<br>      reject(&quot;Error retrieving users by age: &quot; + event.target.error);<br>    };<br>    <br>    transaction.oncomplete = () =&gt; {<br>      db.close();<br>    };<br>  });<br>}<br><br>// Usage<br>getUsersByAgeRange(25, 35)<br>  .then(users =&gt; console.log(&quot;Users aged 25-35:&quot;, users))<br>  .catch(error =&gt; console.error(error));</pre><p>The IDBKeyRange.bound(minAge, maxAge) creates a range that includes all values between the minimum and maximum ages. When you pass this range to openCursor(), the cursor only visits records that fall within those boundaries.</p><p>We’re using the “age” index here, which means the cursor moves through users sorted by age and only stops at those within our specified range. The rest works like a regular cursor — collect matching users and return them when done.</p><p>IndexedDB provides other key range methods like only() for exact matches, lowerBound() for everything above a value, and upperBound() for everything below a value. You can also control whether the boundaries are inclusive or exclusive.</p><h3>Storing Binary Data</h3><p>IndexedDB can store binary data like images:</p><pre>async function storeImage(imageFile) {<br>  const db = await openDatabase();<br>  <br>  return new Promise((resolve, reject) =&gt; {<br>    const reader = new FileReader();<br>    <br>    reader.onload = async (event) =&gt; {<br>      try {<br>        const transaction = db.transaction([&quot;images&quot;], &quot;readwrite&quot;);<br>        const imagesStore = transaction.objectStore(&quot;images&quot;);<br>        <br>        const imageObject = {<br>          name: imageFile.name,<br>          type: imageFile.type,<br>          size: imageFile.size,<br>          lastModified: imageFile.lastModified,<br>          data: event.target.result <br>        };<br>        <br>        const request = imagesStore.add(imageObject);<br>        <br>        request.onsuccess = () =&gt; {<br>          resolve(request.result);<br>        };<br>        <br>        request.onerror = (event) =&gt; {<br>          reject(&quot;Error storing image: &quot; + event.target.error);<br>        };<br>        <br>        transaction.oncomplete = () =&gt; {<br>          db.close();<br>        };<br>      } catch (error) {<br>        reject(&quot;Error in transaction: &quot; + error);<br>      }<br>    };<br>    <br>    reader.onerror = () =&gt; {<br>      reject(&quot;Error reading file&quot;);<br>    };<br>    <br>    reader.readAsArrayBuffer(imageFile);<br>  });<br>}<br><br>// Usage with a file input<br>document.getElementById(&#39;imageInput&#39;).addEventListener(&#39;change&#39;, (event) =&gt; {<br>  const file = event.target.files[0];<br>  if (file) {<br>    storeImage(file)<br>      .then(id =&gt; console.log(&quot;Image stored with ID:&quot;, id))<br>      .catch(error =&gt; console.error(error));<br>  }<br>});</pre><h3>IndexedDB Alternatives</h3><p>IndexedDB’s verbose API and complex transaction handling can be cumbersome for everyday development. Several libraries wrap IndexedDB to provide cleaner, more intuitive interfaces while maintaining the same underlying power.</p><ul><li><a href="https://dexie.org/"><strong>Dexie</strong></a> is probably the most popular IndexedDB wrapper. It provides a promise-based API that eliminates much of the boilerplate code you’ve seen throughout these examples. Instead of manually managing transactions and handling multiple event callbacks, Dexie lets you work with your data using familiar async/await patterns.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase"><strong>IDB</strong></a> is a lightweight wrapper created by the Chrome team. It focuses on providing a minimal Promise-based interface over IndexedDB without adding much abstraction. If you want IndexedDB’s full power but with cleaner syntax, IDB strikes a good balance.</li></ul><p>These libraries don’t replace IndexedDB , they make it more easy to work with. Under the hood, they’re still using the same concepts of transactions, object stores, and cursors that you’ve learned here. Understanding the underlying IndexedDB concepts helps you use these wrappers more effectively and debug issues when they arise.</p><h3>Putting Everything Together</h3><p>Let’s put everything together by building a simple note-taking application that works offline:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2F9ux4e0by%2F&amp;type=text%2Fhtml&amp;schema=jsfiddle&amp;display_name=jsFiddle&amp;src=https%3A%2F%2Fjsfiddle.net%2F9ux4e0by%2Fembedded%2F" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a008fa628a4218d52d78e76d656a010/href">https://medium.com/media/1a008fa628a4218d52d78e76d656a010/href</a></iframe><h3>Wrapping Up</h3><p>IndexedDB may not be the most glamorous browser API, but its flexibility makes it an indispensable tool for modern web applications that require reliable client-side storage. As the web continues to evolve, with progressive web apps becoming more prevalent and user expectations for performance and reliability increasing, IndexedDB’s importance will only grow. Understanding how to use IndexedDB becomes incredibly valuable when building applications that must be both resilient and responsive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5deac2bf913b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Optimization Techniques for Node.js Applications]]></title>
            <link>https://abubalogun.medium.com/performance-optimization-techniques-for-node-js-applications-4cb009430634?source=rss-703e978f4870------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb009430634</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abubakar Balogun]]></dc:creator>
            <pubDate>Mon, 13 May 2024 22:11:47 GMT</pubDate>
            <atom:updated>2024-06-07T13:40:23.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHAlaH_3hiDG_vMkd75rSQ.jpeg" /></figure><p>Performance matters when building a web application. The goal is to build fast and reliable applications that provide a great user experience. Responsive apps keep users engaged and improve the retention rate. Conversely, sluggish applications frustrate users and lead to abandonment.</p><p>If you are building a backend service, especially with Node.js, performance cannot be an afterthought. Node.js may have a reputation for being fast, but this doesn’t necessarily guarantee that your application will operate at an optimal level. To maximize the potential of Node.js, you need to take deliberate action.</p><p>In this article, we will go through various techniques and best practices to improve the performance of Node.js applications.</p><h3>Why Performance Optimization Matters?</h3><p>Performance optimization is not always about improving the speed of an application, although it is certainly a part of it. It is also about conserving precious resources like memory, CPU, and bandwidth. A poorly optimized app wastes a lot of resources and incurs costs. With limited hardware resources, optimization lets you get the most out of what you have. You avoid unnecessary upgrades and ensure every penny of your investment counts.</p><p>Scalability is also a factor that can’t be ignored. A properly optimized app can easily handle concurrent users without experiencing strain. This is especially important in business, as a performant application helps maintain an edge over competitors.</p><p>Given Node’s non-blocking nature, optimization becomes even more important. Node is incredibly good at parallel I/O, but a single CPU-intensive task can impede the entire application’s performance. You have to keep the event loop running smoothly. Poorly optimized code would eventually lead to subpar performance, unhappy users, and higher costs. Proper optimization prevents these issues.</p><h3>When to Consider Performance Optimization?</h3><p>Performance optimization should always be top of mind when building Node.js apps — from the initial planning all the way through deployment and beyond. That said, there are certain times when you really need to double down on optimization efforts:</p><ul><li><strong>Early Development:</strong> Getting designs, architecture, algorithms, and approaches right from the start pays major dividends down the road. Prioritizing efficiency, scalability, and maintainability early sets you up for success.</li><li><strong>Tackling Technical Debt:</strong> As apps grow and evolve, technical debt piles up. If left unchecked, this can strangle performance over time. Regular refactoring, optimization passes, and code clean-up keep bloat at bay.</li><li><strong>New Features:</strong> Tacking on new functionality inevitably impacts performance. Before shipping anything new, put in the work to ensure it won’t degrade the overall experience.</li><li><strong>Pre-Deploy:</strong> Speaking of shipping, you better hope your app can actually handle real-world loads before pushing to production! Thorough performance testing and tuning pre-deploy is non-negotiable.</li><li><strong>Bottleneck Whack-a-Mole: </strong>Whether in development, testing, or production, any time slowdowns or issues crop up, you need to quickly identify and squash those performance bottlenecks through optimization.</li><li><strong>Reducing Operational Costs:</strong> A finely optimized app simply costs less to run and scale by being friendlier on CPU, memory, bandwidth and the rest. For cost-conscious teams, that’s a huge win.</li><li><strong>Load Testing:</strong> With simulated traffic, load testing is the perfect chance to uncover scaling limitations, bottlenecks under heavy fire, and optimization opportunities pre-launch.</li><li><strong>Infrastructure Scaling: </strong>As your infrastructure grows to meet demand, your optimization strategies need to keep pace. Scaling out requires revisiting performance tuning to ensure efficiency at scale.</li><li><strong>Resource-Constrained Environments:</strong> For edge devices, embedded systems, or other constrained use cases, ruthless optimization is mandatory to maximize limited resources.</li><li><strong>Ongoing Maintenance:</strong> Optimization isn’t a one-and-done thing. You need to continuously review and adjust as data grows, usage patterns shift and new code is introduced over time.</li><li><strong>Production Monitoring: </strong>Finally, always keep an ear to the ground in production! User complaints or metrics indicating slowdowns should immediately trigger investigation and improvement work.</li></ul><h3>Techniques for Optimizing Node.js Applications</h3><p>Now that you understand when you need to prioritize performance optimization for your Node.js apps. Let’s explore some of the most effective ways to squeeze out maximum performance in Node.js applications:</p><h3>Code profiling</h3><p>To optimize a Node.js application, you first need to figure out where what might be causing performance bottlenecks. Profiling helps you do just this. It shows you which parts of your code are taking the most time and resources. Once you know the slow spots, you can focus on improving them. To determine the current state of your app, you might need to carry out the following tests:</p><p><strong>Load testing:</strong> This checks how your app handles a normal, expected amount of users and traffic. It lets you spot any slowdowns or issues that pop up when the app is being used regularly.</p><p><strong>Spike testing: </strong>This throws a sudden burst of users or activity at your app — more than the normal load. It shows how your app responds when there’s an unexpected spike in demand, and if it has any limits that get reached.</p><p><strong>Stress testing: </strong>This test pushes your app to its limits by gradually increasing the load until it breaks down. It shows you the maximum your app can handle before it fails, so you can identify weak points or resources running out.</p><p><strong>Scalability testing: </strong>This looks at whether your app can easily handle more users and traffic by adding more resources like servers or memory. It reveals any bottlenecks or architectural problems that might prevent the app from scaling up smoothly.</p><p>Performing some or all of the above tests will provide you with several important metrics, such as:</p><ul><li>response times</li><li>average latency</li><li>error rates</li><li>requests per second</li><li>throughput</li><li>CPU and memory usage</li><li>concurrent users</li></ul><p>and more.</p><p>There are several profiling tools like Node’s built-in profiler (node-prof), the v8-profiler module, or third-party tools like clinic.js or 0X to analyze performance metrics such as CPU usage, memory consumption, and event loop delays. Also, monitoring tools like PM2, NewRelic, or AppDynamics can provide real-time insights into your application’s performance in production environments.</p><h3>Using Native Cluster Module or PM2 for Scaling</h3><p>Node.js comes with a built-in cluster module that allows you to take advantage of multi-core systems and distribute the load across multiple worker processes. This can improve the performance and scalability of your application by leveraging all the available CPU cores. Let’s look at how to use the cluster module to distribute the load across multiple worker processes:</p><pre>const cluster = require(&#39;cluster&#39;);<br>const http = require(&#39;http&#39;);<br>const numCPUs = require(&#39;os&#39;).cpus().length;<br><br>if (cluster.isMaster) {<br>  console.log(`Master process ${process.pid} is running`);<br>  for (let i = 0; i &lt; numCPUs; i++) {<br>    cluster.fork();<br>  }<br>  cluster.on(&#39;exit&#39;, (worker, code, signal) =&gt; {<br>    console.log(`Worker ${worker.process.pid} died with code ${code} and signal ${signal}`);<br>    console.log(&#39;Starting a new worker&#39;);<br>    cluster.fork();<br>  });<br>} else {<br>  http.createServer((req, res) =&gt; {<br>    res.writeHead(200);<br>    res.end(&#39;Hello from worker process\\n&#39;);<br>  }).listen(8000);<br>  console.log(`Worker ${process.pid} started`);<br>}</pre><p>The master process forks a new worker process for each available CPU core. Each worker process listens for incoming HTTP requests on port 8000. If a worker process crashes, the master process is notified and creates a new worker to replace the crashed one.</p><p>Most often, it is better to use PM2 (Process Manager 2) because it offers convenience and comes with additional features. There is no need to write a boilerplate code.</p><p>To use PM2 for scaling, you first need to install it:</p><pre>npm install pm2 --save-dev</pre><p>Once installed, you can start your application with PM2 and enable clustering:</p><pre>pm2 start app.js -i max</pre><p>The -i max flag instructs PM2 to start as many instances of your application as there are available CPU cores. PM2 will automatically load balance incoming requests across these instances.</p><p>You can also manually specify the number of instances to start:</p><pre>pm2 start app.js -i 4</pre><p>This will start four instances of your application.</p><p>PM2 comes with additional features like zero-downtime reloads, monitoring, and logging which make it a popular tool for managing and scaling Node.js applications in production environments.</p><h3>Leverage Gzip Compression</h3><p>Gzip compression can reduce the amount of data transferred between the server and the client significantly, which can result in faster response times and improved performance at large, especially for applications that serve large amounts of text-based content (e.g., HTML, CSS, JavaScript).</p><p>In Node.js, you can enable Gzip compression by using a library called compression. To use compression you first need to install it via npm registry and import it into your express project:</p><p>Installing compression library:</p><pre>npm install compression</pre><p>To use compression library:</p><pre>const express = require(&#39;express&#39;);<br>const compression = require(&#39;compression&#39;);<br>const app = express();<br><br>// Enable Gzip compression<br>app.use(compression());<br><br>app.use(express.static(&#39;public&#39;));<br><br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server running at http://localhost:3000&#39;);<br>});</pre><p>The middleware automatically compresses the response data based on the request&#39;s Accept-Encoding header and the response&#39;s content type.</p><p>When serving text-based content, using Gzip can reduce the amount of data transferred between the server and the client which can result in faster response times.</p><h3>Use Timeout Blocking I/O operations</h3><p>Node.js is designed to handle many connections at once by avoiding blocking operations that tie things up. However, if a slow I/O operation like reading a file gets stuck, it can block Node.js from doing other work efficiently. To prevent this, use timeouts for slow I/O tasks. A timeout sets the maximum time for an operation to finish. If it takes too long, you can cancel it or handle it in a way that doesn’t block everything else.</p><p>For example, setting a timeout when reading a file:</p><pre>const fs = require(&#39;fs&#39;);<br><br><br>const MAX_TIMEOUT = 5000;<br>const readFile = (filePath, callback) =&gt; {<br>  fs.readFile(filePath, (err, data) =&gt; {<br>    if (err) {<br>      return callback(err);<br>    }<br>    callback(null, data);<br>  });<br>};<br><br>const readFileWithTimeout = (filePath, callback) =&gt; {<br>  const timeoutId = setTimeout(() =&gt; {<br>    callback(new Error(&#39;File read operation timed out&#39;));<br>  }, MAX_TIMEOUT);<br>  readFile(filePath, (err, data) =&gt; {<br>    clearTimeout(timeoutId);<br>    if (err) {<br>      return callback(err);<br>    }<br>    callback(null, data);<br>  });<br>};</pre><p>The readFileWithTimeout function sets a 5-second timeout using setTimeout. If the fs.readFile the operation takes longer, the timeout callback is triggered, passing an error to the provided callback.</p><p>If readFile completes before the timeout, clearTimeout cancels the timeout and passes the file data to the callback.</p><p>Bear in mind that timeout value should balance your app’s needs; too short risks cutting off legitimate long operations, and too long defeats the purpose of using timeouts.</p><h3>Use Streaming for I/O Operations</h3><p>Streaming is really useful when you are dealing with large files, network responses, or any scenario where data needs to be processed as soon as it arrives, rather than waiting for the entire data to be loaded into memory. It is one of the powerful techniques for optimizing Node.js applications, especially when dealing with I/O operations involving large amounts of data.</p><p>Let’s say you need to read a multi-gigabyte CSV file with millions of rows. You can use streams to process data in small chunks as it comes in. Let’s see what I mean:</p><pre>const fs = require(&#39;fs&#39;);<br>const stream = require(&#39;stream&#39;);<br>const csvParser = require(&#39;csv-parser&#39;);<br><br>const csvStream = fs.createReadStream(&#39;large-data.csv&#39;)<br>  .pipe(csvParser());<br><br>const writableStream = new stream.Writable({<br>  write(chunk, encoding, next) {<br>    console.log(&#39;Got chunk of CSV data:&#39;, chunk);<br>    next();<br>  }<br>});<br><br>csvStream.pipe(writableStream);<br><br>writableStream.on(&#39;error&#39;, (err) =&gt; {<br>  console.error(&#39;Error:&#39;, err);<br>});<br><br>writableStream.on(&#39;finish&#39;, () =&gt; {<br>  console.log(&#39;CSV data processing completed.&#39;);<br>});</pre><p>The readable csvStream pipes CSV data chunk-by-chunk to the writable stream. The write method processes each chunk as it arrives, without waiting for the full CSV file to load into memory.</p><p>Streaming prevents memory bloat and improves performance for I/O heavy tasks like parsing huge CSV files. It’s perfect for any scenario dealing with large data sets that would be impractical to load fully into memory or a large API response.</p><h3>Minimize dependencies</h3><p>Dependencies can provide valuable functionality and speed up the workflow, but having too many dependencies or using outdated or unnecessary dependencies can sometimes negatively impact your application’s performance.</p><p>Let’s learn to look into some ways to minimize dependencies in Node.js applications:</p><ul><li><strong>Audit and Remove Unused Dependencies</strong>: Periodically audit your project’s dependencies and remove any unused or unnecessary packages. You can use tools like npm-prune or depcheck to identify and remove unused dependencies.</li></ul><pre>npm install -g npm-prune</pre><p>Run the prune command to remove unused dependencies</p><pre><br>npm prune</pre><ul><li><strong>Upgrade Dependencies Regularly</strong>: Keep your dependencies up-to-date by regularly upgrading them to the latest stable versions. Outdated dependencies can pose security risks, introduce bugs, or miss out on performance improvements. You can use tools like npm-check-updates or npm outdated to check for available updates.</li></ul><p>Install the package</p><pre>npm install -g npm-check-updates</pre><p>Check for available updates</p><pre>npm-check-updates</pre><p>Update dependencies</p><pre><br>npm-check-updates -u<br>npm install</pre><ul><li><strong>Use Bundlers and Tree Shaking</strong>: Leverage module bundlers like Webpack or Rollup, which can perform tree shaking, a process that removes unused code from your application and its dependencies. This can significantly reduce the final bundle size and improve performance.</li><li><strong>Prefer Smaller and Focused Dependencies</strong>: When choosing dependencies, opt for smaller and more focused packages that provide only the functionality you need, rather than larger, monolithic libraries with many unused features.</li><li><strong>Consider Writing Custom Code</strong>: In some cases, it may well be worth it to write custom code instead of relying on a dependency, especially if the required functionality is relatively simple or specific to your application.</li></ul><h3>Load balancing</h3><p>As your Node.js application grows and handles more traffic, you will need to distribute that load across multiple servers to maintain performance and availability. This is where load balancing comes into play. Load balancing spreads incoming requests across a group of servers and prevents any single server from getting overwhelmed. You can use software solutions like:</p><ul><li>Nginx or HAProxy</li><li>Cloud load balancing services (AWS ELB, Google Cloud Load Balancing, etc.)</li></ul><p>Effective load balancing improves performance by sharing the workload. It also strengthened fault tolerance. If one server fails, traffic gets redirected to healthy servers, thereby maintaining high availability.</p><h3>Serve Node.js static assets with Nginx</h3><p>Node.js is a great tool for building backend services. However, it’s not optimized for serving static files and can experience performance bottlenecks when tasked with this responsibility. Nginx can be used as a reverse proxy to handle serving static assets for your Node.js application, while your Node.js app handles dynamic requests and application logic. This setup improves performance and scalability by leveraging Nginx’s optimized static file-serving capabilities.</p><h3><strong>Offload CPU-intensive Tasks</strong></h3><p>Node is great at handling multiple I/O operations at once. But when it comes to heavy CPU work like number crunching or media processing, Node can get bogged down since it’s single-threaded. These CPU-bound tasks can bog everything down and cause delays.</p><p>The solution is to offload the CPU-intensive work to separate processes or services. That way, the main Node process stays nimble for regular I/O.</p><p>You can use things like:</p><ul><li>Child processes to run CPU tasks in parallel across multiple cores</li><li>Worker threads to execute CPU work in separate threads within Node</li><li>Web workers for client-side CPU scripting in background threads</li><li>Serverless functions like AWS Lambda to run code in the cloud</li><li>External APIs designed for CPU-heavy jobs like image processing</li></ul><p>Splitting off the number crunching prevents it from tying up Node’s single thread. Your app stays responsive for regular networking and I/O tasks it’s awesome at. The CPU muscle gets flexed elsewhere.</p><h3>Use the Latest Node.js Version</h3><p>Node.js is an actively developed and maintained project, with frequent releases that introduce new features, performance improvements, and bug fixes. Using an outdated version of Node.js can potentially lead to performance issues, security vulnerabilities, and compatibility problems with newer libraries and frameworks. Each new Node.js release includes optimizations and improvements to the V8 JavaScript engine, which can result in better execution times and overall performance.</p><p>To upgrade Node.js, you can download the latest version from the Node.js official website or use a version manager like nvm. This tool allows you to install and switch between different Node.js versions easily.</p><p>If you already have nvm installed on your computer, you can easily Install the latest Node.js version</p><p>You can list the available Node.js versions by running:</p><pre>nvm ls-remote</pre><p>Install the latest Node.js version:</p><pre>nvm install &lt;nodejs version&gt;</pre><p>Use the latest installed version:</p><pre>nvm use &lt;nodejs version&gt;</pre><p>You can use the same nvm usecommand to switch between different versions of Node.js if you encounter some issue relating to compatibility. That being said, your application would benefit greatly from the latest performance improvements by keeping the Node.js version up-to-date.</p><h4>Wrapping up</h4><p>Performance optimization is an ongoing and iterative process that should be embedded throughout the entire development lifecycle of a Node.js application. Before choosing which optimization techniques to implement, try to evaluate each strategy against your specific application requirements, infrastructure, and performance goals.</p><p>Happy Hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb009430634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js Security Best Practices for Production Environment]]></title>
            <link>https://towardsdev.com/node-js-security-best-practices-for-production-environment-77b9c27f005b?source=rss-703e978f4870------2</link>
            <guid isPermaLink="false">https://medium.com/p/77b9c27f005b</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Abubakar Balogun]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 19:28:35 GMT</pubDate>
            <atom:updated>2024-04-24T16:33:39.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RniDtZweB56Bma9XYzkZsQ.png" /></figure><p>In recent years, Node.js has become one of the leading choices for building scalable backend web applications, with an impressive 30 million applications currently in operation and claiming a noteworthy 3.5% market share, according to W3techs. What distinguishes Node.js’s ascent is its steady adoption trajectory, in contrast to sudden spikes typical of newer technologies. However, alongside its growing prevalence, ensuring the security of Node.js applications in production environments remains a top priority.</p><p>Like any software, Node.js applications are susceptible to a range of cyber threats, from injection attacks to data breaches. The risks associated with insecure Node.js applications are significant and demand attention. In this article, we explore various approaches and best practices aimed at improving the security of Node.js applications in production settings.</p><h3>Why Should You Take Node.js Security so Serious?</h3><p>Because Node.js is the most widely used Javascript runtime for web development, its widespread usage makes it a prime target for attackers seeking to exploit vulnerabilities. Also, Node.js heavily relies on the Node Package Manager (NPM) ecosystem for libraries and modules. While this allows for rapid development, it also introduces the risk of using third-party packages with security vulnerabilities. Any npm package, no matter how innocent-looking, can access Node.js modules, such as file systems, networks, and more. This access means they can execute malicious code and gain entry to sensitive data in the production environment. A single malicious package could open the door for executing malware or exposing sensitive data. A recent report by <a href="http://mend.io/">mend.io</a> indicated that since 2019, almost <a href="https://www.mend.io/wp-content/media/2022/02/Mend-npm-Threat-Repot.pdf">104,000 open-source packages</a> have been flagged as malicious, posing threats to the integrity of software projects and potentially exposing user data. While these statistics may paint a sobering picture, this article aims to provide a set of standard practices recommended by the Node.js Security Working Group (SWG) to avoid these vulnerabilities, keep sensitive data safe, and prevent Node.js applications from harmful attacks. Let’s explore them together.</p><h3>Common Node.js Security Vulnerabilities and how to Mitigate them.</h3><p>Node.js applications can face a wide range of security vulnerabilities. Some are specific to the Node.js runtime, while others are more general issues that any software could encounter. Common vulnerabilities include, but are not limited to:</p><h3>Denial of Service (DoS) Attacks</h3><p>DoS is a cyber attack in which the bad actor aims to disrupt services by overwhelming the target (servers) with a flood of requests, and exhausting resources such as CPU, memory, or network bandwidth. In Node.js applications, common DoS attack vectors include sending a large number of requests to endpoints that perform expensive computations or blocking the event loop with synchronous operations that prevent normal traffic from proceeding, resulting in denial-of-service to regular users. There is also another attack known as Distributed Denial of Service (DDoS)<strong>.</strong> Both DoS and DDoS attacks are similar except that DoS attacks come from a single computer source while DDoS attacks come from various distributed sources simultaneously. The severity of these attacks is significant, this entails downtime, loss of revenue, as well as reputation damage.</p><h3>Mitigation</h3><p>Preventing DoS attacks can be a serious challenge, particularly during periods of high traffic. A robust defence against DDoS threats relies on several critical factors, such as reducing the attack surface, observing traffic patterns, vigilant threat monitoring, and implementing scalable DDoS mitigation tools.</p><p><strong>DDoS prevention methods</strong></p><ul><li><strong>Implement Rate Limiting</strong>: Set limits on the number of requests allowed from a single IP address within a certain time frame. This helps prevent attackers from flooding your server with excessive requests.</li><li><strong>Use Web Application Firewalls (WAF)</strong>: Deploy WAF solutions that can filter and block malicious traffic, including DoS attacks. WAFs can detect and mitigate various types of attacks in real-time.</li><li><strong>Scale Infrastructure</strong>: Ensure your infrastructure is scalable to handle sudden spikes in traffic. Use load balancers and distributed architectures to distribute traffic across multiple servers and prevent any single point of failure.</li><li><strong>Monitor Traffic Patterns</strong>: Regularly monitor your network traffic for unusual patterns or spikes that may indicate a DoS attack. Implement intrusion detection systems (IDS) or intrusion prevention systems (IPS) to detect and respond to malicious activities.</li><li><strong>Enable DDoS Protection Services</strong>: Utilize DDoS protection services offered by cloud service providers or specialized DDoS mitigation companies. These services can help detect and mitigate large-scale DDoS attacks before they reach your network.</li><li><strong>Optimize Application Code</strong>: Ensure your application code is optimized to handle requests efficiently. Avoid expensive computations or blocking operations that could potentially be exploited in DoS attacks.</li><li><strong>Secure Network Infrastructure</strong>: Secure your network infrastructure by applying security best practices, such as using strong authentication methods, keeping software and systems up-to-date with patches, and segmenting network traffic to limit the impact of an attack.</li></ul><h3>HTTP Request Smuggling</h3><p>HTTP request smuggling occurs when discrepancies in the interpretation of HTTP headers between front-end and back-end systems enable attackers to manipulate requests, potentially bypassing security measures. In Node.js applications, this vulnerability often stems from inconsistencies in how proxy servers or middleware handle HTTP headers.</p><p>Improper handling of HTTP headers, especially within setups involving reverse proxies or load balancers, can lead to HTTP request smuggling. Let’s look into a simplified example to better understand how this vulnerability manifests in a Node.js environment.</p><p>Consider a basic Node.js server using the Express framework:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello, world!&#39;);<br>});<br>app.listen(3000, () =&gt; {<br>  console.log(&#39;Server is running on port 3000&#39;);<br>});</pre><p>Now, imagine this Node.js server deployed behind a reverse proxy or load balancer. The reverse proxy might forward HTTP requests to the Node.js server using HTTP/1.0 protocol, while the Node.js server expects HTTP/1.1.</p><p>Here’s a scenario illustrating how HTTP request smuggling might occur:</p><p>An attacker crafts a request with conflicting “Content-Length” headers — one indicating a shorter length and another indicating a longer length:</p><pre>POST / HTTP/1.1<br>Host: vulnerable-website.com<br>Content-Length: 4<br>Content-Length: 100<br>Transfer-Encoding: chunked<br><br>0<br>GET /admin HTTP/1.1<br>Host: vulnerable-website.com</pre><p>The reverse proxy and the Node.js server interpret the request differently. The reverse proxy might process the first “Content-Length” header and forward only part of the request to the Node.js server. However, the Node.js server may interpret the second “Content-Length” header, expecting additional data that the reverse proxy did not forward. Consequently, it may treat the subsequent request (“GET /admin HTTP/1.1”) as part of the original request, potentially leading to security vulnerabilities such as unauthorized access to sensitive resources.</p><h3>Mitigation</h3><ul><li>Ensure consistent use of HTTP protocol versions (either HTTP/1.0 or HTTP/1.1) across your infrastructure.</li><li>Implement robust validation and sanitization of HTTP headers within your Node.js application.</li><li>Employ security measures like Content-Length validation, strict header parsing, and payload validation to detect and prevent smuggling attacks.</li></ul><h3>Insecure or Malicious Third-party Modules</h3><p>Using third-party libraries with known vulnerabilities can introduce security risks to your application, as mentioned earlier in the article. Even if these NPM packages don’t harbour malicious intent, they can inadvertently introduce security flaws, especially in older versions. Additionally, some dependencies may no longer receive maintenance or have been deprecated.</p><p>Fortunately, the Node.js core is backed by a large community committed to security. The Node.js Security Working Group (SWG) plays a vital role in enhancing the security of Node.js applications. This group gathers vulnerability data from the community, shares it with the Node Security Platform, and ensures the public disclosure of vulnerabilities in Node packages.</p><p><strong><em>Mitigation:</em></strong></p><p>To mitigate these risks, prioritize using the latest dependency versions. Developers often release updates to fix bugs, including security vulnerabilities in older versions. Running <strong>npm audit</strong> can help identify dependencies with potential security issues.</p><p>Additionally, integrating Static Application Security Testing (SAST) and Software Composition Analysis (SCA) into your continuous integration and delivery (CI/CD) processes is also crucial. These tools help ensure that your applications remain secure throughout development and deployment.</p><p>Some effective SAST tools for Node.js include:</p><ul><li>Semgrep</li><li>eslint-plugin-security</li><li>vuln-regex-detector</li></ul><h3>Experimental Features in Production</h3><p>Experimental features are by definition not stable and may undergo significant changes or even removal in future versions of Node.js. This can lead to compatibility issues and breakages in your application when you upgrade Node.js. Also, experimental features may not have undergone thorough security reviews, making them potentially more vulnerable to security exploits or vulnerabilities.</p><h3>Mitigation:</h3><p>Stick to stable, well-tested features for production. Understand the maturity level of any feature and its security risks before using it in production. Test new features thoroughly in staging environments before putting them into production.</p><h3>DNS Rebinding</h3><p>DNS rebinding also known as <strong>CWE-346</strong> is a type of attack that manipulates the Domain Name System (DNS) to bypass the same-origin policy, a security measure implemented by web browsers to prevent different websites from interacting with each other.</p><p>Attackers exploit DNS rebinding vulnerabilities to bypass same-origin policy protections, allowing them to interact with resources that should be restricted. In Node.js, this vulnerability can be exploited by manipulating DNS responses to point to local addresses or internal network resources, thereby circumventing browser security restrictions.</p><h3>Mitigation</h3><p>Mitigation involves implementing strict DNS resolution policies, validating hostnames and IP addresses, and using techniques such as DNS pinning to prevent DNS rebinding attacks.</p><h3>Running Node.js with Root privilege</h3><p>Running Node.js with root privileges can introduce significant security risks due to the increased access it grants to system resources. When Node.js is executed with root privileges, it gains elevated permissions, expanding its potential attack surface and making it a prime target for malicious actors. This heightened level of access opens the door to privilege escalation attacks, where attackers exploit vulnerabilities in the Node.js process to gain root access and potentially compromise the entire system. Additionally, running Node.js as root allows the process to manipulate files and interact with the network with elevated privileges, increasing the risk of unauthorized access, data breaches, and network-based attacks</p><h3>Mitigation:</h3><p>Run Node.js processes with limited permissions by using dedicated user accounts with minimal access rights. Additionally, consider using containerization technologies like Docker or process managers like PM2 to isolate Node.js applications and enforce resource constraints.</p><h3>Improper error handling</h3><p>Improper error handling poses significant risks to the security and stability of software systems. When errors are not handled appropriately, sensitive information may be inadvertently exposed, leading to privacy breaches and potential exploitation by malicious actors. In addition, inadequate error handling can introduce vulnerabilities that attackers can exploit to gain unauthorized access to systems or disrupt their operation.</p><h3>Mitigation:</h3><p>Implement proper error handling by validating input data, sanitizing user-controlled inputs, and using structured error handling mechanisms such as try-catch blocks. Avoid exposing detailed error messages or stack traces to users in production environments, as this information can aid attackers in identifying vulnerabilities and crafting targeted attacks.</p><h3>Use authorization and access controls</h3><p>Failing to implement proper access controls and authorization mechanisms can lead to serious security vulnerabilities. Without proper controls, malicious actors could potentially access or manipulate sensitive data, execute unauthorized actions, or even gain elevated privileges within the application or system.</p><h3>Mitigation:</h3><ol><li><strong>Principle of Least Privilege</strong>: Ensure that users, processes, and components have only the minimum necessary permissions and access rights to perform their intended functions. Avoid granting excessive privileges that could be exploited if compromised.</li><li><strong>Role-Based Access Control (RBAC)</strong>: Implement a role-based access control system that assigns permissions and access rights based on the roles and responsibilities of users or components within the application. This helps to enforce the principle of least privilege and reduces the risk of unauthorized access or actions.</li><li><strong>Authentication and Authorization</strong>: Implement robust authentication and authorization mechanisms to verify the identity of users or components and validate their permissions before granting access to sensitive resources or functionalities. This can include techniques such as password-based authentication, multi-factor authentication, or token-based authentication for APIs.</li><li><strong>Input Validation and Sanitization</strong>: Validate and sanitize all user input and external data before processing it within the application. Malicious input can potentially bypass authorization checks or introduce vulnerabilities if not properly handled.</li><li><strong>Secure Communication</strong>: Use secure communication protocols (e.g., HTTPS) and encryption techniques to protect sensitive data in transit, especially when transmitting authentication credentials or sensitive information between clients and servers.</li></ol><h3>Lack of robust monitoring and Logging</h3><p>Logging plays a pivotal role in any application, providing crucial insights into its behaviour, performance, and error occurrences. In Node.js applications, effective logging is particularly vital, aiding developers in comprehending the application’s inner workings, diagnosing issues, and maintaining its health. However, inadequate monitoring and logging practices can hinder the timely detection and response to security incidents.</p><h3>Mitigation</h3><p>It’s imperative to implement comprehensive logging and monitoring solutions. These measures enable the prompt identification and mitigation of security threats. By closely monitoring system and application logs, you can pinpoint suspicious activities, anomalous behaviours, and security-related events. Leveraging centralized log management platforms and intrusion detection systems (IDS) further enhances the ability to aggregate and analyze log data efficiently.</p><h3>Cross-Site Request Forgery (CSRF)</h3><p>CSRF is a security problem where attackers trick your browser into doing things you didn’t intend on a site where you’re logged in. They exploit how browsers automatically send cookies with requests, even if they’re fake ones.</p><h3>Mitigation:</h3><p>To protect against CSRF, use CSRF tokens and check them properly. These tokens are unique for each user session and go with form submissions. On the server, make sure these tokens are real to stop bad requests and keep your site safe.</p><h3>Monkey Patching</h3><p>Modifying or extending built-in objects or libraries at runtime can introduce unexpected behaviour and security vulnerabilities. Let’s at an example of monkey patching where we are overriding a method in the built-in String object in Node.js:</p><pre>const originalToUpperCase = String.prototype.toUpperCase;<br><br>// Monkey patching: Overriding toUpperCase method<br>String.prototype.toUpperCase = function() {<br>    // Add logging or custom functionality here<br>    console.log(&quot;Custom toUpperCase method called!&quot;);<br>    // Call the original method with the current context<br>    return originalToUpperCase.apply(this, arguments);<br>};<br>// Testing the monkey patched method<br>const modifiedString = &quot;hello&quot;;<br>console.log(modifiedString.toUpperCase());</pre><p><strong><em>Mitigation</em>:</strong></p><p>Avoid monkey patching whenever possible. Use recommended extension points and design patterns to extend functionality safely. When necessary, thoroughly review and test monkey patches to ensure compatibility, stability, and security. Additionally, document and communicate any modifications to built-in objects or libraries to maintain code maintainability and facilitate future updates and debugging.</p><h3>Closing Thought</h3><p>Node.js security best practices go far beyond just the few mentioned above. They involve comprehensive, almost obsessive checks for vulnerabilities in the codebase. To build a resilient application, one must adopt a security-first mindset and follow Node.js best practices from the outset. A secure approach should be taken not only for your application but also for your execution environment. Operating systems, hosting environments, and networks all play a role in application security. It is important to remember that security is an ongoing process, not a one-time task. Regularly reassess your application’s security posture and invest in security tools. By prioritizing security at every stage of the development lifecycle, we can build more resilient and secure software that inspires trust and confidence among users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77b9c27f005b" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/node-js-security-best-practices-for-production-environment-77b9c27f005b">Node.js Security Best Practices for Production Environment</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step: Build Your own HTTP Client like Axios using Node.js and Typescript]]></title>
            <link>https://abubalogun.medium.com/step-by-step-build-your-own-http-client-like-axios-using-node-js-and-typescript-6680582fcdfe?source=rss-703e978f4870------2</link>
            <guid isPermaLink="false">https://medium.com/p/6680582fcdfe</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[http-client]]></category>
            <dc:creator><![CDATA[Abubakar Balogun]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 18:06:55 GMT</pubDate>
            <atom:updated>2025-07-30T14:50:10.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO5YpOfzuxENQZDnWUbUVA.png" /></figure><p>An HTTP client is a program embedded within a larger application that sends requests to a server using the Hypertext Transfer Protocol (HTTP) and receives and processes the responses. Many modern applications and services communicate with each other over the web using HTTP-based APIs (Application Programming Interfaces). Well-known web browsers like Chrome, Firefox, Safari, and Edge serve as examples of HTTP clients. They initiate HTTP requests to servers when users navigate web pages, submit forms, or engage in other interactions on the web. It’s also not uncommon for servers to communicate with each other to request resources for specific tasks. Consider a scenario where a Node.js backend application needs to consume the OpenAI API. HTTP clients such as Axios, node-fetch, and the recently stable Node.js fetch API are commonly used to facilitate this communication.</p><p>As someone who uses Axios in both browser and Node.js environments, I’ve come to appreciate its convenience for handling HTTP requests on both the client and server sides. This experience sparked my curiosity about the inner workings of HTTP clients like Axios. If you share this curiosity, why not embark on a journey to build your own simple HTTP client capable of sending requests and processing responses?</p><p>This tutorial invites you to explore Node.js mastery by utilizing its powerful built-in module to create a rudimentary HTTP client that works similarly to Axios. Step-by-step, you’ll explore the essential concepts of handling HTTP requests, decoding responses, managing headers, and gracefully managing errors. By the end, you’ll not only understand the mechanics of an HTTP client but also have your custom-built tool ready to seamlessly connect with web services. Let’s dive in!</p><h3>Prerequisites</h3><ul><li>Make sure to have Node.js installed on your computer. You can head to the official node.js website to download the latest node.js version..</li><li>Node.js Basics: Ensure you have a good understanding of Node.js fundamentals. Know how to work with modules, handle asynchronous operations, and manage dependencies using npm or yarn.</li><li>JavaScript Async Operations: Understand asynchronous JavaScript, as most HTTP requests are asynchronous. Understand promises, async/await, and how they work to handle asynchronous tasks.</li><li>A basic knowledge of Typescript: This project uses Typescript but you can follow along in plain Javascript.</li></ul><h3>How does Axios work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2sECDqwHPurOnAPKqvbHA.png" /></figure><p>Before we go building our HTTP client, let’s grasp how Axios operates. Axios is an isomorphic JavaScript library, meaning it operates in both browser and Node.js environments. Its isomorphic nature allows developers to write consistent code for making HTTP requests across different platforms. In Node.js environments, Axios takes advantage of the built-in <strong>http</strong> module, making it capable of handling HTTP requests without the need for external dependencies. This integration with Node.js allows Axios to tap into the server-side capabilities of the platform. On the other hand, in browser environments, Axios utilizes the <strong>XMLHttpRequest</strong> object, providing compatibility with various web browsers. This ensures that Axios can be incorporated into front-end applications seamlessly.</p><h3>Understanding the HTTP Request and Response Lifecycle</h3><p>Another important concept to understand when building an HTTP client is the HTTP Request and Response Lifecycle. The HTTP request and response lifecycle intricately details the steps involved when a client, like a web browser, interacts with a server to access information from a website. Below is a structured breakdown of this lifecycle:</p><h3>Request Phase:</h3><ol><li><strong>Client Initiation</strong>:</li></ol><ul><li>A user action, like entering a URL, clicking a link or submitting a form, triggers the client (web browser) to send an HTTP request to a server.</li></ul><ol><li><strong>Request Formation</strong>:</li></ol><ul><li>The client assembles an HTTP request comprising:</li><li><strong>HTTP Method</strong>: Specifies the type of request (GET, POST, etc.).</li><li><strong>URL/URI</strong>: Identifies the requested resource.</li><li><strong>Headers</strong>: Additional details like content type, accepted languages, and authentication.</li><li><strong>Body (optional)</strong>: Data accompanying POST or PUT requests.</li></ul><ol><li><strong>Transmission</strong>:</li></ol><ul><li>The request traverses the network via TCP/IP to reach the server.</li></ul><h3>Server-Side Processing:</h3><ol><li><strong>Server Actions</strong>:</li></ol><ul><li>Upon receiving the request, the server:</li><li><strong>Routes</strong> it to the specified resource.</li><li><strong>Handles</strong> the request by executing necessary operations.</li><li><strong>Generates</strong> an HTTP response.</li></ul><p><strong>2. Response Composition</strong>:</p><ul><li>The server constructs an HTTP response comprising:</li><li><strong>Status Code</strong>: Indicates the request outcome (e.g., 200, 404, 500).</li><li><strong>Headers</strong>: Details about content, server, and caching.</li><li><strong>Body</strong>: Data/resource in HTML, JSON, XML, etc.</li></ul><p><strong>3. Transmission</strong>:</p><ul><li>The server dispatches the HTTP response back to the client over the network.</li></ul><h3>Client-Side Handling:</h3><ol><li><strong>Response Processing</strong>:</li></ol><ul><li>On receiving the response, the client:</li><li><strong>Checks Status Code</strong>: Determines success or errors.</li><li><strong>Renders Content</strong>: Displays the data (webpage, images, text) for the user.</li><li><strong>Performs Actions</strong>: Executes scripts or initiates further requests.</li></ul><p><strong>2. Lifecycle Continuation</strong>:</p><ul><li>The specific request/response interaction concludes, presenting content in the browser.</li></ul><p>This cyclical process persists as users engage with the web app, prompting additional HTTP requests for various resources or actions.</p><h3>Implementation</h3><p>Let’s get into a practical implementation for creating an HTTP client in Node.js by leveraging TypeScript.</p><h3>Setting Up the Project</h3><p>Let’s begin by initializing a new Node.js project. Open your terminal and create a new directory for the project:</p><pre>mkdir http-client<br>cd http-client<br>npm init -y</pre><h3>Installing Dependencies</h3><p>Since we’ll be using TypeScript for this project, we need to install a couple of dependencies:</p><pre>npm install typescript @types/node ts-node</pre><p>@types/node provides types for Node.js, and ts-node allows us to run TypeScript directly in the terminal without having to transpile to JavaScript..</p><h3>Creating Project Files</h3><p>Create the necessary files for your project structure. For project</p><ul><li>Create a <strong>src</strong> directory to hold TypeScript files.</li><li>Inside<strong>src</strong>, create <strong>HttpClient.ts</strong> to start writing our HTTP client implementation.</li></ul><h3>Defining the interface for the HTTP client</h3><p>In the src folder, create a file named type.ts. This will house a type declaration for <strong>HttpClient.ts</strong>. Let’s start by defining the interfaces for request options and HTTP response.</p><pre>import http from &#39;http&#39;;<br><br>export interface RequestOptions&lt;T&gt; extends http.RequestOptions {<br>  method: &quot;GET&quot; | &quot;POST&quot; | &quot;PUT&quot; | &quot;PATCH&quot; | &quot;DELETE&quot;;<br>  headers?: Record&lt;string, string&gt;;<br>  queryParameters?: Record&lt;string, string&gt;;<br>  body?: T;<br>}<br><br>export interface HttpResponse&lt;T&gt; {<br>  data: T;<br>  status?: number;<br>  statusMessage?: string;<br>  headers: Record&lt;string, string&gt;;<br>}</pre><p>These interfaces establish a clear blueprint for creating HTTP requests and processing responses within our client. The <strong>RequestOptions</strong> interface encapsulates essential details such as request method, headers, query parameters, and the request body. Meanwhile, the <strong>HttpResponse</strong> interface defines the structure of the received response, encompassing response data, status code, status message, and response headers.</p><h3>Step 5: Define the structure of the HTTP client class</h3><pre>import http from &quot;http&quot;;<br>import https from &quot;https&quot;;<br>import { RequestOptions, HttpResponse } from &quot;./types&quot;;<br><br>export class HttpClient {<br>  private baseURL?: string;<br>  constructor(baseURL?: string) {<br>    this.baseURL = baseURL;<br>  }<br>}</pre><p>In this phase, we define the structure of the HTTP client class. We import <strong>http</strong> and <strong>https</strong> modules for making HTTP requests and import types needed for request options and response handling, as well as sending HTTP requests on both secured and insecure networks, such as localhost.</p><p>The <strong>HttpClient</strong> class contains a private optional variable <strong>baseURL</strong>, which represents the base URL for the HTTP client. It also includes a constructor function that accepts an optional <strong>baseURL</strong> parameter, allowing the client to be initialized with a base URL if needed.</p><h3>Implement Utility Functions</h3><p>Let’s begin by implementing private methods that handle the behind-the-scenes work to ensure the functionality of our HTTP client.</p><h3>a. isValidUrl:</h3><pre>private isValidUrl(url: string): boolean {<br>    try {<br>      new URL(url);<br>      return true;<br>    } catch (error) {<br>      return false;<br>    }<br>  }</pre><p>The <strong>isValidUrl</strong> method in the <strong>HttpClient</strong> class validates a given URL string by attempting to create a new <strong>URL</strong> object with it. If the creation is successful, indicating a valid URL, the method returns <strong>true</strong>; otherwise, it returns <strong>false</strong>. This method simplifies and standardizes URL validation across the application, ensuring consistent validation logic throughout different parts of the codebase.</p><h3>b. buildUrl:</h3><pre>private buildUrl(path: string, queryParameters?: Record&lt;string, string&gt;) {<br>    let url = this.baseURL || &quot;&quot;;<br>    if (url &amp;&amp; !url.endsWith(&quot;/&quot;)) {<br>      url += &quot;/&quot;;<br>    }<br><br>url += path;<br>    if (queryParameters) {<br>      const queryParams = new URLSearchParams(Object.entries(queryParameters));<br>      url += `?${queryParams.toString()}`;<br>    }<br>    return url;<br>  }</pre><p>The buildUrl method in the HttpClient class is essential for constructing complete URLs for HTTP requests. It takes a path parameter representing the endpoint path and an optional queryParameters parameter for specifying query string parameters. Its primary objective is to ensure the generated URL is valid and incorporates any necessary query parameters.</p><p>The method initializes the url variable with the base URL (this.baseURL) if it exists, or an empty string otherwise. It then appends the endpoint path to the URL. Before doing so, it checks if the URL already ends with a trailing slash (&quot;/&quot;). If not, it appends one to ensure proper URL formatting.</p><p>If queryParameters are provided, the method constructs a query string using the URLSearchParams API. This ensures that query parameters are correctly encoded and formatted. The resulting query string is then appended to the URL using the &quot;?&quot; separator.</p><p>Finally, the method returns the fully constructed URL, which includes the base URL (if any), endpoint path, and any specified query parameters. By centralizing URL construction logic within the buildUrl method, the HttpClient class ensures that URLs across the application are consistently formatted and include all necessary parameters. This approach enhances code readability, maintainability, and consistency in handling HTTP requests.</p><h3>c. buildRequestOptions:</h3><pre>private buildRequestOptions&lt;T&gt;(<br>    method: RequestOptions&lt;T&gt;[&quot;method&quot;],<br>    options: RequestOptions&lt;T&gt;<br>  ): RequestOptions&lt;T&gt; {<br>    const requestOptions: RequestOptions&lt;T&gt; = {<br>      method,<br>      headers: options.headers || {},<br>    };<br><br>if (options.body) {<br>      requestOptions.headers![&quot;Content-Type&quot;] = &quot;application/json&quot;;<br>    }<br>    return requestOptions;<br>  }</pre><p>The <strong>buildRequestOptions</strong> method constructs the options object to be passed to the underlying HTTP request library <strong>http</strong>. It takes the HTTP method and additional options provided by the user and builds a request options object. This includes setting headers, particularly the <strong>Content-Type</strong> header for requests with a body. Properly setting request options ensures that requests are sent with the necessary configuration.</p><h3>d. sendRequest:</h3><pre>private async sendRequest&lt;T&gt;(<br>    url: string,<br>    options: RequestOptions&lt;T&gt;<br>  ): Promise&lt;HttpResponse&lt;T&gt;&gt; {<br>    if (!this.isValidUrl(url)) {<br>      return Promise.reject(new Error(`Invalid URL provided`));<br>    }<br><br><br>const protocol = url.startsWith(&quot;http:&quot;) ? http : https;<br>    return new Promise((resolve, reject) =&gt; {<br>      try {<br>        const request = protocol.request(url, options, (res) =&gt; {<br>          let data = &quot;&quot;;<br>          res.on(&quot;data&quot;, (chunk) =&gt; {<br>            data += chunk;<br>          });<br>          res.on(&quot;end&quot;, (data: any) =&gt; {<br>            if (<br>              res.statusCode &amp;&amp;<br>              res.statusCode &gt;= 200 &amp;&amp;<br>              res.statusCode &lt; 300<br>            ) {<br>              const response: HttpResponse&lt;T&gt; = {<br>                data: JSON.parse(data),<br>                status: res.statusCode,<br>                statusMessage: res.statusMessage,<br>                headers: res.headers,<br>              };<br>              resolve(response);<br>            } else {<br>              reject(new Error(&quot;&quot;));<br>            }<br>          });<br>          request.on(&quot;error&quot;, (error) =&gt; {<br>            reject(new Error(`Request error: ${error}`));<br>          });<br>          request.end();<br>        });<br>      } catch (error) {<br>        reject(new Error(`Request Error: ${error}`));<br>      }<br>    });  <br>}</pre><p>This method is responsible for actually sending the HTTP request. It utilizes the appropriate protocol (<strong>http</strong> or <strong>https</strong>) based on the URL&#39;s scheme. It constructs the request, handles data received from the server, and resolves or rejects the promise based on the response status code. This method encapsulates the low-level details of sending HTTP requests and handling responses, abstracting them away from the rest of the application code.</p><h3>Implement the send Function</h3><p>In this phase, we define the main <strong>send</strong> function that handles sending requests, including handling the request body.</p><pre>private async send&lt;T&gt;(<br>    method: RequestOptions&lt;T&gt;[&quot;method&quot;],<br>    path: string,<br>    options: RequestOptions&lt;T&gt;,<br>    body?: T<br>  ): Promise&lt;HttpResponse&lt;T&gt;&gt; {<br>    const url = this.buildUrl(path, options.queryParameters);<br><br>if (body) {<br>      options.body = body;<br>    }<br>    let requestOptions = this.buildRequestOptions(method, options);<br>    try {<br>      const response = await this.sendRequest&lt;T&gt;(url, requestOptions);<br>      return response;<br>    } catch (error) {<br>      throw error;<br>    }  <br>}</pre><p>The <strong>send</strong> function within the <strong>HttpClient</strong> class serves as the core method responsible for sending HTTP requests. It acts as a central piece of functionality for making HTTP requests using various methods such as GET, POST, PUT, PATCH, and DELETE. This function abstracts away the details of creating and sending HTTP requests, enabling other methods within the <strong>HttpClient</strong> class to delegate the actual request sent to it.</p><p>Functionally, <strong>send</strong> starts by constructing the full URL for the request using the <strong>buildUrl</strong> method, which incorporates the base URL (if provided) and any query parameters. It then builds the request options object using the <strong>buildRequestOptions</strong> method, ensuring that appropriate headers are set, particularly for requests with a body (e.g., setting the &quot;Content-Type&quot; header to &quot;application/json&quot;).</p><p>Afterwards, the function initiates the HTTP request using the appropriate protocol (HTTP or HTTPS) based on the URL’s scheme. It manages the request lifecycle, including error handling for request errors and response status codes. Upon receiving a response, the function parses the response data and constructs an <strong>HttpResponse</strong> object containing relevant information such as the response data, status code, status message, and headers.</p><p>Finally, <strong>send</strong> returns a promise that resolves with the <strong>HttpResponse</strong> object upon successful completion of the request or rejects with an error if an error occurs during the request process. This encapsulation of HTTP request logic provides a unified interface for making requests of different types while abstracting away complexities, promoting code reusability, readability, and maintainability.</p><h3>Step 5: Implement HTTP Methods (get, post, put, patch, delete)</h3><p>In this phase, we implement public methods for common HTTP methods (<strong>GET</strong>, <strong>POST</strong>, <strong>PUT</strong>, <strong>PATCH</strong>, <strong>DELETE</strong>) that utilize the <strong>send</strong> function.</p><pre>  public async get&lt;T&gt;(path: string, options: RequestOptions&lt;T&gt; = { method: &quot;GET&quot; }) {<br>    return this.send&lt;T&gt;(&quot;GET&quot;, path, options);<br>  }<br>  public async post&lt;T&gt;(path: string, body: T, options: RequestOptions&lt;T&gt; = { method: &quot;POST&quot; }) {<br>    return this.send&lt;T&gt;(&quot;POST&quot;, path, options, body);<br>  }<br>  public async put&lt;T&gt;(path: string, body: T, options: RequestOptions&lt;T&gt; = { method: &quot;PUT&quot; }) {<br>    return this.send&lt;T&gt;(&quot;PUT&quot;, path, options, body);<br>  }<br>  public async patch&lt;T&gt;(path: string, body: T, options: RequestOptions&lt;T&gt; = { method: &quot;PATCH&quot; }) {<br>    return this.send&lt;T&gt;(&quot;PATCH&quot;, path, options, body);<br>  }<br>  public async delete&lt;T&gt;(path: string, options: RequestOptions&lt;T&gt; = { method: &quot;DELETE&quot; }) {<br>    return this.send&lt;T&gt;(&quot;DELETE&quot;, path, options);<br>  }</pre><p>The <strong>post</strong>, <strong>put</strong>, <strong>patch</strong>, and <strong>delete</strong> methods within the <strong>HttpClient</strong> class provide convenience wrappers around the <strong>send</strong> function for making HTTP requests with specific HTTP methods. These methods abstract away the details of constructing and sending requests, making it easier to perform common CRUD operations (Create, Read, Update, Delete) in HTTP-based applications.</p><p>Each of these methods takes parameters such as the path, request body (for methods that support it), and additional options for customization. They internally call the <strong>send</strong> function with the appropriate HTTP method and pass along the provided parameters, ensuring consistency and adherence to HTTP standards.</p><ul><li><strong>post</strong>: This method sends an HTTP POST request to the specified path with the provided request body. It utilizes the <strong>send</strong> function with the HTTP method set to &quot;POST&quot; and passes the path, request body, and any additional options.</li><li><strong>put</strong>: Similar to <strong>post</strong>, this method sends an HTTP PUT request to the specified path with the provided request body. It uses the <strong>send</strong> function with the HTTP method set to &quot;PUT&quot; and passes the necessary parameters.</li><li><strong>patch</strong>: The <strong>patch</strong> method sends an HTTP PATCH request to the specified path with the provided request body. It internally invokes the <strong>send</strong> function with the HTTP method set to &quot;PATCH&quot; and passes the path, request body, and any additional options.</li><li><strong>delete</strong>: Finally, the <strong>delete</strong> method sends an HTTP DELETE request to the specified path. It calls the <strong>send</strong> function with the HTTP method set to &quot;DELETE&quot; and passes the path and any additional options.</li></ul><p>These methods encapsulate common HTTP request patterns, promoting code readability, reusability, and maintainability by providing a clear and consistent interface for performing CRUD operations in HTTP-based communication.</p><h3>Step 6: Usage</h3><p>Let’s explore how to utilize our HTTP client to make an HTTP request to <a href="https://dummyjson.com./"><strong>https://dummyjson.com</strong>.</a></p><pre>import { HttpClient } from &quot;./main&quot;;<br>const axios = new HttpClient(&quot;&lt;https://dummyjson.com/&gt;&quot;);<br><br>(async () =&gt; {<br>  try {<br>    const res = await axios.get(&quot;products/1&quot;);<br>    console.log(&quot;Result: &quot;, res);<br>  } catch (error) {<br>    console.log(&quot;Error featcting data: &quot;);<br>  }<br>})();</pre><p>After execution, the console output should resemble the following:</p><pre>Result:  {<br>  data: {<br>    id: 1,<br>    title: &#39;iPhone 9&#39;,<br>    description: &#39;An apple mobile which is nothing like apple&#39;,<br>    price: 549,<br>    discountPercentage: 12.96,<br>    rating: 4.69,<br>    stock: 94,<br>    brand: &#39;Apple&#39;,<br>    category: &#39;smartphones&#39;,<br>    thumbnail: &#39;&lt;https://cdn.dummyjson.com/product-images/1/thumbnail.jpg&gt;&#39;,<br>    images: [<br>      &#39;&lt;https://cdn.dummyjson.com/product-images/1/1.jpg&gt;&#39;,<br>      &#39;&lt;https://cdn.dummyjson.com/product-images/1/2.jpg&gt;&#39;,<br>      &#39;&lt;https://cdn.dummyjson.com/product-images/1/3.jpg&gt;&#39;,<br>      &#39;&lt;https://cdn.dummyjson.com/product-images/1/4.jpg&gt;&#39;,<br>      &#39;&lt;https://cdn.dummyjson.com/product-images/1/thumbnail.jpg&gt;&#39;<br>    ]<br>  },<br>  status: 200,<br>  statusMessage: &#39;OK&#39;,<br>  headers: {<br>    &#39;access-control-allow-origin&#39;: &#39;*&#39;,<br>    &#39;x-dns-prefetch-control&#39;: &#39;off&#39;,<br>    &#39;x-frame-options&#39;: &#39;SAMEORIGIN&#39;,<br>    &#39;strict-transport-security&#39;: &#39;max-age=15552000; includeSubDomains&#39;,<br>    &#39;x-download-options&#39;: &#39;noopen&#39;,<br>    &#39;x-content-type-options&#39;: &#39;nosniff&#39;,<br>    &#39;x-xss-protection&#39;: &#39;1; mode=block&#39;,<br>    &#39;x-ratelimit-limit&#39;: &#39;100&#39;,<br>    &#39;x-ratelimit-remaining&#39;: &#39;99&#39;,<br>    date: &#39;Thu, 22 Feb 2024 20:10:52 GMT&#39;,<br>    &#39;x-ratelimit-reset&#39;: &#39;1708632662&#39;,<br>    &#39;content-type&#39;: &#39;application/json; charset=utf-8&#39;,<br>    &#39;content-length&#39;: &#39;537&#39;,<br>    etag: &#39;W/&quot;219-Qb5jNZGxbDZom9db3B0+RJe2d+4&quot;&#39;,<br>    vary: &#39;Accept-Encoding&#39;,<br>    server: &#39;railway&#39;<br>  }<br>}</pre><h3>Challenges Ahead</h3><p>We have made significant progress in constructing our HTTP client, which can now send requests and handle responses. However, our current implementation represents only a fraction of the potential capabilities available. The purpose of this tutorial is to establish a foundation for creating a custom HTTP client. Below, I outline several enhancements that can be integrated to further solidify your understanding.</p><ol><li><strong>Timeout Implementation</strong></li></ol><ul><li><strong>Challenge</strong>: Implement timeout functionality to gracefully handle scenarios where responses take longer than expected.</li><li><strong>Impact</strong>: Enhance the client’s reliability by preventing prolonged waits for responses.</li></ul><p><strong>2. Interceptor Integration</strong></p><ul><li><strong>Challenge</strong>: Implement interceptors to manipulate requests or responses before they are sent or received.</li><li><strong>Impact</strong>: Provide flexibility to the client by intercepting and modifying requests or responses based on predefined logic.</li></ul><p><strong>3. Diverse Response Types</strong></p><ul><li><strong>Challenge</strong>: Expand the options for response types beyond the basics (text, document, media) to effectively handle diverse content formats.</li><li><strong>Impact</strong>: Enrich the client’s capabilities to seamlessly manage a wider range of content types, increasing versatility.</li></ul><p><strong>4. Error Handling and Retry Logic</strong></p><ul><li><strong>Challenge</strong>: Develop a robust error handling mechanism along with retry logic to manage transient errors and ensure more reliable communication with servers.</li><li><strong>Impact</strong>: Improve reliability by gracefully managing errors and enhancing the client’s resilience.</li></ul><p>Implementing these challenges and expanding the functionality will significantly boost your understanding of Node.js http module.</p><h3>Conclusion</h3><p>Engaging in project-based learning, such as building an HTTP client as demonstrated in this tutorial, is one of the most effective methods for solidifying newly acquired knowledge. While it is unlikely that you will often need to reinvent the wheel by constructing your own HTTP client in real-world scenarios, this exercise offers invaluable insights into the workings of Node.js http module.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6680582fcdfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring 5 Practical Use Cases for Node.js Crypto Library]]></title>
            <link>https://abubalogun.medium.com/exploring-4-practical-use-cases-for-node-js-crypto-library-8a92fc2b2bd0?source=rss-703e978f4870------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a92fc2b2bd0</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[back-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abubakar Balogun]]></dc:creator>
            <pubDate>Sun, 18 Feb 2024 15:35:39 GMT</pubDate>
            <atom:updated>2024-04-28T13:43:11.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laHah3_JsvPg5SzDmBUsuA.png" /></figure><p>Node.js remains a popular Javascript runtime environment for developing secure and scalable web applications. Its rich ecosystem of libraries and tools simplifies building applications, and one such built-in library is crypto. This library offers various cryptographic utilities for securing web applications.</p><p>In this article, we’ll explore 5 practical use cases for the Node.js Crypto library, covering topics like hashing, encryption, and signing. After reading this article, you’ll have a good understanding of various ways to leverage Node.js crypto library for application security.</p><h3>1. Generate Secure Tokens and Passwords</h3><p>When generating tokens like email verification codes, a common approach is to use Math.random(). However, Math.random() generates pseudo-random numbers, which means they are predictable and not suitable for security-critical applications. For such purposes, Node.js Crypto provides functions like crypto.randomBytes() to generate cryptographically secure random numbers, which are unpredictable and crucial for robust security. Here is how to use crypto.randomBytes() to generate a secured token:</p><pre>const crypto = require(&quot;crypto&quot;);<br><br>function generateSecureToken(length) {<br>    return new Promise((resolve, reject) =&gt; {<br>        crypto.randomBytes(length, (err, buffer) =&gt; {<br>            if (err) {<br>                reject(err);<br>            } else {<br>                const token = buffer.toString(&#39;hex&#39;);<br>                resolve(token);<br>            }<br>        });<br>    });<br>}<br><br>async function main() {<br>    try {<br>        const token = await generateSecureToken(16);<br>        console.log(&#39;Secure token:&#39;, token);<br>    } catch (error) {<br>        console.error(&#39;Error generating secure token:&#39;, error);<br>    }<br>}<br><br>main()</pre><h3>2. Generate Cryptographic Hashes</h3><p>One of the most common and vital applications of Node.js <em>crypto </em>module is generating cryptographic hash functions. A cryptographic hash function is a mathematical algorithm that transforms input data of any size into a fixed-size string of characters with certain cryptographic properties, such as preimage resistance, second preimage resistance, and collision resistance. These functions are invaluable in various security-critical scenarios such as password storage, digital signatures, and ensuring data integrity. Although hash functions like MD5 and RIPEMD exist, they are no longer recommended for cryptographic purposes due to vulnerabilities. Instead, secure hash functions like SHA-256 and SHA-3 should be used. In Node.js, the crypto library offers functionalities for generating cryptographic hashes.</p><p>Suppose you have sensitive data and you want to ensure its integrity or detect whether it has been tampered with. In such scenarios, cryptographic hashes play a crucial role. These hashes, generated using algorithms like SHA-256 provided by Node.js’s crypto library, provides a unique fingerprint for your data, making it computationally infeasible for anyone to tamper with the data without detection.</p><p>How to generate a cryptographic hash in Node.js using the SHA-256 algorithm:</p><pre>const crypto = require(&quot;crypto&quot;);<br><br>function generateHash(data) {<br>  const hash = crypto.createHash(&quot;sha256&quot;);<br>  hash.update(data);<br>  return hash.digest(&quot;hex&quot;);<br>}<br><br><br>const sensitiveData = &quot;This is my sensitive data.&quot;;<br><br>const hashValue = generateHash(sensitiveData);<br><br>console.log(&quot;Original Data:&quot;, sensitiveData);<br>console.log(&quot;Hash Value:&quot;, hashValue);<br><br>const tamperedData = &quot;This is my tampered data.&quot;;<br>const tamperedHashValue = generateHash(tamperedData);<br><br>console.log(&quot;\nTampered Data:&quot;, tamperedData);<br>console.log(&quot;Tampered Hash Value:&quot;, tamperedHashValue);<br><br>if (hashValue === tamperedHashValue) {<br>  console.log(&quot;\nThe data hasn&#39;t been tampered with.&quot;);<br>} else {<br>  console.log(&quot;\nThe data has been tampered with!&quot;);<br>}</pre><p>In this code, the generateHash() function takes sensitive data as input and utilizes the SHA-256 hashing algorithm to create a cryptographic hash. The resulting hash can then be used for various security purposes, including data integrity verification.</p><h3>3. Data Encryption &amp; Decryption</h3><p>There are various reasons why an application may require data encryption, this may include compliance requirements, secure data transfer, backup and disaster recovery, and more. To implement data encryption and decryption in Node.js, the crypto library can be used for the encryption and decryption processes. For instance, in a chat system where sensitive messages are exchanged, encryption can strengthen security. Below is a simple example showing how to encrypt and decrypt data using AES encryption with Node.js:</p><pre>const crypto = require(&quot;crypto&quot;);<br><br>function encryptSymmetric(plaintext, key, algorithm = &quot;aes-256-cbc&quot;) {<br>  const iv = crypto.randomBytes(16);<br>  const cipher = crypto.createCipheriv(algorithm, key, iv);<br>  const ciphertext =<br>    cipher.update(plaintext, &quot;utf8&quot;, &quot;hex&quot;) + cipher.final(&quot;hex&quot;);<br>  return { ciphertext, iv };<br>}<br><br>function decryptSymmetric(ciphertext, key, iv, algorithm = &quot;aes-256-cbc&quot;) {<br>  const decipher = crypto.createDecipheriv(algorithm, key, iv);<br>  const decrypted =<br>    decipher.update(ciphertext, &quot;hex&quot;, &quot;utf8&quot;) + decipher.final(&quot;utf8&quot;);<br>  return decrypted;<br>}<br><br>const plaintext = &quot;This is a secret message.&quot;;<br>const key = crypto.randomBytes(32);<br><br>const { ciphertext, iv } = encryptSymmetric(plaintext, key);<br><br>console.log(&quot;Encrypted data:&quot;, ciphertext);<br>console.log(&quot;IV:&quot;, iv.toString(&quot;hex&quot;));<br><br>const decryptedPlaintext = decryptSymmetric(ciphertext, key, iv);<br><br>console.log(&quot;Decrypted data:&quot;, decryptedPlaintext);</pre><h3>4. Digital signature</h3><p>A digital signature is like an electronic fingerprint for digital information. It uses cryptography to ensure authenticity, integrity, and Non-repudiation of information. The Node.js crypto library provides a functionality to cryptographically sign information. Consider a scenario where you have a Node.js application that communicates with a third-party API over the network. You want to ensure the authenticity and integrity of the data exchanged between your application and the API. Digital signatures can be used to achieve this.</p><p><strong>Example</strong>:</p><pre>const crypto = require(&quot;crypto&quot;);<br><br>function generateDigitalSignature(data, privateKey) {<br>  const sign = crypto.createSign(&quot;SHA256&quot;);<br>  sign.update(data);<br>  return sign.sign(<br>    {<br>      key: privateKey,<br>      padding: crypto.constants.RSA_PKCS1_PSS_PADDING,<br>      saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST,<br>    },<br>    &quot;base64&quot;<br>  );<br>}<br><br><br>function verifyDigitalSignature(data, signature, publicKey) {<br>  const verify = crypto.createVerify(&quot;SHA256&quot;);<br>  verify.update(data);<br>  return verify.verify(<br>    {<br>      key: publicKey,<br>      padding: crypto.constants.RSA_PKCS1_PSS_PADDING,<br>      saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST,<br>    },<br>    signature,<br>    &quot;base64&quot;<br>  );<br>}<br><br><br>const data = &quot;My sensitive data!&quot;;<br>const privateKey = crypto.generateKeyPairSync(&quot;rsa&quot;, {<br>  modulusLength: 2048,<br>  publicKeyEncoding: {<br>    type: &quot;pkcs1&quot;,<br>    format: &quot;pem&quot;,<br>  },<br>  privateKeyEncoding: {<br>    type: &quot;pkcs1&quot;,<br>    format: &quot;pem&quot;,<br>  },<br>}).privateKey;<br><br>const publicKey = crypto.generateKeyPairSync(&quot;rsa&quot;, {<br>  modulusLength: 2048,<br>  publicKeyEncoding: {<br>    type: &quot;pkcs1&quot;,<br>    format: &quot;pem&quot;,<br>  },<br>  privateKeyEncoding: {<br>    type: &quot;pkcs1&quot;,<br>    format: &quot;pem&quot;,<br>  },<br>}).publicKey;<br><br><br>const signature = generateDigitalSignature(data, privateKey);<br>console.log(&quot;Digital Signature:&quot;, signature);<br><br>const isSignatureValid = verifyDigitalSignature(data, signature, publicKey);<br>console.log(&quot;Is Signature Valid:&quot;, isSignatureValid);</pre><p>In the above code example, we have two functions: generateDigitalSignature() and verifyDigitalSignature(). The generateDigitalSignature() function takes data and a private key as input and returns the digital signature. The verifyDigitalSignature() function takes the data, signature, and public key as input and returns a boolean indicating whether the signature is valid.</p><h3>5. Password Hashing</h3><p>In addition to its cryptographic capabilities, the Node.js crypto module serves as a robust tool for password hashing. While bcrypt is a commonly favoured choice for password hashing in Node.js applications due to its security features, crypto offers a viable alternative.</p><p><strong>Example:</strong></p><pre>const crypto = require(&quot;crypto&quot;);<br><br>function hashPassword(password) {<br>  const salt = crypto.randomBytes(16).toString(&quot;hex&quot;);<br>  const hash = crypto<br>    .pbkdf2Sync(password, salt, 10000, 64, &quot;sha256&quot;)<br>    .toString(&quot;hex&quot;);<br>  return {<br>    salt: salt,<br>    hash: hash,<br>  };<br>}<br><br>const password = &quot;myPassword123&quot;;<br>const hashedPassword = hashPassword(password);<br>console.log(&quot;Salt:&quot;, hashedPassword.salt);<br>console.log(&quot;Hash:&quot;, hashedPassword.hash);</pre><p>In this code snippet, the <strong>hashPassword()</strong> function utilizes the <strong>crypto</strong> module to securely hash passwords. The process involves generating a cryptographically strong random salt, which is then combined with the password using the PBKDF2 algorithm with SHA-256 hashing. This ensures a high level of security and resistance against common attacks like rainbow table lookups and brute force attempts</p><h3>Conclusion</h3><p>This article has provided an insightful exploration of the capabilities of the Node.js Crypto library and its importance in improving the security of Node.js applications. Throughout the article, we’ve explored several core aspects, such as secure token generation, data encryption, digital signature generation, and password hashing.</p><p>Thanks for reading and I hope you find this article quite insightful.</p><p>You can read more about the Node.js crypto module and its other practical uses on the Node.js official website: <a href="https://nodejs.org/api/crypto.html">https://nodejs.org/api/crypto.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a92fc2b2bd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create Vercel-style Navigation Animation]]></title>
            <link>https://abubalogun.medium.com/how-to-create-vercel-style-navigation-animation-09d169961f12?source=rss-703e978f4870------2</link>
            <guid isPermaLink="false">https://medium.com/p/09d169961f12</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[framer-motion]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Abubakar Balogun]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 21:46:42 GMT</pubDate>
            <atom:updated>2024-02-15T21:54:11.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*AyAyqOs1d3sr8gcAyUX5qg.gif" /></figure><p>If you have been using Vercel for deployment for a while, you might have noticed a subtle animation when you hover or click on the sub-header on the dashboard’s page. It is a direction-aware animation that follows the direction of your mouse from the previous position to the destination position. Unlike intrusive animations that can complicate the user experience, this particular animation adds a touch of elegance without disrupting the overall flow. In this article, we will walk through the process of recreating this direction-aware animation inspired by Vercel in React using the Framer Motion library. The beauty of this approach is that it allows us to achieve the desired effect without resorting to manual DOM manipulations or introducing unnecessary side effects.</p><h3>Getting started</h3><p>To begin, create a new React app using Vite with the following command:</p><pre>npm create vite vercel-navgition</pre><p>After setting up the project, navigate to the project directory and start the development server:</p><pre>cd vercel-navigation<br><br>npm run dev</pre><p>Next, install the required dependencies — Framer Motion and React Router:</p><pre>npm install framer-motion react-router-dom</pre><h3>Configure React Roter</h3><p>Next, we configure React Router to handle navigation within our application. Open the <strong>main.jsx</strong> file and update it as follows:</p><pre>import React from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import App from &quot;./App.jsx&quot;;<br>import &quot;./index.css&quot;;<br>import { BrowserRouter } from &quot;react-router-dom&quot;;<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;BrowserRouter&gt;<br>      &lt;App /&gt;<br>    &lt;/BrowserRouter&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><h3>File structure</h3><pre>.<br>└── vercel-navigation/<br>    ├── public<br>    ├── assets<br>    └── src/<br>        ├── components/<br>        │   ├── Header.jsx<br>        │   └── SubHeader.jsx<br>        ├── App.jsx<br>        ├── index.css<br>        ├── main.jsx<br>        └── ...</pre><p>For this project, I created two components, a Header and a Subheader. This is because I want it to resemble Vercel dashboard page. You necessarily don’t need a Header component, as most animation will be done in the Subheader component.</p><h3>Header component:</h3><pre>const Header = () =&gt; {<br>  return (<br>    &lt;header className=&quot;container mx-auto flex justify-between items-center p-4 text-white&quot;&gt;<br>      &lt;div id=&quot;logo&quot; className=&quot;text-2xl font-bold&quot;&gt;<br>        Fercel<br>      &lt;/div&gt;<br>      &lt;div className=&quot;flex gap-3 items-center&quot;&gt;<br>        &lt;div<br>          id=&quot;account&quot;<br>          className=&quot;text-lg rounded-full p-1 border border-gray-500&quot;<br>        &gt;<br>          &lt;svg<br>            xmlns=&quot;&lt;http://www.w3.org/2000/svg&gt;&quot;<br>            fill=&quot;none&quot;<br>            viewBox=&quot;0 0 24 24&quot;<br>            strokeWidth={1.5}<br>            stroke=&quot;currentColor&quot;<br>            className=&quot;w-6 h-6&quot;<br>          &gt;<br>            &lt;path<br>              strokeLinecap=&quot;round&quot;<br>              strokeLinejoin=&quot;round&quot;<br>              d=&quot;M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0&quot;<br>            /&gt;<br>          &lt;/svg&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;div<br>            id=&quot;account&quot;<br>            className=&quot;text-lg rounded-full p-4 bg-gradient-to-tr from-blue-500 to-green-500&quot;<br>          &gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/header&gt;<br>  );<br>};</pre><pre>export default Header;</pre><p>The Header component represents the top section of our application, featuring a logo and an account indicator. I included the header component to mimic the Vercel dashboard page, although there is no other specific reason for its inclusion. Feel free to ignore it if you prefer.</p><h3>SubHeader Component</h3><pre>import { Link } from &quot;react-router-dom&quot;;<br><br>const SubHeader = () =&gt; {<br>  const navItems = [<br>    { id: &quot;overview&quot;, label: &quot;Overview&quot; },<br>    { id: &quot;integration&quot;, label: &quot;Integration&quot; },<br>    { id: &quot;analytics&quot;, label: &quot;Analytics&quot; },<br>    { id: &quot;notifications&quot;, label: &quot;Notifications&quot; },<br>    { id: &quot;billing&quot;, label: &quot;Billing&quot; },<br>  { id: &quot;settings&quot;, label: &quot;Settings&quot; },<br>    { id: &quot;security&quot;, label: &quot;Security&quot; },<br>  ];<br>  return (<br>    &lt;nav className=&quot;container mx-auto flex justify-between items-center  text-white border-b border-gray-500&quot;&gt;<br>      &lt;ul className=&quot;flex&quot;&gt;<br>        {navItems.map((nav) =&gt; (<br>          &lt;li<br>            key={nav.id}<br>            className=&quot;relative px-4 py-2&quot;<br>          &gt; <br>      &lt;Link<br>              href={`/${nav.id}`}<br>              className=&quot;text-gray-200&quot;<br>            &gt;<br>              {nav.label}<br>            &lt;/Link&gt;      <br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/nav&gt;<br>  );<br>};<br>export default SubHeader;</pre><p>The <strong>SubHeader</strong> component is where the animation takes place. It renders a list of navigation items, each with corresponding links. In this component, we create an array of navigation items <strong>navItems</strong>, map through the array to generate a list of items with links, and apply styling for the desired appearance.</p><p>On the browser, you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SrcGms_M_uv_0KAhAckvw.png" /></figure><h3>Creating Animation</h3><p>Observing the animation closely, you’ll notice two distinct animations in the navigation: the hover animation and the active animation. The hover animation is triggered when you hover over the navigation links, following the mouse direction. In contrast, the active animation is only triggered when you click on a navigation link, causing it to slide from the previous active link to the current one. Let’s break it down step by step.</p><h3>Implementing Hover animation.</h3><pre>import { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br>import { motion } from &quot;framer-motion&quot;;<br><br>const SubHeader = () =&gt; {<br>  const [hoveredNavItem, setHoveredNavItem] = useState(null);<br>  const navItems = [<br>    { id: &quot;overview&quot;, label: &quot;Overview&quot; },<br>    { id: &quot;integration&quot;, label: &quot;Integration&quot; },<br>    { id: &quot;settings&quot;, label: &quot;Settings&quot; },<br>    { id: &quot;profile&quot;, label: &quot;Profile&quot; },<br>    { id: &quot;analytics&quot;, label: &quot;Analytics&quot; },<br>    { id: &quot;notifications&quot;, label: &quot;Notifications&quot; },<br>    { id: &quot;billing&quot;, label: &quot;Billing&quot; },<br>    { id: &quot;security&quot;, label: &quot;Security&quot; },<br>  ];<br>  const handleNavItemHover = (navId: string) =&gt; {<br>    setHoveredNavItem(navId);<br>  };<br>  const handleNavItemMouseLeave = () =&gt; {<br>    setHoveredNavItem(null);<br>  };<br>  return (<br>    &lt;nav className=&quot;container mx-auto flex justify-between items-center  text-white border-b border-gray-500&quot;&gt;<br>      &lt;ul className=&quot;flex&quot;&gt;<br>        {navItems.map((nav) =&gt; (<br>          &lt;li<br>            key={nav.id}<br>            onMouseMove={() =&gt; handleNavItemHover(nav.id)}<br>            onMouseLeave={handleNavItemMouseLeave}<br>            className=&quot;relative px-4 py-2&quot;<br>          &gt;<br>            &lt;Link<br>              to={`/${nav.id}`}<br>              className=&quot;relative z-20 text-white<br>              &quot;<br>            &gt;<br>              {nav.label}<br>            &lt;/Link&gt;<br>            {hoveredNavItem === nav.id &amp;&amp; (<br>              &lt;motion.span<br>                layoutId=&quot;hover&quot;<br>                transition={{ type: &quot;spring&quot;, duration: 0.4 }}<br>                className=&quot;absolute inset-0  bg-gray-600/50 rounded-lg&quot;<br>              &gt;&lt;/motion.span&gt;<br>            )}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/nav&gt;<br>  );<br>};<br>export default SubHeader;</pre><p>We use a <strong>useState</strong> hook to track the currently hovered navigation item. Two event handlers are defined: <strong>handleNavItemHover</strong> is triggered when hovering over a navigation item, updating the <strong>hoveredNavItem</strong> state with the corresponding navigation item&#39;s id. <strong>handleNavItemMouseLeave</strong> resets <strong>hoveredNavItem</strong> to <strong>null</strong> when the mouse leaves a navigation item.</p><p>Each list item contains a link (<strong>&lt;Link&gt;</strong>) directing to a specific path. Upon hovering over a navigation item, a transparent overlay (<strong>&lt;motion.span&gt;</strong>) with a hover animation is displayed using the <strong>motion</strong> library. The <strong>layoutId</strong> property ensures smooth transitions, while the <strong>transition</strong> property defines the animation&#39;s type and duration. Positioned absolutely, the transparent overlay covers the entire list item, creating an engaging hover effect.</p><h3>Implementing Active animation</h3><pre>import { useState } from &quot;react&quot;;<br>import { Link } from &quot;react-router-dom&quot;;<br>import { motion } from &quot;framer-motion&quot;;<br><br>const SubHeader = () =&gt; {<br>  const [activeNavItem, setActiveNavItem] = useState(null);<br>  const [hoveredNavItem, setHoveredNavItem] = useState(null);<br>  const navItems = [<br>    { id: &quot;overview&quot;, label: &quot;Overview&quot; },<br>    { id: &quot;integration&quot;, label: &quot;Integration&quot; },<br>    { id: &quot;settings&quot;, label: &quot;Settings&quot; },<br>    { id: &quot;profile&quot;, label: &quot;Profile&quot; },<br>    { id: &quot;analytics&quot;, label: &quot;Analytics&quot; },<br>    { id: &quot;notifications&quot;, label: &quot;Notifications&quot; },<br>    { id: &quot;billing&quot;, label: &quot;Billing&quot; },<br>    { id: &quot;security&quot;, label: &quot;Security&quot; },<br>  ];<br>  const handleNavItemClick = (navId) =&gt; {<br>    setActiveNavItem(navId);<br>    setHoveredNavItem(null);<br>  };<br>  const handleNavItemHover = (navId) =&gt; {<br>    setHoveredNavItem(navId);<br>  };<br>  const handleNavItemMouseLeave = () =&gt; {<br>    setHoveredNavItem(null);<br>  };<br>  return (<br>    &lt;nav className=&quot;container mx-auto flex justify-between items-center  text-white border-b border-gray-500&quot;&gt;<br>      &lt;ul className=&quot;flex&quot;&gt;<br>        {navItems.map((nav) =&gt; (<br>          &lt;li<br>            key={nav.id}<br>            onClick={()=&gt; handleNavItemClick(nav.id)}<br>            onMouseMove={() =&gt; handleNavItemHover(nav.id)}<br>            onMouseLeave={handleNavItemMouseLeave}<br>            className=&quot;relative px-4 py-2&quot;<br>          &gt;<br>            &lt;Link<br>              to={`/${nav.id}`}<br>              className={`relative z-20  ${<br>                activeNavItem === nav.id ? &quot;text-gray-200&quot; : &quot;text-gray-500&quot;<br>              }`}<br>            &gt;<br>              {nav.label}<br>            &lt;/Link&gt;<br>            {hoveredNavItem === nav.id &amp;&amp; (<br>              &lt;motion.span<br>                layoutId=&quot;hover&quot;<br>                transition={{ type: &quot;spring&quot;, duration: 0.4 }}<br>                className=&quot;absolute inset-0  bg-gray-600/50 rounded-lg&quot;<br>              &gt;&lt;/motion.span&gt;<br>            )}<br>            {activeNavItem === nav.id &amp;&amp; (<br>              &lt;motion.span<br>                layoutId=&quot;active&quot;<br>                transition={{ type: &quot;spring&quot;, duration: 0.5 }}<br>                className=&quot;z-10 absolute inset-0 border-b-2 &quot;<br>              &gt;&lt;/motion.span&gt;<br>            )}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/nav&gt;<br>  );<br>};<br>export default SubHeader;</pre><p>Similar to the hover animation implementation, we introduce a useState hook to track the state of the active link. When a navigation item is clicked, the handleNavItemClick function is called, updating the activeNavItem state to the clicked item’s ID. We maintain consistency with the hover animation, ensuring smooth transitions and visual cues for user interaction.</p><h3>Storing the state in the URL</h3><p>To maintain the active state even after a page reload or component mount, we need a solution beyond <strong>useState</strong>. One effective approach is to synchronize the active state with the URL. By doing so, the state persists across page reloads and component mounts.</p><p>We utilize React Router’s <strong>useLocation</strong> hook to access the current URL. Then, we employ the <strong>useEffect</strong> hook to update the active state whenever the URL changes. This method ensures that the active state remains synchronized with the URL, providing a more robust and efficient solution compared to initializing the active state with <strong>useState</strong>.</p><pre>import { useEffect, useState } from &quot;react&quot;;<br>import { Link, useLocation } from &quot;react-router-dom&quot;;<br>import { motion } from &quot;framer-motion&quot;;<br><br>const SubHeader = () =&gt; {<br>  const location = useLocation();<br>  const [activeNavItem, setActiveNavItem] = useState(null);<br>  const [hoveredNavItem, setHoveredNavItem] = useState(null);<br><br>  const navItems = [<br>    { id: &quot;overview&quot;, label: &quot;Overview&quot; },<br>    { id: &quot;integration&quot;, label: &quot;Integration&quot; },<br>    { id: &quot;settings&quot;, label: &quot;Settings&quot; },<br>    { id: &quot;profile&quot;, label: &quot;Profile&quot; },<br>    { id: &quot;analytics&quot;, label: &quot;Analytics&quot; },<br>    { id: &quot;notifications&quot;, label: &quot;Notifications&quot; },<br>    { id: &quot;billing&quot;, label: &quot;Billing&quot; },<br>    { id: &quot;security&quot;, label: &quot;Security&quot; },<br>  ];<br><br>  const handleNavItemHover = (navId: string) =&gt; {<br>    setHoveredNavItem(navId);<br>  };<br><br>  const handleNavItemMouseLeave = () =&gt; {<br>    setHoveredNavItem(null);<br>  };<br><br>  useEffect(() =&gt; {<br>    // Update activeNavItem when location changes<br>    setActiveNavItem(location.pathname.substring(1));<br>  }, [location.pathname]);<br><br>  return (<br>    &lt;nav className=&quot;container mx-auto flex justify-between items-center  text-white border-b border-gray-500&quot;&gt;<br>      &lt;ul className=&quot;flex&quot;&gt;<br>        {navItems.map((nav) =&gt; (<br>          &lt;li<br>            key={nav.id}<br>            onMouseMove={() =&gt; handleNavItemHover(nav.id)}<br>            onMouseLeave={handleNavItemMouseLeave}<br>            className=&quot;relative px-4 py-2&quot;<br>          &gt;<br>            &lt;Link<br>              to={`/${nav.id}`}<br>              className={`relative z-20  ${<br>                activeNavItem === nav.id ? &quot;text-gray-200&quot; : &quot;text-gray-500&quot;<br>              }`}<br>            &gt;<br>              {nav.label}<br>            &lt;/Link&gt;<br>            {hoveredNavItem === nav.id &amp;&amp; (<br>              &lt;motion.span<br>                layoutId=&quot;hover&quot;<br>                transition={{ type: &quot;spring&quot;, duration: 0.4 }}<br>                className=&quot;absolute inset-0  bg-gray-600/50 rounded-lg&quot;<br>              &gt;&lt;/motion.span&gt;<br>            )}<br>            {activeNavItem === nav.id &amp;&amp; (<br>              &lt;motion.span<br>                layoutId=&quot;active&quot;<br>                transition={{ type: &quot;spring&quot;, duration: 0.5 }}<br>                className=&quot;z-10 absolute inset-0 border-b-2 &quot;<br>              &gt;&lt;/motion.span&gt;<br>            )}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/nav&gt;<br>  );<br>};<br><br>export default SubHeader;</pre><p>We leverage React Router’s functionality and the useEffect hooks to synchronize and persist the animation state even after page refresh.</p><h3>Conclusion</h3><p>This tutorial has showcased the implementation of direction-aware animation inspired by Vercel. By following the steps outlined here, you can enhance the visual appeal and interactivity of your web applications. The integration of Framer motion and React Router libraries allows for seamless animation transitions based on user interaction. I trust that you have found this tutorial informative and insightful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09d169961f12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>