<?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"><channel><title><![CDATA[Ashish Maurya's Blog]]></title><description><![CDATA[Hey I am Ashish Maurya. A freelance web developer and problem solver, I have been working with Reactjs and similar frontend technology for a while. I'm also well versed with backend technologies.]]></description><link>https://blog.theashishmaurya.me</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1625284808708/R62bxDcXq.png</url><title>Ashish Maurya&apos;s Blog</title><link>https://blog.theashishmaurya.me</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 22 Apr 2026 18:02:02 GMT</lastBuildDate><atom:link href="https://blog.theashishmaurya.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Build a Neural Network from Scratch in Go: Part 1]]></title><description><![CDATA[How to Build a Neural Network from Scratch in Go: Part 1 - Understanding and Reading the MNIST Dataset
Hey there! Welcome to the first part of our exciting series on building a neural network from scratch using Go. If you’re new to machine learning o...]]></description><link>https://blog.theashishmaurya.me/how-to-build-a-neural-network-from-scratch-in-go-part-1</link><guid isPermaLink="true">https://blog.theashishmaurya.me/how-to-build-a-neural-network-from-scratch-in-go-part-1</guid><category><![CDATA[neural networks]]></category><category><![CDATA[golang]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Deep Learning]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Wed, 05 Mar 2025 14:12:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ZiQkhI7417A/upload/db7b3861ee8613f482c5b02d9c4b0b85.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-how-to-build-a-neural-network-from-scratch-in-go-part-1-understanding-and-reading-the-mnist-dataset">How to Build a Neural Network from Scratch in Go: Part 1 - Understanding and Reading the MNIST Dataset</h1>
<p>Hey there! Welcome to the first part of our exciting series on building a neural network from scratch using Go. If you’re new to machine learning or Go, don’t worry—we’re going to take this step by step, starting with the foundation: the data. In this article, we’ll dive into the MNIST dataset, a classic collection of handwritten digits that’s perfect for learning the ropes of neural networks. Our goal today is to get the dataset, understand its structure, and write some Go code to read it. Plus, we’ll unpack some key concepts like big and little endian and one-hot encoding along the way.</p>
<p>Here’s what we’ll cover:</p>
<ul>
<li><p><strong>What is the MNIST Dataset?</strong> A quick intro to this famous dataset.</p>
</li>
<li><p><strong>How to Get the MNIST Dataset</strong> Where and how to download it.</p>
</li>
<li><p><strong>The Structure of MNIST</strong> Breaking down its binary format.</p>
</li>
<li><p><strong>Reading MNIST in Go</strong> Walking through the code to load the data.</p>
</li>
<li><p><strong>Key Concepts</strong> Explaining big and little endian, one-hot encoding, and alternatives.</p>
</li>
<li><p><strong>Conclusion</strong> Wrapping up and looking ahead.</p>
</li>
</ul>
<p>Let’s get started!</p>
<hr />
<h2 id="heading-what-is-the-mnist-dataset">What is the MNIST Dataset?</h2>
<p>Imagine you’re teaching a kid to recognize numbers. You’d show them lots of examples of handwritten digits, right? That’s exactly what the MNIST dataset does for machines. MNIST stands for Modified National Institute of Standards and Technology dataset, and it’s a collection of 70,000 grayscale images of handwritten digits (0 through 9). Each image is a tidy 28x28 pixels, and it comes with a label telling us which digit it is.</p>
<p>The dataset is split into two parts:</p>
<ul>
<li><p><strong>Training Set</strong>: 60,000 images to teach our neural network.</p>
</li>
<li><p><strong>Test Set</strong>: 10,000 images to check how well it learned.</p>
</li>
</ul>
<p>MNIST is like the "Hello World" of machine learning—simple, well-organized, and widely used. It’s perfect for our first adventure into building a neural network from scratch.</p>
<hr />
<h2 id="heading-how-to-get-the-mnist-dataset">How to Get the MNIST Dataset</h2>
<p>Ready to grab the data? Head over to <a target="_blank" href="http://yann.lecun.com/exdb/mnist/">Yann LeCun’s MNIST page</a>. You’ll find four files to download:</p>
<ul>
<li><p><code>train-images-idx3-ubyte.gz</code>: The 60,000 training images.</p>
</li>
<li><p><code>train-labels-idx1-ubyte.gz</code>: The labels for the training images.</p>
</li>
<li><p><code>t10k-images-idx3-ubyte.gz</code>: The 10,000 test images.</p>
</li>
<li><p><code>t10k-labels-idx1-ubyte.gz</code>: The labels for the test images.</p>
</li>
</ul>
<p>These files are compressed with gzip, so after downloading, you’ll need to unzip them. On a Mac or Linux, you can run <code>gunzip filename.gz</code> in the terminal. On Windows, tools like 7-Zip or WinRAR work great. Once unzipped, you’ll have four binary files with extensions like <code>.idx3-ubyte</code> and <code>.idx1-ubyte</code>. Place them in a folder called <code>mnist/</code> in your project directory, and we’re good to go!</p>
<hr />
<h2 id="heading-the-structure-of-mnist">The Structure of MNIST</h2>
<p>Before we jump into coding, let’s peek under the hood of these binary files. MNIST uses a custom format called IDX, and it’s pretty straightforward once you get the hang of it.</p>
<h3 id="heading-image-files">Image Files</h3>
<p>The image files (<code>train-images-idx3-ubyte</code> and <code>t10k-images-idx3-ubyte</code>) start with a 16-byte header:</p>
<ul>
<li><p><strong>Magic Number (4 bytes)</strong>: A special number (2051) that identifies the file type.</p>
</li>
<li><p><strong>Number of Images (4 bytes)</strong>: 60,000 for training, 10,000 for testing.</p>
</li>
<li><p><strong>Rows (4 bytes)</strong>: Always 28.</p>
</li>
<li><p><strong>Columns (4 bytes)</strong>: Also 28.</p>
</li>
</ul>
<p>After the header, the pixel data follows: 784 bytes per image (28 × 28), with each byte representing a pixel’s grayscale value from 0 (black) to 255 (white). Picture it as one long row of pixels for each image, like a flattened version of a 28x28 grid.</p>
<h3 id="heading-label-files">Label Files</h3>
<p>The label files (<code>train-labels-idx1-ubyte</code> and <code>t10k-labels-idx1-ubyte</code>) are simpler, with an 8-byte header:</p>
<ul>
<li><p><strong>Magic Number (4 bytes)</strong>: 2049 this time.</p>
</li>
<li><p><strong>Number of Labels (4 bytes)</strong>: Matches the number of images (60,000 or 10,000).</p>
</li>
</ul>
<p>Then, it’s just one byte per label, giving us the digit (0–9) for each corresponding image.</p>
<p>One catch: all these multi-byte numbers (like the magic number or number of images) are stored in <strong>big-endian</strong> byte order. Don’t worry if that sounds unfamiliar—we’ll explain it soon!</p>
<hr />
<h2 id="heading-reading-mnist-in-go">Reading MNIST in Go</h2>
<p>Now for the fun part: let’s write some Go code to read this data. We’ll create functions to load the images and labels, making sure they’re ready for our neural network. The code below is an improved version of what you provided, with better error handling and a cleaner structure.</p>
<p>Create a file called <code>reader.go</code> in a <code>reader</code> package:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> reader

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"encoding/binary"</span>
    <span class="hljs-string">"errors"</span>
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"os"</span>
)

<span class="hljs-keyword">const</span> (
    trainingImagesPath = <span class="hljs-string">"mnist/train-images.idx3-ubyte"</span>
    trainingLabelsPath = <span class="hljs-string">"mnist/train-labels.idx1-ubyte"</span>
    testImagesPath     = <span class="hljs-string">"mnist/t10k-images.idx3-ubyte"</span>
    testLabelsPath     = <span class="hljs-string">"mnist/t10k-labels.idx1-ubyte"</span>
)

<span class="hljs-comment">// ReadImages reads both training and test images from MNIST dataset</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ReadImages</span><span class="hljs-params">()</span> <span class="hljs-params">(trainingImages [][]<span class="hljs-keyword">float64</span>, testImages [][]<span class="hljs-keyword">float64</span>, err error)</span></span> {
    trainingImages, err = readMnistImages(trainingImagesPath, <span class="hljs-number">60000</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, err
    }

    testImages, err = readMnistImages(testImagesPath, <span class="hljs-number">10000</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, err
    }

    <span class="hljs-keyword">return</span> trainingImages, testImages, <span class="hljs-literal">nil</span>
}

<span class="hljs-comment">// ReadLabels reads both training and test labels from MNIST dataset</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ReadLabels</span><span class="hljs-params">()</span> <span class="hljs-params">(trainingLabels [][]<span class="hljs-keyword">float64</span>, testLabels [][]<span class="hljs-keyword">float64</span>, err error)</span></span> {
    trainingLabels, err = readMnistLabels(trainingLabelsPath, <span class="hljs-number">60000</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, err
    }

    testLabels, err = readMnistLabels(testLabelsPath, <span class="hljs-number">10000</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, err
    }

    <span class="hljs-keyword">return</span> trainingLabels, testLabels, <span class="hljs-literal">nil</span>
}

<span class="hljs-comment">// Generic function to read image data from a file</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readMnistImages</span><span class="hljs-params">(filepath <span class="hljs-keyword">string</span>, expectedImages <span class="hljs-keyword">uint32</span>)</span> <span class="hljs-params">([][]<span class="hljs-keyword">float64</span>, error)</span></span> {
    <span class="hljs-comment">// Open the file</span>
    file, err := os.Open(filepath)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> file.Close()

    <span class="hljs-comment">// Read the header</span>
    header := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, <span class="hljs-number">16</span>)
    _, err = file.Read(header)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, err
    }

    <span class="hljs-comment">// Parse header information</span>
    magicNumber := binary.BigEndian.Uint32(header[<span class="hljs-number">0</span>:<span class="hljs-number">4</span>])
    numImages := binary.BigEndian.Uint32(header[<span class="hljs-number">4</span>:<span class="hljs-number">8</span>])
    numRows := binary.BigEndian.Uint32(header[<span class="hljs-number">8</span>:<span class="hljs-number">12</span>])
    numCols := binary.BigEndian.Uint32(header[<span class="hljs-number">12</span>:<span class="hljs-number">16</span>])

    fmt.Println(<span class="hljs-string">"Image file:"</span>, filepath)
    fmt.Println(<span class="hljs-string">"Magic number:"</span>, magicNumber, <span class="hljs-string">"Images:"</span>, numImages, <span class="hljs-string">"Rows:"</span>, numRows, <span class="hljs-string">"Columns:"</span>, numCols)

    <span class="hljs-comment">// Validate header</span>
    <span class="hljs-keyword">if</span> magicNumber != <span class="hljs-number">2051</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, errors.New(<span class="hljs-string">"invalid magic number for image file"</span>)
    }

    <span class="hljs-keyword">if</span> numImages != expectedImages {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, fmt.Errorf(<span class="hljs-string">"expected %d images, but found %d"</span>, expectedImages, numImages)
    }

    <span class="hljs-comment">// Read image data</span>
    images := <span class="hljs-built_in">make</span>([][]<span class="hljs-keyword">float64</span>, numImages)
    <span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> images {
        images[i] = <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">float64</span>, numRows*numCols)
        tempImage := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, numRows*numCols)
        _, err := file.Read(tempImage)
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, err
        }

        <span class="hljs-comment">// Normalize pixel values to [0,1]</span>
        <span class="hljs-keyword">for</span> j := <span class="hljs-keyword">range</span> tempImage {
            images[i][j] = <span class="hljs-keyword">float64</span>(tempImage[j]) / <span class="hljs-number">255.0</span>
        }
    }

    <span class="hljs-keyword">return</span> images, <span class="hljs-literal">nil</span>
}

<span class="hljs-comment">// Generic function to read label data from a file</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">readMnistLabels</span><span class="hljs-params">(filepath <span class="hljs-keyword">string</span>, expectedLabels <span class="hljs-keyword">uint32</span>)</span> <span class="hljs-params">([][]<span class="hljs-keyword">float64</span>, error)</span></span> {
    <span class="hljs-comment">// Open the file</span>
    file, err := os.Open(filepath)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> file.Close()

    <span class="hljs-comment">// Read the header</span>
    header := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, <span class="hljs-number">8</span>)
    _, err = file.Read(header)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, err
    }

    <span class="hljs-comment">// Parse header information</span>
    magicNumber := binary.BigEndian.Uint32(header[<span class="hljs-number">0</span>:<span class="hljs-number">4</span>])
    numLabels := binary.BigEndian.Uint32(header[<span class="hljs-number">4</span>:<span class="hljs-number">8</span>])

    fmt.Println(<span class="hljs-string">"Label file:"</span>, filepath)
    fmt.Println(<span class="hljs-string">"Magic number:"</span>, magicNumber, <span class="hljs-string">"Labels:"</span>, numLabels)

    <span class="hljs-comment">// Validate header</span>
    <span class="hljs-keyword">if</span> magicNumber != <span class="hljs-number">2049</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, errors.New(<span class="hljs-string">"invalid magic number for label file"</span>)
    }

    <span class="hljs-keyword">if</span> numLabels != expectedLabels {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, fmt.Errorf(<span class="hljs-string">"expected %d labels, but found %d"</span>, expectedLabels, numLabels)
    }

    <span class="hljs-comment">// Read label data</span>
    labels := <span class="hljs-built_in">make</span>([][]<span class="hljs-keyword">float64</span>, numLabels)
    <span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> labels {
        <span class="hljs-comment">// One-hot encoding for digits 0-9</span>
        labels[i] = <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">float64</span>, <span class="hljs-number">10</span>)
        <span class="hljs-keyword">var</span> label <span class="hljs-keyword">uint8</span>
        err := binary.Read(file, binary.BigEndian, &amp;label)
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, err
        }
        labels[i][label] = <span class="hljs-number">1.0</span>
    }

    <span class="hljs-keyword">return</span> labels, <span class="hljs-literal">nil</span>
}

<span class="hljs-comment">// ReadData is the original function for backward compatibility</span>
<span class="hljs-comment">// It reads both images and labels from MNIST dataset</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">ReadData</span><span class="hljs-params">()</span> <span class="hljs-params">(trainingImages [][]<span class="hljs-keyword">float64</span>, trainingLabels [][]<span class="hljs-keyword">float64</span>,
    testImages [][]<span class="hljs-keyword">float64</span>, testLabels [][]<span class="hljs-keyword">float64</span>, err error)</span></span> {

    trainingImages, testImages, err = ReadImages()
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, err
    }

    trainingLabels, testLabels, err = ReadLabels()
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, <span class="hljs-literal">nil</span>, err
    }

    <span class="hljs-keyword">return</span> trainingImages, trainingLabels, testImages, testLabels, <span class="hljs-literal">nil</span>
}
</code></pre>
<h3 id="heading-how-it-works">How It Works</h3>
<p>Let’s break this down:</p>
<ol>
<li><p><code>readMNISTImages</code>:</p>
<ul>
<li><p>Opens the image file and reads the 16-byte header.</p>
</li>
<li><p>Checks the magic number (2051) and ensures we have the expected number of images and dimensions (28x28).</p>
</li>
<li><p>Reads 784 bytes per image, normalizes each pixel to a value between 0 and 1 (by dividing by 255), and stores them in a 2D slice.</p>
</li>
</ul>
</li>
<li><p><code>readMNISTLabels</code>:</p>
<ul>
<li><p>Opens the label file and reads the 8-byte header.</p>
</li>
<li><p>Verifies the magic number (2049) and number of labels.</p>
</li>
<li><p>Reads one byte per label and converts each into a 10-element one-hot encoded vector (e.g., digit 3 becomes <code>[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]</code>).</p>
</li>
</ul>
</li>
<li><p><code>ReadData</code>:</p>
<ul>
<li>Ties it all together by calling the above functions with the correct file paths and parameters.</li>
</ul>
</li>
</ol>
<p><strong>Pro Tip</strong>: Notice the <code>defer file.Close()</code>? In Go, this ensures the file closes when the function exits, even if an error occurs. Also, we’ve replaced <code>log.Fatal</code> with proper error returns so the caller can decide what to do—much friendlier for reusable code!</p>
<hr />
<h2 id="heading-key-concepts">Key Concepts</h2>
<h3 id="heading-big-and-little-endian">Big and Little Endian</h3>
<p>Ever wondered how computers store numbers bigger than a single byte? It’s all about byte order, and there are two flavors:</p>
<ul>
<li><p><strong>Big-Endian</strong>: The "big" end (most significant byte) comes first. For example, the number 2051 is stored as <code>00 00 08 03</code>. It’s like reading a number from left to right in some cultures.</p>
</li>
<li><p><strong>Little-Endian</strong>: The "little" end (least significant byte) comes first, so 2051 would be <code>03 08 00 00</code>. Think of it as right-to-left.</p>
</li>
</ul>
<p>MNIST uses big-endian, which is why we use <code>binary.BigEndian</code> in our Go code to read those 4-byte integers correctly. Your computer might be little-endian (most modern PCs are), so this conversion is crucial.</p>
<h3 id="heading-one-hot-encoding">One-Hot Encoding</h3>
<p>Our labels are digits from 0 to 9, but neural networks like to work with probabilities. One-hot encoding turns each label into a 10-element vector where only one position is 1, and the rest are 0s. For example:</p>
<ul>
<li><p>Label 2 becomes <code>[0, 0, 1, 0, 0, 0, 0, 0, 0, 0]</code>.</p>
</li>
<li><p>Label 7 becomes <code>[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]</code>.</p>
</li>
</ul>
<p>It’s like flipping on one light switch out of ten to signal the digit. This matches our network’s output layer, making it easier to compute errors during training.</p>
<h3 id="heading-alternatives-to-one-hot-encoding">Alternatives to One-Hot Encoding</h3>
<p>One-hot encoding isn’t the only game in town. Here are some other options:</p>
<ul>
<li><p><strong>Label Encoding</strong>: Just use the integer itself (e.g., 0 for 0, 1 for 1, etc.). Simple, but it implies an order (like 9 is "greater" than 0), which can confuse neural networks for classification tasks.</p>
</li>
<li><p><strong>Binary Encoding</strong>: Represent digits in binary (e.g., 3 as <code>011</code>, 9 as <code>1001</code>). Uses fewer dimensions but still assumes some structure.</p>
</li>
<li><p><strong>Embeddings</strong>: Fancy learned vectors that capture relationships between categories. Great for complex data like words, less so for our simple digits.</p>
</li>
</ul>
<p>For MNIST, one-hot encoding is the go-to because it’s clear and works seamlessly with our network’s output.</p>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Phew, we did it! In this first part, we’ve grabbed the MNIST dataset, decoded its binary structure, and written Go code to read it into memory. We’ve got our images normalized and our labels one-hot encoded, ready for action. Plus, we’ve demystified big and little endian and explored why one-hot encoding is our friend.</p>
<p>Next time, we’ll start building the neural network itself—layers, weights, and all that jazz. So stick around, keep coding, and let’s see where this journey takes us. Have questions or ideas? Drop them below—let’s learn together!</p>
]]></content:encoded></item><item><title><![CDATA[Bcrypt: The Unsung Hero of Password Security]]></title><description><![CDATA[In the digital age, where data breaches are as common as coffee spills, one cryptographic algorithm stands out for its robustness in securing our passwords: bcrypt. Let's dive into the world of bcrypt hashing, uncovering its mechanics, the role of sa...]]></description><link>https://blog.theashishmaurya.me/bcrypt-the-unsung-hero-of-password-security</link><guid isPermaLink="true">https://blog.theashishmaurya.me/bcrypt-the-unsung-hero-of-password-security</guid><category><![CDATA[backend]]></category><category><![CDATA[passwords]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sat, 23 Nov 2024 12:34:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zvHhKiVuR9M/upload/c1d81fd3017068426d9c0b4ac6f15cc3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the digital age, where data breaches are as common as coffee spills, one cryptographic algorithm stands out for its robustness in securing our passwords: <strong>bcrypt</strong>. Let's dive into the world of bcrypt hashing, uncovering its mechanics, the role of salting, and how it keeps our credentials safe from prying eyes.</p>
<h3 id="heading-what-is-bcrypt">What is Bcrypt?</h3>
<p>Bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher. Its primary goal? To protect passwords in storage against offline attacks. Here's why bcrypt isn't just another algorithm:</p>
<ul>
<li><p><strong>Adaptive Hashing</strong>: bcrypt allows for variable computational cost, meaning you can increase its security over time as computing power advances.</p>
</li>
<li><p><strong>Built-in Salt</strong>: Each password hash includes a unique salt, reducing the effectiveness of rainbow tables and ensuring that identical passwords have different hashes.</p>
</li>
</ul>
<h3 id="heading-the-structure-of-a-bcrypt-hash">The Structure of a Bcrypt Hash</h3>
<pre><code class="lang-text">$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy
</code></pre>
<ul>
<li><p><strong>2a</strong> : This is the version of bcrypt. Think of it as the type of bread for your sandwich.</p>
</li>
<li><p><strong>10</strong>: Represents the cost factor. It's like deciding how much effort goes into making the sandwich. A higher number means more rounds of hashing, making it tougher for someone to crack.</p>
</li>
<li><p><strong>Salt</strong>: N9qo8uLOickgx2ZMRZoMye - This is the unique seasoning. Each password gets its own special blend, ensuring no two sandwiches taste the same.</p>
</li>
<li><p><strong>Hash</strong>: IjZAgcfl7p92ldGxad68LJZdL17lhWy - This is the actual hashed password, the main ingredient after being processed with the salt.</p>
</li>
</ul>
<h3 id="heading-how-does-bcrypt-work">How Does Bcrypt Work?</h3>
<p>Here's a step-by-step breakdown:</p>
<ol>
<li><p><strong>Password Input</strong>: When you type in your password, it's like ordering a custom sandwich.</p>
<pre><code class="lang-go"> password := []<span class="hljs-keyword">byte</span>(<span class="hljs-string">"yourpassword"</span>)
</code></pre>
</li>
<li><p><strong>Hashing with Salt</strong>: bcrypt generates a salt for each password. This is like the chef adding a secret ingredient.</p>
<pre><code class="lang-go"> hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
 <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
     log.Fatal(err)
 }
</code></pre>
</li>
<li><p><strong>Storing the Hash</strong>: The hash, including the salt, is stored in your database. When someone tries to log in:</p>
<pre><code class="lang-go"> storedHash := bcryptHashFromDatabase <span class="hljs-comment">// This would be read from your storage</span>
</code></pre>
</li>
<li><p><strong>Password Verification</strong>:</p>
<ul>
<li><p>The salt from storedHash is extracted (like reading the recipe).</p>
</li>
<li><p>The provided password is hashed using this salt.</p>
</li>
<li><p>The two hashes are compared in constant time to prevent timing attacks.</p>
</li>
</ul>
</li>
</ol>
<pre><code class="lang-go">    err := bcrypt.CompareHashAndPassword(storedHash, providedPassword)
    <span class="hljs-keyword">if</span> err == <span class="hljs-literal">nil</span> {
        fmt.Println(<span class="hljs-string">"Login successful"</span>)
    } <span class="hljs-keyword">else</span> {
        fmt.Println(<span class="hljs-string">"Login failed"</span>)
    }
</code></pre>
<h3 id="heading-engaging-with-bcrypt">Engaging with Bcrypt</h3>
<p>To make this more visual, think of bcrypt like cooking:</p>
<ul>
<li><p><strong>Salting</strong>: Just like adding spices to a dish, bcrypt adds a unique flavor (salt) to each password, making each hash unique.</p>
</li>
<li><p><strong>Slow Cooking</strong>: bcrypt intentionally takes time to hash (the cost factor). This slow cooking process is a security feature, making brute-force attacks less feasible.</p>
</li>
<li><p><strong>Taste Test</strong>: When you try to log in, bcrypt isn't just checking if the password is right; it's ensuring the dish (hash) matches the original recipe (stored hash), including the secret ingredient (salt).</p>
</li>
</ul>
<h3 id="heading-why-not-just-store-passwords-plainly">Why Not Just Store Passwords Plainly?</h3>
<p>Storing passwords in plain text is like leaving your front door unlocked. Here are a few reasons why bcrypt is better:</p>
<ul>
<li><p><strong>Salting</strong>: Prevents pre-computed hash attacks.</p>
</li>
<li><p><strong>Adaptive Difficulty</strong>: As hardware improves, you can increase the cost factor to stay ahead of computational advances.</p>
</li>
<li><p><strong>Secure Against Timing Attacks</strong>: Constant-time comparison prevents hackers from deducing information from how long comparisons take.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Bcrypt turns the simple act of password hashing into an art form, ensuring that even if someone gets their hands on your database, cracking those passwords would be like trying to reverse-engineer a gourmet recipe from a single bite of a dish.</p>
<p>Next time you type in your password, give a nod to bcrypt for keeping your digital life secure. And remember, always use strong, unique passwords for each service, because even the best seasoning can't protect a poorly chosen ingredient.</p>
]]></content:encoded></item><item><title><![CDATA[The Hierarchy of Grammars: Unveiling the Language Rules in Computer Science]]></title><description><![CDATA[In our daily used language, we use Grammar, similarly, in computer language, we have a set of rules called grammar on which a language is defined. In this article, we will look into what those Grammars are and how we define and use them.
Exploring th...]]></description><link>https://blog.theashishmaurya.me/the-hierarchy-of-grammars-unveiling-the-language-rules-in-computer-science</link><guid isPermaLink="true">https://blog.theashishmaurya.me/the-hierarchy-of-grammars-unveiling-the-language-rules-in-computer-science</guid><category><![CDATA[toc]]></category><category><![CDATA[json parser]]></category><category><![CDATA[compiler]]></category><category><![CDATA[Go Language]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 29 Dec 2023 10:54:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1703847213087/f079dfc9-a18a-4553-ba84-6fe21151eb48.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In our daily used language, we use <strong>Grammar</strong>, similarly, in computer language, we have a set of rules called grammar on which a language is defined. In this article, we will look into what those Grammars are and how we define and use them.</p>
<h3 id="heading-exploring-the-chomsky-hierarchy-of-grammars"><strong>Exploring the Chomsky Hierarchy of Grammars</strong></h3>
<p>Computer languages and grammar studies are pretty cozy with each other, and we can thank Noam Chomsky for that. Chomsky came up with a way to look at grammar mathematically, and it's been a big deal in computational linguistics and computer science. He divided grammars into four types, each with its own complexity and what's needed to process them. This breakdown is super helpful for making programming languages and understanding languages in general.</p>
<p><strong>Type-0 Grammars: Unrestricted Grammar</strong> Type-0 grammars are like the Wild West of grammars in Chomsky's world. They don't have any rules holding them back. The languages they create are called recursively enumerable languages. To handle these, you need a Turing machine, which is like the Swiss Army knife of computational models. Anything you can compute, you can express in a Type-0 language. It's the full monty of computing power.</p>
<p><strong>Type-1 Grammars: Context-Sensitive Grammar</strong> Next up are Type-1 grammars or context-sensitive ones. These are a bit more reined in than Type-0. They're behind context-sensitive languages, which need a linear bounded automaton to be recognized. Think of it as a Turing machine on a leash, its space directly tied to the input size. These grammars aren't the go-to for programming, but they're key in understanding complex computer languages and even natural languages.</p>
<p><strong>Type-2 Grammars: Context-Free Grammar</strong> Then there's Type-2, the context-free grammars. These guys are all about rules that don't care about context. They're recognized by pushdown automata, essentially Turing machines with a memory cap. Most programming languages fall here since they hit that sweet spot of being complex enough for nifty parsing algorithms but not too wild to handle.</p>
<p><strong>Type-3 Grammars: Regular Grammar</strong> Finally, at the simpler end, we have Type-3 or regular grammar. These are the most straightforward and limited bunch. They birth regular languages, which a finite state automaton can recognize – basically, the simplest kind of computational model. Regular grammars are the stars in text processing and setting up the groundwork in compilers.</p>
<h3 id="heading-so-what-is-grammar">So What is Grammar?</h3>
<p>A Grammar can be formally defined as</p>
<blockquote>
<p>A Grammar G can be formally described using four tuples a G = ( V, T, S, P) where,</p>
<p>V = set of Variables or Non-Terminal Symbols.<br />T = Set of Terminal Symbols<br />S = Start Symbols<br />P = Production rules for Terminal and non-Terminals</p>
</blockquote>
<p>A production rule has the form a -&gt; ß where a and ß are strings on V U T and at least one symbol belongs to V.</p>
<h3 id="heading-regular-grammar">Regular Grammar</h3>
<p>Regular Grammar can be divided into two types:</p>
<ol>
<li><strong>Right Linear Grammar</strong></li>
</ol>
<p>A Grammar is said to be Right Linear if all productions are of the form</p>
<p>$$A \rightarrow xB$$</p><p>$$\ A \rightarrow x$$</p><p>$$where \ A,B \in V \ and \ x \in T$$</p><p>In simple terms, a Non-terminal symbol (B) lies on the right side of the terminal Symbol.</p>
<ol>
<li><strong>Left Linear Grammar</strong></li>
</ol>
<p>A Grammar is said to be Left Linear if all productions are of the form</p>
<p>$$A \rightarrow Bx$$</p><p>$$\ A \rightarrow x$$</p><p>$$where \ A,B \in V \ and \ x \in T$$</p><p>In simple terms, a Non-terminal symbol (B) lies on the right side of the terminal Symbol.</p>
<h3 id="heading-derivations-from-grammar">Derivations from Grammar</h3>
<p>The set of all strings that can be derived from a Grammar is said to be the Language Generated from that Grammar.</p>
<p>For Example:</p>
<p>$$G1 = (\{S,A,B\}),\{a.b\},S,\{S \rightarrow AB, A \rightarrow\ a, B \rightarrow\ b \}) \\a$$</p><h3 id="heading-context-free-grammar">Context Free Grammar</h3>
<p>In formal language theory, a Context-free language is a language generated by some context-free Grammar.</p>
<p>The set of all Context-free languages is identical to the set of languages accepted by Pushdown Automata.</p>
<p>Context Free Grammar is defined by 4 tuples as G = { V, ∑, S, P } where</p>
<p>V = Set of Variable or Non-Terminal Symbols<br />∑ = Set of Terminal Symbols<br />S = Start Symbols<br />P = Production Rule</p>
<p>$$\text{Context free Grammar has Production Rule of the form } \ A \rightarrow a \ where, a = \{V \ \cup \ ∑ \ \}* \ and \ A \in V$$</p><h3 id="heading-context-sensitive-grammar"><strong>Context-Sensitive Grammar</strong></h3>
<h3 id="heading-checking-if-a-certain-string-belongs-to-grammar-or-not">Checking if a certain String Belongs to Grammar or not</h3>
<p><strong>Steps</strong></p>
<p>1) Start with the start symbol and choose the closest production that matches to the given string.</p>
<p>2) Replace the variables with their most appropriate production. Repeat the process until the string is generated or until no other productions are left.</p>
<h3 id="heading-derivation-tree-or-parse-tree">Derivation Tree or Parse Tree</h3>
<p>A Derivation Tree or Parse Tree is an ordered rooted tree that Graphically represents the semantic information of strings derived from a Context-Free Grammar.</p>
<p>Root Vertex: Must be labeled by the Start Symbol<br />Vertex: Labelled by Non-Terminal Symbols<br />Leaves: Labelled by Terminal Symbols or <strong>∈</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1703786464579/65a729ed-6027-4512-80aa-52ee4909a2ba.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-types-of-derivation-tree">Types of Derivation Tree.</h3>
<ol>
<li><p>Left Derivation Tree: A left Derivation tree is obtained by applying production to the leftmost variable in each step.</p>
</li>
<li><p>Right Derivation Tree: A Right Derivation Tree is obtained by applying production to the rightmost variable in each step.</p>
</li>
</ol>
<h2 id="heading-ambiguous-grammar">Ambiguous Grammar</h2>
<p>Grammar is said to be ambiguous if there exist two or more derivatives trees for a string w ( that means two or more left derivation trees)</p>
<p><img src="https://media.geeksforgeeks.org/wp-content/uploads/20220719212802/p6-660x393.jpg" alt="Ambiguous Grammar - GeeksforGeeks" /></p>
<h2 id="heading-tldr"><strong>TL;DR</strong></h2>
<p>In this article, we explore the concept of grammar in computer languages, inspired by Noam Chomsky's hierarchy of grammars. Chomsky categorized grammars into four types, each with varying complexity and applications in computational linguistics and computer science:</p>
<ol>
<li><p>Type-0 Grammars: Unrestricted grammars with no rules, capable of expressing anything computable.</p>
</li>
<li><p>Type-1 Grammars: Context-sensitive grammars that require linear bounded automata for recognition, useful for understanding complex computer and natural languages.</p>
</li>
<li><p>Type-2 Grammars: Context-free grammars recognized by pushdown automata, commonly used in programming languages.</p>
</li>
<li><p>Type-3 Grammars: Regular grammars recognized by finite state automata, fundamental in text processing and compiler development.</p>
</li>
</ol>
<p>The article also provides formal definitions and explanations for different grammar types, including regular grammar, context-free grammar, and context-sensitive grammar. Additionally, it discusses the concept of derivation trees and ambiguity in grammar.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In summary, grammars play a crucial role in defining the rules of computer languages. Noam Chomsky's hierarchy of grammars categorizes them into four types, each with distinct complexity levels and applications. Understanding these grammar types is essential for programming, computational linguistics, and language processing tasks. Regular grammars are the simplest, while context-sensitive grammars offer a deeper level of complexity, bridging the gap between language theory and practical applications in computer science. Context-free grammars, on the other hand, are widely used in programming languages, making it a critical topic for developers and language designers. Lastly, the article touches on derivation trees and the potential for ambiguity in grammar, highlighting the importance of clarity and precision in language definitions.</p>
]]></content:encoded></item><item><title><![CDATA[Decoding the World of Regular and Non-Regular Languages (TOC)]]></title><description><![CDATA[Introduction
In the vast landscape of computer science, languages are not just confined to human communication; they also extend into the realm of formal languages, classified into regular and non-regular categories. Understanding these languages is ...]]></description><link>https://blog.theashishmaurya.me/decoding-the-world-of-regular-and-non-regular-languages-toc</link><guid isPermaLink="true">https://blog.theashishmaurya.me/decoding-the-world-of-regular-and-non-regular-languages-toc</guid><category><![CDATA[toc]]></category><category><![CDATA[Regular Expressions]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[nlp]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Tue, 19 Dec 2023 17:48:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/5u6bz2tYhX8/upload/f967e69902b9ed95cfda7e01e7db2b89.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<p>In the vast landscape of computer science, languages are not just confined to human communication; they also extend into the realm of formal languages, classified into regular and non-regular categories. Understanding these languages is crucial in various areas of computer science, from compiler design to the analysis of algorithms. In this blog post, we will explore the concepts of regular and non-regular languages, provide examples for better comprehension, and delve into the operations performed on these languages.</p>
<h2 id="heading-regular-and-non-regular-languages"><strong>Regular and Non-Regular Languages</strong></h2>
<h3 id="heading-regular-languages"><strong>Regular Languages</strong></h3>
<p>Regular languages are a subset of formal languages that can be recognized and generated by finite automata. These languages follow the rules of regular expressions, which are powerful tools for pattern matching and text processing. Regular languages exhibit simple and predictable behaviour, making them fundamental in various areas of computer science.</p>
<h3 id="heading-non-regular-languages"><strong>Non-Regular Languages</strong></h3>
<p>On the other hand, non-regular languages do not adhere to the restrictions imposed by regular languages. These languages often require more complex computational models, such as pushdown automata or Turing machines, for recognition and generation. Non-regular languages pose challenges in terms of analysis and computation due to their inherent complexity.</p>
<h2 id="heading-examples-of-regular-and-non-regular-languages"><strong>Examples of Regular and Non-Regular Languages</strong></h2>
<h3 id="heading-regular-language-example"><strong>Regular Language Example</strong></h3>
<p>Consider the language of all strings over the alphabet {0, 1} that represent binary numbers divisible by 3. This language can be recognized by a finite automaton, showcasing its regularity.</p>
<h3 id="heading-non-regular-language-example"><strong>Non-Regular Language Example</strong></h3>
<p>An example of a non-regular language is the set of all strings of the form {0^n1^n | n ≥ 0}, which represents the language of balanced parentheses. This language requires a stack-based computational model, as it cannot be recognized by a finite automaton.</p>
<h2 id="heading-operations-on-regular-and-non-regular-languages"><strong>Operations on Regular and Non-Regular Languages</strong></h2>
<h3 id="heading-regular-languages-operations"><strong>Regular Languages Operations</strong></h3>
<ol>
<li><p><strong>Union (|):</strong> Given two regular languages L1 and L2, their union L1 | L2 is also a regular language.</p>
</li>
<li><p><strong>Concatenation (⋅):</strong> If L1 and L2 are regular languages, then their concatenation L1 ⋅ L2 is a regular language.</p>
</li>
<li><p><strong>Kleene Star (*):</strong> For a regular language L, its Kleene closure L* is also a regular language.</p>
</li>
</ol>
<h3 id="heading-non-regular-languages-operations"><strong>Non-Regular Languages Operations</strong></h3>
<ol>
<li><p><strong>Intersection (∩):</strong> The intersection of two non-regular languages may not necessarily be non-regular. It depends on the specific languages and their characteristics.</p>
</li>
<li><p><strong>Complement (¬):</strong> The complement of a non-regular language is not guaranteed to be non-regular.</p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In conclusion, regular and non-regular languages are foundational concepts in formal language theory and computer science. Understanding their properties, examples, and operations is crucial for designing efficient algorithms, building compilers, and solving computational problems. As we continue to explore the vast world of languages, these distinctions become essential for navigating the complexities of computation and communication in the digital age.</p>
]]></content:encoded></item><item><title><![CDATA[Handling ServerSent event in React App]]></title><description><![CDATA[Hello Guys, welcome back to my blog. Today we will be creating our small server and React app to learn about Server-Sent Events and how to handle them in a React App.
But before we even start building anything let's learn about Server-Side Events (SS...]]></description><link>https://blog.theashishmaurya.me/handling-serversent-event-in-react-app</link><guid isPermaLink="true">https://blog.theashishmaurya.me/handling-serversent-event-in-react-app</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[React]]></category><category><![CDATA[Remix]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Mon, 27 Nov 2023 18:18:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/IlxX7xnbRF8/upload/fd05f38b1658923f1a50de43b006ad12.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Guys, welcome back to my blog. Today we will be creating our small server and React app to learn about Server-Sent Events and how to handle them in a React App.</p>
<p>But before we even start building anything let's learn about Server-Side Events (SSE)</p>
<h2 id="heading-server-side-event">Server-Side Event</h2>
<blockquote>
<p>A Server-Sent Event (SSE) is a simple and efficient mechanism for sending real-time updates from the server to the client over HTTP. It is a standard web technology that enables servers to push data to web clients over a single, long-lived HTTP connection in real time.</p>
</blockquote>
<p>In simple words, you can send push events from the backend to the frontend. Below is a small explanation to understand it better.</p>
<p><img src="https://i.ytimg.com/vi/p0E3vNY1jtE/maxresdefault.jpg" alt="Server-sent event android client - YouTube" /></p>
<h2 id="heading-heres-a-basic-overview-of-how-server-sent-events-work">Here's a basic overview of how Server-Sent Events work:</h2>
<ol>
<li><p><strong>Connection Establishment:</strong> The client initiates a request to the server, and the server responds with a special media type called <code>text/event-stream</code>. This indicates that the server will be sending events in a specific format.</p>
<pre><code class="lang-xml"> HTTP/1.1 200 OK
 Content-Type: text/event-stream
 Cache-Control: no-cache
 Connection: keep-alive
</code></pre>
</li>
<li><p><strong>Event Format:</strong> The server sends events to the client in a specific text-based format. Each event is a plain text message with a series of fields, such as "event," "data," and "id." For example:</p>
<pre><code class="lang-http"> plaintextCopy codeevent: eventName
 data: This is the event data
 id: 123
</code></pre>
</li>
<li><p><strong>Handling Events on the Client:</strong> The client receives these events and can handle them using JavaScript. The <code>EventSource</code> API is commonly used for this purpose. The client can define event listeners to process specific types of events.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> eventSource = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">'/events'</span>);

 eventSource.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
   <span class="hljs-built_in">console</span>.log(event.data);
 };

 eventSource.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
   <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'EventSource failed:'</span>, error);
 };
</code></pre>
</li>
<li><p><strong>Connection Persistence:</strong> The SSE connection remains open, allowing the server to push new events to the client whenever necessary. This is different from traditional request-response mechanisms where the client initiates each request.</p>
</li>
</ol>
<h2 id="heading-creating-a-simple-golang-app">Creating a simple Golang App</h2>
<p>I will keep the implementation simple here. In this section, we just create a simple Server Sent Event in Golang. Which listens to <code>/stream</code> route.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net/http"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Printf(<span class="hljs-string">"starting server on 8000\n"</span>)
    http.HandleFunc(<span class="hljs-string">"/stream"</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
        <span class="hljs-comment">// Set headers</span>
        w.Header().Set(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"text/event-stream"</span>)
        w.Header().Set(<span class="hljs-string">"Cache-Control"</span>, <span class="hljs-string">"no-cache"</span>)
        w.Header().Set(<span class="hljs-string">"Connection"</span>, <span class="hljs-string">"Keep-alive"</span>)

        <span class="hljs-comment">// Send an Intial Connection Response</span>

        fmt.Fprint(w, <span class="hljs-string">"data: Connection"</span>)
        flusher, ok := w.(http.Flusher)
        <span class="hljs-keyword">if</span> !ok {
            http.Error(w, <span class="hljs-string">"Streaming not supported"</span>, http.StatusInternalServerError)
            <span class="hljs-keyword">return</span>
        }

        <span class="hljs-comment">// Simulates sending event every second</span>

        <span class="hljs-keyword">for</span> {
            fmt.Fprintf(w, <span class="hljs-string">"data: %s\n\n"</span>, time.Now().Format(<span class="hljs-string">"15:04:05"</span>))
            flusher.Flush()
            time.Sleep(<span class="hljs-number">1</span> * time.Second)
        }

    })
    err := http.ListenAndServe(<span class="hljs-string">":8000"</span>, <span class="hljs-literal">nil</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }

}
</code></pre>
<p>This is it for the development of the server. Let's look at the React app in the next section.</p>
<h2 id="heading-creating-a-react-app">Creating a React app</h2>
<p>In this section we will create a React app, For this tutorial we will be using Remix. Remix is a framework built for React.</p>
<pre><code class="lang-bash">npx create-remix
</code></pre>
<p>Once that is done, just add a useEffect with the below code.</p>
<pre><code class="lang-typescript">useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> eventSource = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">'http://localhost:8000/stream'</span>);

    eventSource.onmessage = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
      setSSEData(event.data);
    };

    eventSource.onerror = <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'EventSource failed:'</span>, error);
      eventSource.close();
    };

    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-comment">// Clean up the event source when the component is unmounted</span>
      eventSource.close();
    };
  }, []); <span class="hljs-comment">// Empty dependency array ensures the effect runs only once</span>
</code></pre>
<p>Let me explain what is happening above, Once we create a <code>new EventSource</code> on the route we are streaming the data and storing it into eventSource. then we listen to onMessage and set the setSSEData to the new data we get from the event.</p>
<p>Now, it's up to you, what you want to do with this data now. What I did was simply display the data like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701108867269/12d8ea1b-1cfa-45ed-8579-12849e5c84f1.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-tldr"><strong>TL;DR:</strong></h1>
<p>This tutorial covers Server-Sent Events (SSE) with a Golang server and a React app using Remix. SSE allows real-time updates from the server to the client over HTTP. The Golang server listens to the <code>/stream</code> route, sending periodic events. The React app, created with Remix, uses <code>EventSource</code> to receive and display the streaming data. The server's SSE implementation and React's <code>useEffect</code> for handling events is explained step by step.</p>
]]></content:encoded></item><item><title><![CDATA[How I build My Own Data structure for Indexing : Bidirectional Map]]></title><description><![CDATA[Recently, in my organization, we came across a need to build an index of files we are using for our in-browser filesystem, where we have the id's of the file/folder which is how frontend understands and a path associated with it in the in-browser fil...]]></description><link>https://blog.theashishmaurya.me/how-i-build-my-own-data-structure-for-indexing-bidirectional-map</link><guid isPermaLink="true">https://blog.theashishmaurya.me/how-i-build-my-own-data-structure-for-indexing-bidirectional-map</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[map]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sun, 08 Oct 2023 06:35:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/l68Z6eF2peA/upload/80ad6599c9cb884c034ae768eb036055.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recently, in my organization, we came across a need to build an index of files we are using for our in-browser filesystem, where we have the id's of the file/folder which is how frontend understands and a path associated with it in the in-browser file system.</p>
<h2 id="heading-brainstorming">Brainstorming</h2>
<p>After a couple of ideas, I thought of creating a map with all the ids mapped to their current path, which was a good idea. But after thinking it harder I found that the update path ( which is basically update Name) would be harder and can't be achieved easily by using one map only, <mark>as if we update a folder we need to update all the child component's path also</mark>. To do so I also needed a reference to all the paths and a way to easily access them.  </p>
<h2 id="heading-bidirectional-map">Bidirectional Map</h2>
<p>I thought of building a bidirectional Map where one map's key are <strong>id</strong> and the other map's key is the <strong>path.</strong> Well, this was a very good solution and optimal in my case. Below is a mental picture of it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696746153963/405c96ad-b411-4e70-8090-b566d42233ce.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-api-for-bidirectional-map">API for bidirectional Map</h2>
<p>After building a basic mental idea about this, I needed to build APIs for this datastructure which can be used and can be easily extended. I was pretty sure we would need operations like <code>add(), get() , update(), delete()</code> . But apart from these, we can also have, <code>getall()</code> other operations depending upon the need.</p>
<p>below is the code of how the finished structure looks in Typescript.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">/**
 * @template K - The type of keys.
 * @template V - The type of values.
 *
 * @class
 * @classdesc A simple bidirectional map for mapping between keys and values.
 *   Provides methods to add mappings and retrieve values by key or value.
 *
 * @example
 * // Example usage:
 * const bidirectionalMap = new BidirectionalMap&lt;string, number&gt;();
 * bidirectionalMap.addMapping('apple', 1);
 * bidirectionalMap.addMapping('orange', 2);
 *
 * // Using key to get value
 * console.log(bidirectionalMap.getValue('apple')); // Output: 1
 *
 * // Using value to get key
 * console.log(bidirectionalMap.getValue(2)); // Output: orange
 */</span>
<span class="hljs-keyword">class</span> BidirectionalMap&lt;K, V&gt; {
  <span class="hljs-comment">/**
   * @private
   * @type {Map&lt;K, V&gt;} - The forward mapping from keys to values.
   */</span>
  <span class="hljs-keyword">private</span> forwardMap: <span class="hljs-built_in">Map</span>&lt;K, V&gt;;

  <span class="hljs-comment">/**
   * @private
   * @type {Map&lt;V, K&gt;} - The reverse mapping from values to keys.
   */</span>
  <span class="hljs-keyword">private</span> reverseMap: <span class="hljs-built_in">Map</span>&lt;V, K&gt;;

  <span class="hljs-comment">/**
   * Creates a new instance of BidirectionalMap.
   * @constructor
   */</span>
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.forwardMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>&lt;K, V&gt;(); <span class="hljs-comment">// used to map key ===&gt; path</span>
    <span class="hljs-built_in">this</span>.reverseMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>&lt;V, K&gt;(); <span class="hljs-comment">// used to map path ====&gt; key</span>
  }

  <span class="hljs-comment">/**
   * Adds a bidirectional mapping between a key and a value.
   *
   * @param {K} key - The key to be mapped.
   * @param {V} value - The value to be mapped.
   * @returns {void}
   * @memberof BidirectionalMap
   */</span>
  addMapping(key: K, value: V): <span class="hljs-built_in">void</span> {
    <span class="hljs-built_in">this</span>.forwardMap.set(key, value);
    <span class="hljs-built_in">this</span>.reverseMap.set(value, key);
  }

  <span class="hljs-comment">/**
   * Retrieves the value associated with the provided key or value.
   *
   * @param {K | V} keyOrValue - The key or value for which to retrieve the associated value or key.
   * @returns {V | K | undefined} The associated value or key, or undefined if not found.
   * @memberof BidirectionalMap
   */</span>
  getValue(keyOrValue: K | V): V | K | <span class="hljs-literal">undefined</span> {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.forwardMap.has(keyOrValue <span class="hljs-keyword">as</span> K)) {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.forwardMap.get(keyOrValue <span class="hljs-keyword">as</span> K);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.reverseMap.has(keyOrValue <span class="hljs-keyword">as</span> V)) {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.reverseMap.get(keyOrValue <span class="hljs-keyword">as</span> V);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
    }
  }

  getAllKeysFromForwardMap() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.forwardMap.keys();
  }

  getAllKeysFromReverseMap() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.reverseMap.keys();
  }

  getAllValuesFromForwardMap() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.forwardMap.values();
  }

  getAllValuesFromReverseMap() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.reverseMap.values();
  }

  getValueFromForwardMap(key: K) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.forwardMap.get(key);
  }

  getValueFromReverseMap(key: V) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.reverseMap.get(key);
  }

  <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> This should update the the values in the both things</span>

  updateValue(key: K, value: V) {
    <span class="hljs-comment">// Update the value of key in forward Map and backward Map</span>
    <span class="hljs-built_in">this</span>.addMapping(key, value);
  }

  getMapping() {
    <span class="hljs-keyword">return</span> {
      forwardMap: <span class="hljs-built_in">this</span>.forwardMap,
      backwardMap: <span class="hljs-built_in">this</span>.reverseMap,
    };
  }
}
</code></pre>
<p>the only thing that is missing is the <code>delete()</code> method, which you guys can create on your own.</p>
<p>Once this is gone the usage of this looks something like below.</p>
<p>Example Usage:</p>
<pre><code class="lang-typescript"> <span class="hljs-meta">@example</span>
 <span class="hljs-comment">// Example usage:</span>
  <span class="hljs-keyword">const</span> bidirectionalMap = <span class="hljs-keyword">new</span> BidirectionalMap&lt;<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>&gt;();
  bidirectionalMap.addMapping(<span class="hljs-string">'apple'</span>, <span class="hljs-number">1</span>);
  bidirectionalMap.addMapping(<span class="hljs-string">'orange'</span>, <span class="hljs-number">2</span>);

  <span class="hljs-comment">// Using key to get value</span>
 <span class="hljs-built_in">console</span>.log(bidirectionalMap.getValue(<span class="hljs-string">'apple'</span>)); <span class="hljs-comment">// Output: 1</span>

 <span class="hljs-comment">// Using value to get key</span>
 <span class="hljs-built_in">console</span>.log(bidirectionalMap.getValue(<span class="hljs-number">2</span>)); <span class="hljs-comment">// Output: orange</span>
</code></pre>
<p>Thank you for reading so far. If you learned something new and liked the article please follow me and subscribe to my email newsletter.</p>
]]></content:encoded></item><item><title><![CDATA[Introducing VideoNotes: Your Ultimate AI-Powered Youtube-to-Notes Companion!"]]></title><description><![CDATA[Hey there, everyone! How's your week treating you? As for me, I must admit, it's been quite tiring. I recently embarked on a new adventure by landing a full-time job—cue the applause and congratulatory comments, if you feel like it! Let me tell you, ...]]></description><link>https://blog.theashishmaurya.me/introducing-videonotes-your-ultimate-ai-powered-youtube-to-notes-companion</link><guid isPermaLink="true">https://blog.theashishmaurya.me/introducing-videonotes-your-ultimate-ai-powered-youtube-to-notes-companion</guid><category><![CDATA[1password]]></category><category><![CDATA[1password-hackathon]]></category><category><![CDATA[BuildWith1Password]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 30 Jun 2023 18:54:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688149582925/0e5b50a0-a467-4a1d-9845-2e79947bece7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, everyone! How's your week treating you? As for me, I must admit, it's been quite tiring. I recently embarked on a new adventure by landing a full-time job—cue the applause and congratulatory comments, if you feel like it! Let me tell you, it's been quite the whirlwind. The days have been jam-packed and filled with a flurry of activities.</p>
<p>By the way, during my college days, I found myself engrossed in numerous informational videos and lectures. Let me tell you, trying to take notes while absorbing all that knowledge was no walk in the park. The struggle was real! <strong>I often wished for a magical AI companion who could effortlessly jot down the key points for me.</strong> Can you imagine how incredible that would be? It would have saved me from the mindless consumption of content without any real progress. And when the opportunity came for this hackathon by <a target="_blank" href="https://1password.com/"><strong>1Password</strong></a> <strong>and</strong> <a target="_blank" href="https://hashnode.com/"><strong>Hashnode</strong></a> I couldn't refuse to participate</p>
<h3 id="heading-the-genesis-of-incredible-idea">The Genesis of Incredible Idea 💡</h3>
<p>After the launch of ChatAI, I wanted to get my hands dirty and try out a bunch of AI mini SAAS tools for my productivity. And a way to jot down the notes from youtube was first on my priority list. And when OpenAI launched the GPT-3 API I jumped at the opportunity to build something cool.</p>
<p>The concept behind Video-notes is to provide a convenient SaaS tool that allows users to simply paste a YouTube link and automatically generate comprehensive notes while watching the video. However, why limit ourselves to just note generation? Let's think bigger! Why not expand the capabilities of the tool to include generating <strong>blog posts, summaries, transcripts, and even language translation</strong>? With such a versatile tool, the possibilities for enhancing productivity and content creation become truly endless.</p>
<p>That's what <strong>Video-Notes is, It's not a boring transcriber for your youtube video but auto-formatting the Transcription to your desired Output using the power of AI.</strong><br />Doesn't it seem amazing?</p>
<h2 id="heading-video-preview">Video Preview</h2>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/o37ueyjsFkk">https://youtu.be/o37ueyjsFkk</a></div>
<p> </p>
<h2 id="heading-the-journey">The Journey 🛣️</h2>
<p>The journey to create this was pretty tiring it was hard to come up with a good architectural design that can be cost-effective as well as fast. Even though below is what I can come up with.</p>
<h3 id="heading-the-architecture"><strong>The Architecture ⚒️</strong></h3>
<ol>
<li><p><strong>Passage by</strong> <a target="_blank" href="https://1password.com/"><strong>1Password</strong></a></p>
<p> Passage feels very intuitive to me as it provides a native way to log in to any application and you don't need to remember the password at all. How cool is it?<br /> Also, the Implementation was pretty simple and straightforward, You can say probably one of the best ways to authenticate your users.</p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/ytdl-core"><strong>YTDL</strong></a></p>
<p> To get the Audio file from the URL of the youtube link I used the YTDL library. In the beginning, I was fetching the audio from Youtube using the YTDL API, and once the audio was received, I streamed and saved it to my in-memory state ( basically state if you use React).</p>
<p> The Problem with this approach was I was streaming a big file back to my react app and not only that I needed to send this file back to the Whisper to get the Transcription.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/blog/introducing-chatgpt-and-whisper-apis"><strong>Whisper API</strong></a></p>
<p> In the beginning, I transcribed the Video from youtube using, OpenAI's product whisper. This worked perfectly for smaller videos but not for larger files as it has a file limit of 25MB (Roughly around ~25min high-quality videos). But any good lecture video or educational video generally exceeds more than 200 MB or more. So I initially thought of chunking the audio into 25 MB chunks and getting the transcription one by one.<br /> This solution was possible but the problem was that it was not very fast in real-world scenarios. No user wants to keep waiting for half an hour ( Yes it took this long) and also the cost to use the whisper API was quite a lot which was not sustainable in the long run.<br /> This was the main reason why I moved away from the whisper API. This did the job accurately but also had a very high cost associated with it.</p>
</li>
<li><p><a target="_blank" href="https://openai.com/blog/introducing-chatgpt-and-whisper-apis"><strong>ChatGPT</strong></a></p>
<p> I don't really think you haven't heard of chatGPT, if you haven't let me tell you it's an amazing generative AI by OpenAI. Now this could solve a ton of my problem like, like converting the transcripts to the <strong>Blog, Summaries, and Notes,</strong> or even translating it into another language. Basically, it's the Brain of the whole application. and very essential part of the whole architecture.</p>
</li>
<li><p><a target="_blank" href="https://firebase.google.com/"><strong>Cloud (Firebase)</strong></a></p>
<p> I used the Firebase product Firestore to save the data like user details and notes details and other stuff. Which I might need to show users in the future.</p>
</li>
</ol>
<h3 id="heading-the-improvision"><strong>The Improvision</strong></h3>
<p>After looking at the above implementation I knew it was not going to sustain itself, even users would think it was an overpriced application if I ever decide to monetize it. Now I needed to search for a solution that can reduce the cost that was associated with Whisper API also the circus I had to go through only to fetch the transcription of the Youtube video.</p>
<p><strong>Youtube does it for free.</strong></p>
<p>I told this problem to my friend he was like dude youtube does that for free. Don't you know? And I was like yes I agree but is it that accurate? I don't think so, and then he mentioned "<strong>You don't need accuracy you need Transcription"</strong> As we were already using the ChatGPT we can post-process the data using it, so any issue with the transcription will be solved automatically.</p>
<h3 id="heading-using-youtubes-auto-cc-as-transcription">Using Youtube's auto-cc as Transcription.</h3>
<p>I used the <strong>YTDL</strong> library to do that. Here is a snippet of what I did, I used Nestjs API to do that as <strong>YTDL</strong> uses fs to run so it was throwing an error in the client so to workaround this used the Next API.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> ytdl <span class="hljs-keyword">from</span> <span class="hljs-string">"ytdl-core"</span>;
<span class="hljs-keyword">import</span> { NextApiRequest, NextApiResponse } <span class="hljs-keyword">from</span> <span class="hljs-string">"next"</span>;
<span class="hljs-keyword">import</span> { parseString } <span class="hljs-keyword">from</span> <span class="hljs-string">"xml2js"</span>;

<span class="hljs-keyword">const</span> lang = <span class="hljs-string">"en"</span>;
<span class="hljs-keyword">const</span> format = <span class="hljs-string">"xml"</span>;

<span class="hljs-comment">// eslint-disable-next-line import/no-anonymous-default-export</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> (req: NextApiRequest, res: NextApiResponse) =&gt; {
  <span class="hljs-keyword">const</span> { url } = req.query;
  ytdl.getInfo(url <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>).then(<span class="hljs-function">(<span class="hljs-params">info: <span class="hljs-built_in">any</span></span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> tracks =
      info.player_response.captions.playerCaptionsTracklistRenderer
        .captionTracks;
    <span class="hljs-keyword">if</span> (tracks &amp;&amp; tracks.length) {
      <span class="hljs-keyword">const</span> track = tracks.find(
        <span class="hljs-function">(<span class="hljs-params">t: { languageCode: <span class="hljs-built_in">string</span> }</span>) =&gt;</span> t.languageCode === lang
      );
      <span class="hljs-keyword">if</span> (track) {
        fetch(<span class="hljs-string">`<span class="hljs-subst">${track.baseUrl}</span>&amp;fmt=<span class="hljs-subst">${format !== <span class="hljs-string">"xml"</span> ? format : <span class="hljs-string">""</span>}</span>`</span>)
          .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.text())
          .then(<span class="hljs-function">(<span class="hljs-params">xmlData</span>) =&gt;</span> {
            <span class="hljs-comment">// Parse XML to JSON</span>
            parseString(xmlData, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
              <span class="hljs-keyword">if</span> (err) {
                <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error parsing XML:"</span>, err);
                res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">"Error parsing XML"</span>);
                <span class="hljs-keyword">return</span>;
              }

              <span class="hljs-comment">// Convert JSON to plain text</span>
              <span class="hljs-keyword">const</span> plainText = result.transcript.text;
              <span class="hljs-keyword">const</span> response = {
                transcript: plainText,
                simpleText: convertToSimpletText(plainText),
              };

              res.send(response);
            });
          })
          .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
            res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">"Error fetching captions"</span>);
          });
      } <span class="hljs-keyword">else</span> {
        res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">"Could not find captions for "</span> + lang);
      }
    } <span class="hljs-keyword">else</span> {
      res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">"No captions found for this video"</span>);
    }
  });
};
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">convertToSimpletText</span>(<span class="hljs-params">transcriptData: <span class="hljs-built_in">any</span></span>) </span>{
  <span class="hljs-keyword">let</span> text = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> { _: line } <span class="hljs-keyword">of</span> transcriptData) {
    <span class="hljs-comment">// Remove unnecessary data (e.g., speaker names)</span>
    <span class="hljs-keyword">const</span> cleanedLine = line.replace(<span class="hljs-regexp">/\[[^\]]+\]/g</span>, <span class="hljs-string">""</span>).trim();
    text += cleanedLine + <span class="hljs-string">" "</span>;
  }
  <span class="hljs-keyword">return</span> text.trim();
}
</code></pre>
<p>Let me quickly explain to you what is happening in the above code. So first we are using YTDL to fetch the video info from the URL our user has given, once we have that we are making another nested <code>api</code> call to the other API which basically fetches the CC in <code>xml</code> format.</p>
<pre><code class="lang-typescript"> fetch(<span class="hljs-string">`<span class="hljs-subst">${track.baseUrl}</span>&amp;fmt=<span class="hljs-subst">${format !== <span class="hljs-string">"xml"</span> ? format : <span class="hljs-string">""</span>}</span>`</span>)
</code></pre>
<p>The Response is received it looked like the below and we need some pre-processing to send this data to the GPT-3.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">/**
 * Notes : Result 
 * Transcript: [
  {
    _: '[Herb, YouTuber]\nThis video demonstrates closed captions.',
    '$': { start: '6.5', dur: '1.7' }
  },
  {
    _: 'To turn on captions, click on the icon over here.',  
    '$': { start: '8.3', dur: '2.7' }
  },
  {
    _: '[Greg, Deaf Singer]\n' +
      'Back when the Internet was first established, deaf people had a\n' +
      'great time with it.',
    '$': { start: '12.5', dur: '3.9' }
  },
  {
    _: 'Everything was readable.\nThen ...',
    '$': { start: '16.5', dur: '2' }
  },
  {
    _: '[Ken, Deaf Listener]\n' +
      'Movies started showing up.\n' +
      'We couldn&amp;#39;t understand them...',
    '$': { start: '19', dur: '3.2' }
  },
  { _: 'there were no captions!', '$': { start: '22.5', dur: '1.5' } },
  {
    _: 'Fortunately, Google Video added support for captions.',
    '$': { start: '24.5', dur: '2.5' }
  },
  { _: 'Thank you, Ken!', '$': { start: '27.5', dur: '1' } },
  {
    _: 'Now, we&amp;#39;ve added that to YouTube.',
    '$': { start: '28.5', dur: '3' }
  },
  {
    _: 'But the first thing he did with\nthat was RickRoll me!',
    '$': { start: '32', dur: '3' }
  },
  {
    _: '♪ Never gonna give you up, ♪\n♪ never gonna let you down...',
    '$': { start: '35.5', dur: '3.5' }
  },
  {
    _: '[Franck, Icone de Mode]\nCaptions and subtitles are also helpful',
    '$': { start: '41.3', dur: '2.7' }
  },
  {
    _: 'for people who speak other languages, like myself.', 
    '$': { start: '44.2', dur: '2' }
  },
  {
    _: 'With subtitles, I can enjoy US Comedy, or news stories from Russia,',
    '$': { start: '46.8', dur: '3.2' }
  },
  { _: 'in my own language. ', '$': { start: '50.1', dur: '1.4' } },
  {
    _: 'As a video uploader, this means you can reach\n' +   
      'to people all over the world, ',
    '$': { start: '52', dur: '4' }
  },
  {
    _: 'irrespective of language.',
    '$': { start: '56.8', dur: '1.7' }
  },
  {
    _: '[Hiroto, Bedhead]\n' +
      'You can upload multiple tracks like English and French, ',
    '$': { start: '59.5', dur: '2.5' }
  },
  {
    _: 'and viewers can choose the track they like.',        
    '$': { start: '62.5', dur: '3.5' }
  },
  {
    _: '[Toliver, Japanese Learner]\n' +
      'For example, if you enjoy using YouTube in French,',  
    '$': { start: '67.5', dur: '4' }
  },
  {
    _: 'French captions will automatically appear.',
    '$': { start: '72', dur: '5' }
  },
  { _: 'With just a single video,', '$': { start: '77.5', dur: '3' } },
  {
    _: 'you can now reach people all around the globe!',     
    '$': { start: '81', dur: '5' }
  },
  {
    _: 'The captioning capability at YouTube was just launched this summer,',
    '$': { start: '88', dur: '3' }
  },
  {
    _: 'and we&amp;#39;re planning to add more features to this.',
    '$': { start: '91.3', dur: '2.7' }
  },
  {
    _: 'If you have any feedback, please let us know!',      
    '$': { start: '94.2', dur: '2.3' }
  }
]
 * 
 */</span>
</code></pre>
<p>It has duration as relevant data which I m thinking to use but for now we just simple data string which we can send to the GPT-3 API.</p>
<p><strong>Pre-Processing</strong></p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">convertToSimpletText</span>(<span class="hljs-params">transcriptData: <span class="hljs-built_in">any</span></span>) </span>{
  <span class="hljs-keyword">let</span> text = <span class="hljs-string">""</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> { _: line } <span class="hljs-keyword">of</span> transcriptData) {
    <span class="hljs-comment">// Remove unnecessary data (e.g., speaker names)</span>
    <span class="hljs-keyword">const</span> cleanedLine = line.replace(<span class="hljs-regexp">/\[[^\]]+\]/g</span>, <span class="hljs-string">""</span>).trim();
    text += cleanedLine + <span class="hljs-string">" "</span>;
  }
  <span class="hljs-keyword">return</span> text.trim();
}
</code></pre>
<p>Once this data is saved to the state, I make the call to GPT-3 API using the data we got in Step 1.</p>
<p>We use a simple GPT-3 completion API Read about it <a target="_blank" href="https://openai.com/blog/introducing-chatgpt-and-whisper-apis">HERE</a>.</p>
<pre><code class="lang-typescript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getGptResponse = <span class="hljs-keyword">async</span> (
  text: <span class="hljs-built_in">string</span>,
  contentType: <span class="hljs-built_in">string</span>
): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">string</span> | <span class="hljs-literal">undefined</span>&gt; =&gt; {
  <span class="hljs-keyword">if</span> (!text) <span class="hljs-keyword">return</span>;

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    fetch(<span class="hljs-string">"https://api.openai.com/v1/chat/completions"</span>, {
      method: <span class="hljs-string">"POST"</span>,
      headers: {
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
        Authorization: <span class="hljs-string">`Bearer <span class="hljs-subst">${getApiKey()}</span>`</span>,
      },
      body: <span class="hljs-built_in">JSON</span>.stringify({
        model: <span class="hljs-string">"gpt-3.5-turbo"</span>,
        messages: [
          {
            role: <span class="hljs-string">"system"</span>,
            content: contentType,
          },
          {
            role: <span class="hljs-string">"assistant"</span>,
            content:
              <span class="hljs-string">"Supported Markdown: #, ##, ###, ####, #####, ######, ![](url), &gt;, *, 1. , ```code```,"</span>,
          },
          {
            role: <span class="hljs-string">"user"</span>,
            content: text,
          },
        ],
      }),
    })
      .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (!response.ok) {
          <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Network response was not ok"</span>);
        }
        <span class="hljs-keyword">return</span> response.json();
      })
      .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(json.choices[<span class="hljs-number">0</span>].message.content);
        resolve(json.choices[<span class="hljs-number">0</span>].message.content);
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(error);
        reject(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"GPT-3 failed"</span>));
      });
  });
};
</code></pre>
<p>In this, I fetch the key From the local storage and then make the API call with the transcription data in the first Step.</p>
<p>Once that is done I need to do an extra step to convert the markdown to the <code>Blocks data.</code> which my editor understands. <strong>Why Markdown?</strong> Surprisingly CHAT GPT is very good at handling markdown than the data is needed.</p>
<p>Once the Editor is populated with the data user wants just SImply saves it and can easily access it from any device anytime.</p>
<h2 id="heading-so-where-does-the-passage-come-in">So where does the Passage Come In?</h2>
<p>Well as we are saving the notes and making API calls to OpenAI which is expensive, we do want some kind of user management. There are a ton of ways to handle it, including the Firebase auths, but what <strong>Passage</strong> gave seems very intuitive and native to having an application experience. It simply uses the native way of the device to authenticate users and login them.<br />Just not that also the implementation was pretty simple and I was blown away by how easy the implementation was, Barely a couple of lines of code. you can read about it in their official doc.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688145640489/84bbed99-1dec-4bac-a0ea-bbd1369176a4.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-application-flow">Application Flow</h2>
<ol>
<li><h3 id="heading-visit-us">Visit Us.</h3>
<p> Go to <a target="_blank" href="https://video-notes-pi.vercel.app/">https://video-notes-pi.vercel.app/</a> and Click on <strong>Get Started.</strong></p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688141636096/6000bbab-52a7-48ac-b69d-0121e91f328a.png" alt class="image--center mx-auto" /></p>
</li>
<li><h3 id="heading-login-using-passage">Login Using Passage</h3>
<p> If you are already login you can continue normally using your native way or you can register.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688141707441/fb4fd800-1511-47d2-834b-1d344c9ed5b1.png" alt class="image--center mx-auto" /></p>
</li>
<li><h3 id="heading-enter-the-url-of-your-youtube-video">Enter the URL of your youtube Video.</h3>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688141779412/12ad5fc9-7500-424b-b7c0-7837210b76f2.png" alt class="image--center mx-auto" /></p>
</li>
<li><h3 id="heading-select-the-format-you-want">Select the format You want.</h3>
<p> Select the format you like to have your output in, In this example, I used Summary as my desired format, you can choose others too, We currently support <strong>Notes, Blogs,</strong> and <strong>Summary</strong> though planning to have others and a custom option too. Where you can write your own prompts.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688141902066/976004ed-9379-4989-8fbd-9329f6c2e042.png" alt class="image--center mx-auto" /></p>
</li>
<li><h3 id="heading-click-and-wait-for-it">Click and Wait for it...</h3>
<p> Once you clicked on Convert, you kind of need to wait for this process to finish, once that is done you will have a screen like below.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688144865592/c511bb87-a61d-41e0-a2ba-dd632c86d0ef.png" alt class="image--center mx-auto" /></p>
</li>
<li><h3 id="heading-save-the-note-to-the-database">Save the Note to the Database.</h3>
<p> You can click <strong>Save</strong> to save to Firebase or you can edit it, it's up to you.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688144999803/bb1a4399-528b-4663-9635-b39ae129d7d7.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Revisit it.<br /> You can revisit your saved notes by clicking on the <strong>Notebook</strong> and then selecting the note you wanna revisit.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688145102765/e177bf27-289b-44e5-a59f-2f3d54558b13.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688145356226/1eb83554-0909-4ab9-88b2-45812f255911.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-results">Results</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688145381964/1dadc337-42cf-4611-8df7-b0c33c0789a4.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-whats-next">What's Next</h2>
<ol>
<li><p><strong>A Better Player</strong>: I Intent to add a better player for playing and navigating the youtube video in sync with the notes or blogs.</p>
</li>
<li><p><strong>A Better Editor</strong>: I intended to add better features to the editor, like code preview, automatic screenshots, etc.</p>
</li>
<li><p><strong>Timestamp-based Notes</strong>: I also planning to add a feature in which we can add timestamps to our notes or transcript so that it's easily navigated.</p>
</li>
<li><p><strong>Better Prompts and Custom Prompts</strong>: Better support for custom prompts and increasing the quality of the existing prompts.</p>
</li>
<li><p><strong>Translation</strong>: A way to get the videos that are not native and transcribe them.</p>
</li>
</ol>
<h2 id="heading-technology-used">Technology Used 🧑‍💻</h2>
<h3 id="heading-frontend">Frontend</h3>
<ol>
<li><p><a target="_blank" href="https://editorjs.io/">Editor.js</a><br /> Free block-style editor with a universal JSON output.</p>
</li>
<li><p><a target="_blank" href="https://nextjs.org/">Nextjs</a></p>
</li>
<li><p><a target="_blank" href="https://blog.1password.com/unlock-1password-with-passkeys/">Passage by 1 Password</a></p>
</li>
</ol>
<h3 id="heading-backend-and-api">Backend and API</h3>
<ol>
<li><p><a target="_blank" href="https://firebase.google.com/">Firebase Firestore</a></p>
</li>
<li><p><a target="_blank" href="https://openai.com/blog/introducing-chatgpt-and-whisper-apis">GPT-3 API</a></p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/ytdl-core">YTDL-Core</a></p>
</li>
</ol>
<h3 id="heading-resources-and-links">Resources and links</h3>
<ol>
<li><p><a target="_blank" href="https://video-notes-pi.vercel.app/">Live Link</a>: <a target="_blank" href="https://video-notes-pi.vercel.app/">https://video-notes-pi.vercel.app/</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/theashishmaurya/videoNotes">GitHub Link</a>: <a target="_blank" href="https://github.com/theashishmaurya/videoNotes">https://github.com/theashishmaurya/videoNotes</a></p>
</li>
</ol>
<h2 id="heading-tldr">TLDR</h2>
<ul>
<li><p>Video-Notes is a SaaS tool that generates notes from informational videos.</p>
</li>
<li><p>It offers features like blog post generation, summaries, transcripts, and language translation.</p>
</li>
<li><p>Technical implementation includes:</p>
<ul>
<li><p>Authentication using Passage.</p>
</li>
<li><p>Fetching audio from YouTube using YTDL.</p>
</li>
<li><p>Transcription using YouTube's auto-cc (switched from Whisper API).</p>
</li>
<li><p>ChatGPT as the core language model.</p>
</li>
<li><p>Data storage using Firebase.</p>
</li>
</ul>
</li>
<li><p>Code snippets for fetching auto-cc from YouTube and using the GPT-3 API were shared.</p>
</li>
<li><p>Improvements were made to reduce costs and enhance transcription accuracy.</p>
</li>
<li><p>Live version: <a target="_blank" href="https://video-notes-pi.vercel.app/">Live Video-Notes</a></p>
</li>
<li><p>GitHub repository: <a target="_blank" href="https://github.com/theashishmaurya/videoNotes">Video-Notes on GitHub</a></p>
</li>
<li><p>If you liked it follow me on <a target="_blank" href="https://twitter.com/theysaymaurya">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/theashishmaurya/">LinkedIn</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Handling JWT Access and Refresh Token using Axios in React App]]></title><description><![CDATA[Hey Readers, How have you been? I hope you are safe and sound. Well, recently I have been working as a frontend dev for a startup and have to implement an Authentication system in their frontend.
Well if you already don't know it there are famously t...]]></description><link>https://blog.theashishmaurya.me/handling-jwt-access-and-refresh-token-using-axios-in-react-app</link><guid isPermaLink="true">https://blog.theashishmaurya.me/handling-jwt-access-and-refresh-token-using-axios-in-react-app</guid><category><![CDATA[React]]></category><category><![CDATA[JSON Web Tokens (JWT)]]></category><category><![CDATA[axios]]></category><category><![CDATA[networking]]></category><category><![CDATA[technology]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Mon, 12 Jun 2023 14:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686563618428/db463927-c066-4cf4-9b73-c9d72eba8d9b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey Readers, How have you been? I hope you are safe and sound. Well, recently I have been working as a frontend dev for a startup and have to implement an Authentication system in their frontend.</p>
<p>Well if you already don't know it there are famously two ways people handle authentication in their products nowadays.</p>
<ol>
<li><p>JWT tokens</p>
</li>
<li><p>OAuth</p>
</li>
</ol>
<p>Well, you can learn about them on the internet there are 100s of blogs and videos for them.</p>
<p>Now let me explain to you guys how to use the first method in React.</p>
<h1 id="heading-jwt-token">JWT Token</h1>
<p>JSON Web Tokens also commonly known as JWT are used to authenticate a client to the server. It can be used for login or other things.</p>
<blockquote>
<p>JSON Web Tokens are an open, industry-standard RFC 7519 method for representing claims securely between two parties.</p>
</blockquote>
<pre><code class="lang-plaintext">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
</code></pre>
<p>above is an example JWT web token it can be decoded in the below format</p>
<h4 id="heading-header">Header</h4>
<pre><code class="lang-plaintext">{
  "alg": "HS256",
  "typ": "JWT"
}
</code></pre>
<h4 id="heading-payload">Payload</h4>
<pre><code class="lang-plaintext">{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}
</code></pre>
<h4 id="heading-verify-signature">Verify Signature</h4>
<pre><code class="lang-plaintext">HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),

your-256-bit-secret

)
</code></pre>
<h3 id="heading-jwt-auth-token-and-jwt-refresh-token">JWT Auth Token and JWT Refresh Token</h3>
<p>A JWT architecture usually has two parts one is <code>authToken</code> and others are <code>refreshToken</code>. Where <code>authToken</code> is responsible for authenticating the user and <code>refreshToken</code> is responsible for getting the new <code>authToken</code> from the backend without asking for <code>username</code> and <code>password</code> from the user.<br />Yes! <code>authTokens</code> expires. Well for security purposes we set up our <code>authToken</code> in such as way that it expires in a while and uses the refresh token to fetch the <code>authToken</code> back.</p>
<h3 id="heading-understanding-the-flow-of-jwt">Understanding the flow of JWT.</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686564000640/21e832a4-c57e-4e0e-8bcc-b72c5a00c22f.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-ia"> </h3>
<ol>
<li><p><strong>User Logins</strong>: User logins with username (email) and password which then goes back to the server to create a new <strong>JWT</strong> token. A simple JWT token contains JWT <code>authToken</code> and JWT <code>refreshToken</code> both tokens have an expiry generally and <code>refreshToken</code> should always have a greater expiry date than <code>authToken</code>.</p>
</li>
<li><p><strong>Token Received</strong>: Once the JWT token is received by the front end they can save that JWT token into local storage or to an in-memory store like Redux. Depends on preferences but there are some standard ways to do that.</p>
</li>
<li><p><strong>Making Calls</strong>: Once the JWT token is saved, all calls which use authentication/authorisation ( Yes mate both are different concepts) uses this JWT token to successfully validate the request.</p>
</li>
<li><p><strong>Token expiry</strong>: Once the JWT token is expired which as we already know going to happen the JWT <strong>refresh token</strong> is used to authenticate the API call and used to fetch the new JWT tokens. (Note: Refresh token can only authenticate the API route which is used to get the new tokens)</p>
</li>
<li><p><strong>Using the new Auth Tokens</strong>: Once you get the new JWT tokens you can use the <code>authTokens</code> to make the API calls to the server.</p>
</li>
<li><p><strong>Repeat the Process</strong>: Keep repeating the process to get the new <code>authTokens</code> and making the API call.</p>
</li>
</ol>
<h2 id="heading-handling-jwt-token-in-react">Handling JWT Token in React.</h2>
<p>Well, you might be working on just the front end and you might have an API endpoint to get the JWT <code>authToken</code> and JWT <code>refreshToken</code>.</p>
<p>let's create a new component to get the auth token. We will call it <code>login.jsx</code> and write the login-related logic here.</p>
<p>In this file, we will have the signup method which takes <code>username</code> and <code>password</code> as payload and gets the <code>authToken</code> and <code>RefreshToken</code></p>
<p>Below is the code for the <code>login component</code> which is responsible for handling the login functionality</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>;

<span class="hljs-keyword">const</span> Login = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [credentials, setCredentials] = useState({
    email: <span class="hljs-string">''</span>,
    password: <span class="hljs-string">''</span>
  });

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    setCredentials({
      ...credentials,
      [e.target.name]: e.target.value
    });
  };

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (e) =&gt; {
    e.preventDefault();

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(<span class="hljs-string">'/api/login'</span>, credentials);
      <span class="hljs-keyword">const</span> { token, refreshToken } = response.data;

      <span class="hljs-comment">// Store the tokens in localStorage or secure cookie for later use</span>
      <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'token'</span>, token);
      <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'refreshToken'</span>, refreshToken);

      <span class="hljs-comment">// Redirect or perform other actions upon successful login</span>
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-comment">// Handle login error</span>
    }
  };

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;input
        <span class="hljs-keyword">type</span>=<span class="hljs-string">"email"</span>
        name=<span class="hljs-string">"email"</span>
        value={credentials.email}
        onChange={handleChange}
      /&gt;
      &lt;input
        <span class="hljs-keyword">type</span>=<span class="hljs-string">"password"</span>
        name=<span class="hljs-string">"password"</span>
        value={credentials.password}
        onChange={handleChange}
      /&gt;
      &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Login&lt;/button&gt;
    &lt;/form&gt;
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Login;
</code></pre>
<p>Let me explain what is happening in the above code.</p>
<ol>
<li><p>First, we are asking users to get the username and password in a form component. We use <code>handleChange</code> function to handle the changes to form.</p>
</li>
<li><p><code>OnSubmit</code> we are making an API call to the backend on <code>/api/login</code> endpoint, which is responsible for handling the authentication and login of the user.</p>
</li>
<li><p>On successful login, we will be having the JWT <code>authToken</code> and JWT<code>refreshToken</code> which we set in the local store for future use. (Note: Saving JWT tokens to the local storage is not secure but for simplicity purposes, we will use this method.)</p>
</li>
</ol>
<h3 id="heading-setting-up-axios-interceptor-for-the-jwt-tokens">Setting Up Axios Interceptor for the JWT tokens.</h3>
<p>In this step, we set up Axios Interceptor so that in every <code>API</code> call Axios automatically append the header with the <code>bearer ${authToken}</code>, which is used to authenticate and authorize the API calls to the backend.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">'axios'</span>;

<span class="hljs-keyword">const</span> api = axios.create({
  baseURL: <span class="hljs-string">'/api'</span>,
});

<span class="hljs-comment">// Add a request interceptor</span>
api.interceptors.request.use(
  <span class="hljs-function">(<span class="hljs-params">config</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> token = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'token'</span>);
    <span class="hljs-keyword">if</span> (token) {
      config.headers.Authorization = <span class="hljs-string">`Bearer <span class="hljs-subst">${token}</span>`</span>;
    }
    <span class="hljs-keyword">return</span> config;
  },
  <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">Promise</span>.reject(error)
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> api
</code></pre>
<p>The above code solves the problem of authenticating each request but what about the JWT token expiration? What will we do when the JWT <code>authToken</code> expires? Now we can ask users to log in again but that is not a good UX, a better way is to automatically fetch the new JWT <code>authToken</code> if the JWT <code>refreshToken</code> exists.  </p>
<p>To do that we will again use Axios interceptor but not at request but at response.  </p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Add a response interceptor</span>
api.interceptors.response.use(
  <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response,
  <span class="hljs-keyword">async</span> (error) =&gt; {
    <span class="hljs-keyword">const</span> originalRequest = error.config;

    <span class="hljs-comment">// If the error status is 401 and there is no originalRequest._retry flag,</span>
    <span class="hljs-comment">// it means the token has expired and we need to refresh it</span>
    <span class="hljs-keyword">if</span> (error.response.status === <span class="hljs-number">401</span> &amp;&amp; !originalRequest._retry) {
      originalRequest._retry = <span class="hljs-literal">true</span>;

      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> refreshToken = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'refreshToken'</span>);
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(<span class="hljs-string">'/api/refresh-token'</span>, { refreshToken });
        <span class="hljs-keyword">const</span> { token } = response.data;

        <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'token'</span>, token);

        <span class="hljs-comment">// Retry the original request with the new token</span>
        originalRequest.headers.Authorization = <span class="hljs-string">`Bearer <span class="hljs-subst">${token}</span>`</span>;
        <span class="hljs-keyword">return</span> axios(originalRequest);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-comment">// Handle refresh token error or redirect to login</span>
      }
    }

    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(error);
  }
);
</code></pre>
<p>So let me explain the code above so that we understand why we need interceptors and how the above code is working.  </p>
<p>On each response error with the status code <code>401</code> which is the status code for <code>Unauthorized</code> and no <code>retryFlag</code> means that the JWT token has expired. Hence we need to fetch the new token using the JWT<code>refreshToken</code> and then we set the newly generated JWT <code>authToken</code> and send the request again for the failed request.<br />In case of any JWT <code>refreshToken</code> error we can redirect to log in so that we can fetch new JWT <code>authToken</code> and JWT<code>refreshToken</code>.  </p>
<h3 id="heading-using-the-above-solution-in-our-application">Using the above solution in our Application.</h3>
<p>Now, you can use the <code>api</code> instance from the <code>api.js</code> files in your components to make authenticated requests. Here's an example of usage:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React, { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> api <span class="hljs-keyword">from</span> <span class="hljs-string">'./api'</span>;

<span class="hljs-keyword">const</span> Profile = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchProfile = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> api.get(<span class="hljs-string">'/profile'</span>);
        setUser(response.data);
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-comment">// Handle error or redirect to login</span>
      }
    };

    fetchProfile();
  }, []);

  <span class="hljs-keyword">if</span> (!user) {
    <span class="hljs-keyword">return</span> &lt;div&gt;Loading...&lt;/div&gt;;
  }

  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      &lt;h2&gt;Welcome, {user.name}!&lt;/h2&gt;
      &lt;p&gt;Email: {user.email}&lt;/p&gt;
      {<span class="hljs-comment">/* Render other user details */</span>}
    &lt;/div&gt;
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
<h3 id="heading-ia-1"> </h3>
<p>TL;DR:</p>
<p>To implement authentication in a React application, one popular approach is to use JSON Web Tokens (JWT). Here's a summary of the steps involved:</p>
<ol>
<li><p>Create a <code>Login</code> component that handles the login form and makes an API call to authenticate the user. Store the received JWT <code>authToken</code> and JWT <code>refreshToken</code> in localStorage.</p>
</li>
<li><p>Set up an Axios instance with interceptors to automatically include the JWT <code>authToken</code> in the headers of authenticated API requests.</p>
</li>
<li><p>Add a response interceptor to handle JWT token expiration. If a request receives a 401 error (Unauthorized) and there is a JWT <code>refreshToken</code> available, use it to fetch a new JWT <code>authToken</code> and update it in localStorage. Then retry the original request with the new authToken.</p>
</li>
<li><p>Use the configured Axios instance in your components to make authenticated API calls.</p>
</li>
</ol>
<p>Remember to handle errors, redirect to login on refreshToken failure, and consider security aspects when storing tokens.</p>
<p>By implementing JWT authentication with refresh tokens and using Axios interceptors, you can create a secure and efficient authentication system in your React application.</p>
]]></content:encoded></item><item><title><![CDATA["Uncovering the Inner Workings of Bitcoin: From Creation to Mining"]]></title><description><![CDATA[Creation of Coins
The creation of Bitcoin can be traced back to a whitepaper published in 2008 by an unknown person or group of people under the pseudonym Satoshi Nakamoto. The whitepaper, titled "Bitcoin: A Peer-to-Peer Electronic Cash System," prop...]]></description><link>https://blog.theashishmaurya.me/uncovering-the-inner-workings-of-bitcoin-from-creation-to-mining</link><guid isPermaLink="true">https://blog.theashishmaurya.me/uncovering-the-inner-workings-of-bitcoin-from-creation-to-mining</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Blockchain technology]]></category><category><![CDATA[Blockchain development]]></category><category><![CDATA[blockchain security]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 14 Apr 2023 06:32:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681453705031/87afc08f-bdd0-4971-ae49-f018735ec708.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-creation-of-coins">Creation of Coins</h3>
<p>The creation of Bitcoin can be traced back to a whitepaper published in 2008 by an unknown person or group of people under the pseudonym Satoshi Nakamoto. The whitepaper, titled "Bitcoin: A Peer-to-Peer Electronic Cash System," proposed a decentralized digital currency that would allow for secure, anonymous transactions without the need for intermediaries like banks or payment processors.</p>
<p>To bring this vision to life, Nakamoto developed the first implementation of the Bitcoin software and released it in January 2009. The software, which is open-source and freely available, allows users to send and receive bitcoins over the internet.</p>
<p>The creation of new bitcoins is achieved through a process known as mining. Mining is the process of using computational power to solve complex mathematical problems, and when a miner solves a problem, they are rewarded with a certain amount of bitcoins. This process is designed to be resource-intensive and difficult, so it is not possible for any single person or group to control the creation of new bitcoins.</p>
<p>The total number of bitcoins that can be created is limited to 21 million, with the final bitcoin set to be mined in the year 2140. This fixed limit on the supply of bitcoins is intended to prevent inflation and ensure that the currency retains its value over time</p>
<h3 id="heading-transactions-and-double-spending">Transactions and double spending</h3>
<p>Transactions in Blockchain are building blocks of Blockchain ( I mean literally). Each Blockchain is made up of several transactions.</p>
<h4 id="heading-lifecycle-of-transactions">LifeCycle of transactions</h4>
<p>Let's Imagine you need to send some Bitcoin to your friend Alice, once you click on the send money than that transaction is got broadcasted to all the Miners out there and miners validate the transaction through several methods(We will talk about them later in this article) on successfully validating the transaction, if more than 50% agrees that block is added to the Blockchain.</p>
<p><img src="https://www.euromoney.com/learning/~/media/4305AB9860D34A26ACBD34FCC9422684.png?la=en&amp;hash=31AFCC82578BB687B747D53597B8487825DC2CFA" alt="How does a transaction get into the blockchain? | Blockchain Explained | Euromoney Learning" /></p>
<p>Now, let's assume Buyer wants to send some money to Alice and Bob not that he only has 15$ worth of Bitcoin. He made two transactions one for 11$ and one for 6$ if a miner validates and tries to validate it, both can see the current balance in Buyer is 15$ hence in this case if transactions are approved Buyer will be sending more money than it originally had. This is called the <strong>Double spending Problem.</strong></p>
<p><img src="https://static.javatpoint.com/tutorial/blockchain/images/blockchain-double-tpending2.png" alt="Blockchain Double Spending - Javatpoint" /></p>
<h4 id="heading-the-solution-to-double-spending">The Solution to Double Spending.</h4>
<p>When a transaction is made on the Bitcoin network, it is broadcast to all nodes in the network. Each node verifies that the transaction is valid by checking that the sender has sufficient funds and that the transaction has not already been spent.</p>
<p>Once the transaction is verified, it is bundled together with other transactions into a block. Miners compete to solve a cryptographic puzzle related to the block, and the first miner to solve the puzzle and add the block to the blockchain is rewarded with newly minted bitcoins.</p>
<p>Once a block is added to the blockchain, it cannot be altered, so any double-spending attempts would be rejected by the network. In order for an attacker to successfully double-spend, they would need to control the majority of the computing power on the network, which is extremely difficult and expensive to do in practice.</p>
<h3 id="heading-bitcoin-scripts">BitCoin Scripts</h3>
<p>If I have to explain this in simple words <strong>"Bitcoin scripts are language Bitcoin uses to do everything it can. from sending funds from a wallet to allowing the creation of multi-user accounts."</strong></p>
<p>Bitcoin Script is not a <strong>fully fledge programming language</strong> meaning it has some limitations and runs in a specific environment, However, this limitation is intentional as this prevents infinite or endless looping and error execution. Where malicious parts of the program can be free to create complicated operations to consume the rate of <a target="_blank" href="https://academy.bit2me.com/en/what-is-hash/"><strong>hash</strong></a> and slow down the Bitcoin system through infinite loops.</p>
<p>A Bitcoin script uses the <strong>LIFO</strong> pattern to read the instruction, it runs from Left to Right executing commands/instruction one by one. To implement this kind of functionality a popular data structure <strong>Stack</strong> is used.</p>
<p>To learn more about Bitcoin Script you can refer to this amazing article <a target="_blank" href="https://academy.bit2me.com/en/que-es-bitcoin-script/#:~:text=Bitcoin%20Script%20is%20the%20language,that%20we%20will%20know%20next.">here.</a></p>
<h3 id="heading-bitcoin-peer-to-peer-network">BitCoin Peer-to-Peer Network</h3>
<p>Before I explain to you how BitCoin Peer to Peer Network works let me first explain what <strong>Peer to Peer</strong> network is.</p>
<p>A <strong>Peer to Peer network</strong> does not need a server to send data to other members of the network. Let's take an example you want to send a movie from your local device to your friend's device. Now there is one way to establish a server from which both you and your friend connect so that you can upload the movie to the server and your friend can download it from the server itself. Now another way is to directly send the movie to your friend without the intervention of any server, this can be achieved using a <strong>peer-to-peer</strong> model where you and your friend both are peers. And once you invite a couple of your friends, it becomes a network of peers.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/P2P_network.svg/640px-P2P_network.svg.png" alt="upload.wikimedia.org/wikipedia/commons/thumb/9/..." /></p>
<p>If <strong>I</strong> have to define it goes something like this, <strong>A peer-to-peer network is one in which two or more PCs share files and access devices such as printers without requiring a separate server computer or server software.</strong></p>
<p>Now, that we are clear about <strong>the Peer-to-Peer</strong> network let's look at how blockchain uses this to establish a secure and decentralized network.</p>
<p>A Blockchain has nodes that are peers in the <strong>Peer-to-Peer</strong> network, each node in the blockchain are miner which has the capability to add a new block to the chain. So, every time transaction happens in Blockchain it gets broadcasted to these nodes, now each node races to validate this transaction, and then once the transaction is validated, this transaction then added to Blockchain. After 51% of nodes agree on this is considered as the Main Blockchain. In this manner, Blockchain achieved pure decentralization and security.</p>
<p><img src="https://images.contentstack.io/v3/assets/blt38dd155f8beb7337/blt2127a655d59a911a/62324a860f49f75a7c667dae/Blockchain_Features.jpg" alt="Peer-to-Peer Blockchain Networks: The Rise of P2P Crypto Exchanges | Bybit  Learn" /></p>
<h3 id="heading-transaction-in-bitcoin-network">Transaction in Bitcoin Network</h3>
<p>Let's again take Alice and Bob's example and understand the transaction in-depth and how every transaction is protected.</p>
<p>But before that let us look at the concept of asymmetric encryption.</p>
<h3 id="heading-asymmetric-encryption-and-how-it-works-in-blockchain">Asymmetric encryption and how it works in Blockchain.</h3>
<p>Now, to understand this let's first understand how symmetric encryption works. Suppose Bob wants to send some data to Alice but the data is sensitive and Bob wants to send this in a way that only Alice can read it. Alice will send her the box so that Bob can put the data in the box and close it. Once the box is closed only Alice can open the Box with her key, let's call this key Alice's Private key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631566793316/h4NIVWufK.png?auto=compress,format&amp;format=webp" alt="image.png" /></p>
<p>Now in cryptography, the same concept is happening, to send a message to Alice Bob encrypts the data using the <strong>Hash function</strong> such that only Alice's private key can Hash it back to the original data.</p>
<p>The problem with the above method was for every time Alice wants to receive a message Alice have to create numerous keys and boxes to receive messages from numerous people. This can be really problematic and hence the concept of the Asymmetric key was introduced.</p>
<p>Now in the <strong>Asymmetric Encryption key</strong>, Alice has two keys one is called <strong>Alice's private key</strong>, and the other is called <strong>Alice's Public key</strong>. Now the public key is shareable and the private key must not be disclosed.</p>
<p>Now, every time someone wants to send a message to Alice they can use Alice's public key and send it to Alice now that message can only be decrypted by Alice's private key.</p>
<p>The math behind is quite long so we will discuss it in later articles, but for now, we understood the private and public key concepts. Let's see how it is implied in Blockchain</p>
<p>In Blockchain when Alice wants to send money to BOB that data will be sent to the miner where they verify some conditions like the following.</p>
<ul>
<li><p>Does Alice have enough money?</p>
</li>
<li><p>Does Alice is the one who sent the money to Bob or is it someone else?</p>
</li>
</ul>
<p>For checking the available balance in the wallet BTC uses something called <strong>UTXO</strong>. <mark>An overview on UTXO will be that it is a set of all the previous transaction done by Alice and after adding and subtracting everything if the balance matches then the miner approve the transaction</mark>.</p>
<p>And to verify if the transaction came from Alice something called a <strong>Digital signature</strong> is used where Alice signs with her private key and sends it to the miner with other data. Well, you have to understand that those logics are automatically implemented in the wallet and Alice doesn't actually sign anything. Moving on what kind of data is sent to the miner?</p>
<p>Well, the data might look something like this with other data of course</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631569095992/rFrz7FzKr.png?auto=compress,format&amp;format=webp" alt="Blockchain Transaction" /></p>
<p>Once it is received the miner will validate the transaction and add it to the Blockchain. Once added to Blockchain the data becomes immutable.</p>
<h3 id="heading-block-mining">Block Mining</h3>
<p>Well, till now it's clear that the blockchain is made of a number of blocks. So what are these blocks and which kind of data do they contain?</p>
<p>Well if we see an overview block looks something like the below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631476105347/a9mYl_Xyp.png?auto=compress,format&amp;format=webp" alt="Merkel Tree Example" /></p>
<p>In this, we can see that a single block contain</p>
<ul>
<li><p>Previous Hash</p>
</li>
<li><p>Nonce</p>
</li>
<li><p>TimeStamp</p>
</li>
<li><p>Merkel Root.</p>
</li>
</ul>
<p>But in exactly a block look something like this with a lot of data</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631476237071/CgxoVytuQ.png?auto=compress,format&amp;format=webp" alt="image.png" /></p>
<p>You can see all the transactions and blocks of the public Blockchain. Here I used <a target="_blank" href="https://etherscan.io/"><strong>Etherscan</strong></a> to get the block data but there are a lot of services out there.</p>
<p>So what happens is every time transactions are made they came to miners where miners validate the transactions and then try to add that block to the public Blockchain.</p>
<p>Why I used "try to add"? Instead of adding, well every miner is trying to add a new block to the Blockchain continuously all the time and it's like a race between every miner.</p>
<p>The way blockchain validates whether a block is valid or not is called <strong>Consensus Mechanism</strong>. There are different ways the Consensus Mechanism works one which is very popular is <strong>Proof of Work</strong> others are <em>Proof of Stake</em>***,*** <em>Proof of Capacity</em>***, and*** <em>Proof of Activity</em>.</p>
<p>In this article, we will only talk about the Proof of Work.</p>
<p>In Proof of Work, every miner has to compute a hash value for the block in some given condition.</p>
<p>Let's say you are a miner and you have to calculate a hash value that should start with 4 0's</p>
<p>for example <strong>0000x147a9393258780beef7d</strong></p>
<p>to calculate something like this takes a lot of trial and error and a lot of computational power. And also there is only one thing you can change in the block which is the value of Nonce.</p>
<p>So every time you want a new hash value, you keep incrementing the value of Nonce and by finding a valid hash you can add that hash to the block.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631477900650/hKVQCLFlS.png?auto=compress,format&amp;format=webp" alt="image.png" /></p>
<p>Well if any miner can add to the Blockchain isn't that make the Blockchain untrustable and unsafe?</p>
<p>Well here comes the power of <strong>Decentralization</strong> to save you. Every time a miner adds a block to the Blockchain other miners do a validation check on that block. If the block is valid and matches their own version of the Blockchain if everything is valid they add that Blockchain to their own version of the Blockchain and start mining the new block.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631566844776/tTs4pHjlt.png?auto=compress,format&amp;format=webp" alt="Blockchain.png" /></p>
<p>Say, if some malicious group tries to add an invalid block to the Blockchain for their own profile. After successfully mining the Blockchain their block will be rejected by other miners which can cost them a lot of money and computation power.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631567043591/1_jWHNeQi.png?auto=compress,format&amp;format=webp" alt="Blockchain.png" /></p>
<p>If another miner successfully mines a valid block the whole Blockchain will move to that version of the block and malicious manners have to sync up to mine the next block.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631569630595/hPLQ5gYat.png?auto=compress,format&amp;format=webp" alt="image.png" /></p>
<p>Well, for every successful mining, each miner is given some reward. For mining on BTC Blockchain, it's BTC coin and on mining on ethereum Blockchain, it's ethereum.</p>
<p>fun fact: It's the only time a new coin is created. (It's just an analogy)</p>
<h3 id="heading-block-propagation-and-block-relay">Block propagation and block relay</h3>
<p>Once a block has been mined, it must be propagated to the rest of the network to ensure that all nodes have a complete and up-to-date copy of the blockchain. This is done through a process called block relay, in which the newly mined block is broadcast to other nodes in the network. As explained above.</p>
<h2 id="heading-working-with-consensus-in-bitcoin">Working with Consensus in BitCoin</h2>
<p>Consensus is the mechanism by which the Bitcoin network ensures that all transactions are valid and secure. This is done through a process called proof of work, which we will explore in more detail in the next section.</p>
<h3 id="heading-distributed-consensus-in-open-environments">Distributed Consensus in open environments</h3>
<p>Distributed consensus in open environments like Bitcoin refers to the process of reaching a common agreement among a network of independent nodes without the need for a centralized authority. In Bitcoin, this consensus mechanism is achieved through a process known as mining, in which nodes compete to solve a cryptographic puzzle and add a new block of transactions to the blockchain.</p>
<p>Each node in the Bitcoin network maintains a copy of the blockchain, which contains a record of all transactions that have ever taken place on the network. When a new transaction is initiated, it is broadcast to all nodes on the network. The nodes then verify the transaction by checking that the sender has sufficient funds and that the transaction meets all other necessary criteria. If the transaction is deemed valid, the node adds it to its copy of the blockchain and broadcasts the updated blockchain to the rest of the network.</p>
<p>In order for the network to reach a consensus on the validity of each transaction, all nodes must agree on the current state of the blockchain. This is achieved through the mining process, in which nodes compete to solve a cryptographic puzzle and add a new block of transactions to the blockchain. The first node to solve the puzzle and add a new block to the blockchain is rewarded with newly created bitcoins and transaction fees.</p>
<p>Once a new block has been added to the blockchain, all nodes on the network must update their copy of the blockchain to reflect the new state. This process is called block propagation and block relay, and it is essential for maintaining the consistency and integrity of the network.</p>
<p>The distributed consensus mechanism used in Bitcoin is designed to be resistant to attacks and manipulation. In order for an attacker to successfully manipulate the network, they would need to control a majority of the network's computational power, a scenario known as a 51% attack. This is difficult to achieve due to the high cost and computational resources required to successfully carry out such an attack.</p>
<h2 id="heading-proof-of-work-pow">Proof of Work (PoW)</h2>
<h3 id="heading-introduction">Introduction</h3>
<p>Proof of work is a consensus mechanism that was first introduced in Bitcoin and is now used by many other cryptocurrencies. The basic idea is that miners must solve a cryptographic puzzle to create a new block, and the first miner to do so is rewarded with newly created bitcoins. This incentivizes miners to secure the network and makes it difficult for any one entity to control the network.</p>
<h3 id="heading-hash-cash-pow">Hash Cash PoW</h3>
<p>HashCash, a proof-of-work algorithm, was designed by Adam Back in 1997 to prevent email spam and denial-of-service attacks. HashCash is now also being used in Bitcoin mining.</p>
<h4 id="heading-how-hashcash-works">How HashCash Works</h4>
<p>HashCash is a proof-of-work algorithm that requires a certain amount of computational work to compute. For email use, a textual encoding of a HashCash stamp is added to the header of an email. This stamp serves as proof that the sender has expended a modest amount of CPU time calculating the stamp prior to sending the email. The Hashcash stamp adds extra verification for emails and makes it unlikely that the email is being sent by a spammer. The receiver can verify the stamp at a negligible computational cost.</p>
<h4 id="heading-the-technical-details">The Technical Details</h4>
<p>The header contains the Hashcash format version, the number of partial preimage bits in the hashed code (known as the "bits"), the date that the message was sent, the resource data string being transmitted (such as an email or IP address), and a string of random characters encoded in base64 format. Additionally, the header contains information proving that the required computation has been performed. The recipient verifies the authenticity of the Hashcash stamp via checks including calculating the 160-bit SHA1 hash of the entire string and checking the date of the message to make sure it was sent recently. The recipient also ensures that the email address in the hash string matches any to which the recipient subscribes.</p>
<h4 id="heading-implementation-and-advantagesdisadvantages">Implementation and Advantages/Disadvantages</h4>
<p>HashCash is simple to implement and doesn't require real money, which is advantageous over micropayment proposals. However, it requires computational resources and is thus less accessible from low-end systems. As computers continue to get faster, the difficulty of the calculations required must be increased over time. HashCash can be incrementally deployed, so it can be adopted without a large upfront investment.</p>
<h4 id="heading-applications">Applications</h4>
<p>HashCash is used for false positives in automated spam filtering systems and as a means to slow down comment spam in blogs. It has also been implemented in the Mozilla Thunderbird email client and in Microsoft's Coordinated Spam Reduction initiative.</p>
<p>Overall, HashCash has been effective in combating email spam and denial-of-service attacks and continues to be a valuable tool in the fight against online threats.</p>
<p><img src="https://qph.cf2.quoracdn.net/main-qimg-7f787a1940548c80a94eabde9ff78ca2" alt="What is Hashcash's proof of work? - Quora" /></p>
<h3 id="heading-bitcoin-pow">Bitcoin PoW</h3>
<p>Proof of Work (PoW) is a consensus mechanism used by the Bitcoin network to confirm transactions and add new blocks to the blockchain. It is a computationally intensive process that involves solving a complex mathematical problem called a cryptographic puzzle. The first node to solve the puzzle is rewarded with newly created bitcoins and transaction fees and is responsible for adding a new block of transactions to the blockchain.</p>
<p>The cryptographic puzzle used in Bitcoin's PoW mechanism is called the SHA-256 algorithm. The algorithm takes an input and produces a fixed-length output, known as a hash. The challenge for miners is to find a hash that meets a specific set of criteria, known as the target. This target is set by the network difficulty, which is adjusted every 2016 block to maintain a target block time of 10 minutes.</p>
<p>To solve the cryptographic puzzle, miners use specialized hardware, known as Application-Specific Integrated Circuits (ASICs), to perform billions of hash calculations per second. This process is known as mining, and it requires a significant amount of computational power and energy.</p>
<p>Once a miner solves the cryptographic puzzle and finds a hash that meets the target, they broadcast the new block to the network. Other nodes on the network then verify the block by checking that the transactions included in the block are valid and that the hash meets the target criteria. If the block is deemed valid, it is added to the blockchain, and the miner is rewarded with newly created bitcoins and transaction fees.</p>
<p>One of the benefits of Bitcoin's PoW mechanism is that it is designed to be decentralized, with no central authority controlling the mining process. Any node on the network can become a miner and participate in the mining process, provided they have the necessary hardware and energy resources.</p>
<p>However, there are also some drawbacks to Bitcoin's PoW mechanism. The energy-intensive nature of mining has led to concerns about the environmental impact of the Bitcoin network, with some estimates suggesting that the network consumes as much energy as a small country. Additionally, the increasing difficulty of mining and the centralization of mining pools have made it difficult for individual miners to compete and earn rewards.</p>
<h3 id="heading-attacks-on-pow-and-monopoly-problems">Attacks on Pow and monopoly problems</h3>
<p>While Bitcoin's Proof of Work (PoW) consensus mechanism is designed to be secure, it is still vulnerable to certain types of attacks. One such attack is known as a 51% attack, in which a single entity or group of entities controls more than 50% of the network's computational power. This would give the attacker the ability to manipulate the network by altering transactions, double-spending bitcoins, and blocking or censoring transactions.</p>
<p>A 51% attack is difficult to carry out in practice, as it requires a significant amount of computational power and energy resources. However, it is not impossible, and there have been several instances of smaller blockchains suffering from 51% attacks. In 2018, the cryptocurrency Verge suffered multiple 51% attacks, leading to losses of over $1 million.</p>
<p>Another issue with Bitcoin's PoW mechanism is the centralization of mining pools. Mining pools are groups of miners who combine their computational power and share the rewards of mining. While mining pools are beneficial for individual miners who may not have the resources to mine on their own, they can also lead to centralization and the potential for monopolies.</p>
<p>As mining becomes increasingly difficult and expensive, small-scale miners may drop out, leaving larger mining pools with a greater share of the computational power. This can lead to a situation where a small number of mining pools control the majority of the network's computational power, leading to concerns about centralization and the potential for monopolies.</p>
<p>To illustrate this issue, we can look at the distribution of Bitcoin's computational power, known as the Hashrate. As of March 2023, the top three mining pools control over 50% of the Hashrate, with the largest pool, F2Pool, controlling over 20%.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681453354170/aaebed83-e720-4c1f-8b34-25bff170d9a8.png" alt class="image--center mx-auto" /></p>
<p>(Source: <a target="_blank" href="https://btc.com/stats/pool"><strong>https://btc.com/stats/pool</strong></a>)</p>
<p>While this distribution is not necessarily a cause for concern, it does highlight the potential for centralization and the need for continued efforts to decentralize the mining process.</p>
<h3 id="heading-proof-of-stake">Proof of Stake:</h3>
<p>Proof of stake is an alternative consensus mechanism that is gaining popularity in the cryptocurrency world. Rather than relying on computational power to secure the network, proof of stake requires users to hold a certain amount of the cryptocurrency to participate in the network's consensus process. This incentivizes users to hold and use the cryptocurrency, rather than simply mining it for profit.</p>
<h3 id="heading-proof-of-burn-and-proof-of-elapsed-time">Proof of Burn and Proof of Elapsed Time</h3>
<p>Proof of burn and proof of elapsed time are two other alternative consensus mechanisms that have been proposed. Proof of burn involves burning or destroying coins to demonstrate commitment to the network, while proof of elapsed time involves randomly selecting a validator based on the amount of time they have been participating in the network.</p>
<h3 id="heading-the-life-of-a-bitcoin-miner">The Life of a Bitcoin Miner</h3>
<p>Bitcoin mining is a competitive and constantly evolving industry, with miners competing to earn newly created bitcoins and secure the network. To be successful, miners must have access to specialized hardware and software, as well as a reliable source of electricity to power their operations. The profitability of mining can fluctuate depending on a variety of factors, including the price of bitcoin, the difficulty of mining, and the cost of electricity.</p>
<h3 id="heading-mining-difficulty">Mining Difficulty</h3>
<p>Mining difficulty is a measure of how difficult it is to find a valid hash for a new block in the Bitcoin network. As more miners join the network and more computational power is added, the difficulty of mining increases to maintain a consistent rate of block creation.</p>
<h3 id="heading-mining-pool">Mining Pool</h3>
<p>Mining pools are groups of miners who pool their computational resources together to increase their chances of earning new bitcoins. Pools allow miners to share the rewards for mining new blocks, making it more accessible to smaller-scale miners who may not have the resources to mine on their own.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In conclusion, Bitcoin is a complex and constantly evolving network that relies on a variety of technologies and mechanisms to ensure its security and resilience. From the creation of coins through mining to the consensus mechanisms used to verify transactions, each aspect of the network plays an important role in its success. As the cryptocurrency industry continues to grow and evolve, it will be interesting to see how these technologies and mechanisms continue to develop and adapt to new challenges and opportunities.</p>
]]></content:encoded></item><item><title><![CDATA[Revolutionizing Industries: The Power of Blockchain Applications]]></title><description><![CDATA[Blockchain technology has been gaining a lot of attention in recent years due to its potential to disrupt industries and improve business processes. In this blog, we will explore some of the most promising enterprise applications of blockchain techno...]]></description><link>https://blog.theashishmaurya.me/revolutionizing-industries-the-power-of-blockchain-applications</link><guid isPermaLink="true">https://blog.theashishmaurya.me/revolutionizing-industries-the-power-of-blockchain-applications</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Blockchain technology]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 14 Apr 2023 05:39:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681450594169/f6072b1f-2151-44df-bd23-5a6364e269dc.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Blockchain technology has been gaining a lot of attention in recent years due to its potential to disrupt industries and improve business processes. In this blog, we will explore some of the most promising enterprise applications of blockchain technology, including cross-border payments, know your customer (KYC), food security, a mortgage over blockchain, blockchain-enabled trade, We Trade - trade finance network, supply chain financing, and identity on the blockchain.</p>
<h3 id="heading-cross-border-payments">Cross-Border Payments</h3>
<p>One of the most promising applications of blockchain technology is cross-border payments. Traditional payment systems can be slow, expensive, and prone to errors. Blockchain technology can offer a faster, more secure, and cheaper way to send money across borders. By using blockchain, transactions can be processed in real-time, and intermediaries such as banks can be eliminated, reducing transaction costs.</p>
<p>For example, Ripple is a blockchain-based payment system that aims to facilitate cross-border payments. Ripple allows financial institutions to settle transactions in seconds, with end-to-end tracking and certainty. This technology has already been adopted by several financial institutions, including Santander and American Express.</p>
<h3 id="heading-know-your-customer-kyc">Know Your Customer (KYC)</h3>
<p>KYC is a process that financial institutions use to verify the identity of their customers. This process is crucial for preventing fraud, money laundering, and terrorism financing. However, the traditional KYC process can be time-consuming, expensive, and prone to errors. Blockchain technology can streamline the KYC process by creating a secure and immutable ledger of customer information.</p>
<p>For example, Deloitte has developed a blockchain-based KYC platform that allows financial institutions to share customer data securely and efficiently. This platform can reduce the time and cost of the KYC process, while also improving the accuracy of customer data.</p>
<h3 id="heading-food-security">Food Security</h3>
<p>Food security is a major global challenge, with around 800 million people experiencing hunger or malnutrition. Blockchain technology can help improve food security by creating a transparent and traceable supply chain. By using blockchain, food producers, distributors, and retailers can track the movement of food products, ensuring that they are safe and meet regulatory standards.</p>
<p>For example, Walmart has implemented a blockchain-based system that allows the retailer to track the movement of food products from the farm to the store. This system can quickly identify the source of food contamination, allowing for a faster and more effective response to food safety issues.</p>
<h3 id="heading-mortgage-over-blockchain">Mortgage over Blockchain</h3>
<p>Mortgage over the blockchain is an application of blockchain technology that aims to simplify the mortgage process. By using blockchain, mortgage lenders can create a secure and transparent ledger of mortgage transactions. This ledger can be used to track the ownership and transfer of mortgage assets, as well as to automate the payment and settlement process.</p>
<p>For example, Fannie Mae and Freddie Mac, two of the largest mortgage lenders in the US, are exploring the use of blockchain technology for mortgage transactions. This technology has the potential to reduce the time and cost of mortgage processing, while also improving the accuracy and security of mortgage transactions.</p>
<h3 id="heading-blockchain-enabled-trade">Blockchain-Enabled Trade</h3>
<p>Blockchain-enabled trade is an application of blockchain technology that aims to improve the efficiency and security of global trade. By using blockchain, trade participants can create a secure and transparent ledger of trade transactions, reducing the risk of fraud and errors. This technology can also enable faster and more efficient trade finance, reducing the time and cost of trade transactions.</p>
<p>For example, Maersk and IBM have developed a blockchain-based trade platform that allows participants to track the movement of goods and documents across the supply chain. This platform can reduce the time and cost of trade transactions, while also improving the security and transparency of trade.</p>
<h3 id="heading-we-trade-trade-finance-network">We Trade - Trade Finance Network</h3>
<p>We Trade is a blockchain-based trade finance network that aims to simplify the trade finance process. By using blockchain, We Trade can create a secure and transparent ledger of trade finance transactions, reducing the time and cost of trade finance. This network also allows trade participants to access a range of trade finance services, including financing, insurance, and logistics.</p>
<p>We Trade was developed by a consortium of nine major banks, including HSBC, Deutsche Bank, and Societe Generale. The platform has already processed over $1 billion in trade finance transactions, demonstrating the potential of blockchain technology to transform the trade finance industry.</p>
<h3 id="heading-supply-chain-financing">Supply Chain Financing</h3>
<p>Supply chain financing is an application of blockchain technology that aims to improve the efficiency and transparency of supply chain finance. By using blockchain, suppliers can create a secure and transparent ledger of supply chain transactions, allowing them to access financing more easily and at a lower cost.</p>
<p>For example, Komgo is a blockchain-based platform that aims to streamline the financing of commodities trade. The platform allows suppliers to create a secure and transparent ledger of supply chain transactions, allowing them to access financing more easily and at a lower cost. Komgo has already been adopted by several major commodity trading companies, including Shell and Mercuria.</p>
<h3 id="heading-identity-on-blockchain">Identity on Blockchain</h3>
<p>Identity on the blockchain is an application of blockchain technology that aims to create a secure and transparent system for managing identity information. By using blockchain, individuals can create a digital identity that is secure, private, and verifiable. This technology can help reduce identity theft, fraud, and other forms of cybercrime.</p>
<p>For example, Civic is a blockchain-based identity platform that allows individuals to create a secure and verifiable digital identity. Civic uses biometric authentication, such as fingerprint scanning, to ensure that the identity information is accurate and secure. This technology has already been adopted by several businesses, including BitGo and Brave.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Blockchain technology has the potential to transform many industries, from finance to supply chain management. By creating a secure and transparent ledger of transactions, blockchain technology can improve efficiency, reduce costs, and increase security. As these applications of blockchain technology continue to develop and evolve, we can expect to see even more innovative uses of this groundbreaking technology in the future.</p>
]]></content:encoded></item><item><title><![CDATA[Demystifying Blockchain: Understanding its Inner Workings and Security Aspects"]]></title><description><![CDATA[Introduction: Overview of Blockchain
Blockchain promises to fundamentally solve the issues of time and trust to address inefficiencies in industries such as financial, healthcare, supply chain, logistics, etc. Blockchain's key features include data i...]]></description><link>https://blog.theashishmaurya.me/demystifying-blockchain-understanding-its-inner-workings-and-security-aspects</link><guid isPermaLink="true">https://blog.theashishmaurya.me/demystifying-blockchain-understanding-its-inner-workings-and-security-aspects</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Security]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sat, 01 Apr 2023 16:50:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680367697695/1beae496-9a02-4c95-9caf-81eadc0490db.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction-overview-of-blockchain">Introduction: Overview of Blockchain</h1>
<p>Blockchain promises to fundamentally solve the issues of time and trust to address inefficiencies in industries such as financial, healthcare, supply chain, logistics, etc. Blockchain's key features include data immutability and a shared ledger where transactional updates are performed by a consensus-driven trust system.</p>
<p>With the blockchain system design, we are attempting to build a system that implied trust. This trust system leads to reduced risks, and various applied technology constructs sucha as cryptography, smart contracts, and concesus essentially create gates to not only reduce risk but to also infuse added security into the transaction system.</p>
<h3 id="heading-what-are-public-ledgers">What are Public Ledgers</h3>
<p>A public ledger is a way to keep all the transactions on a particular blockchain open and accessible to the public. This provides transparency and openness, though it is publically available and accessible to the general public this ledger is immutable i.e can't be modified.</p>
<p>Here are some of the examples from the Ethereum Blockchain</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631476237071/CgxoVytuQ.png?auto=compress,format&amp;format=webp" alt="image.png" /></p>
<h3 id="heading-business-logic-with-smart-contact">Business Logic with Smart Contact</h3>
<p><strong>Smart contracts are business logic that is stored on the blockchain (hence immutable) that runs when predetermined conditions are met.</strong> They typically are used to automate the execution of an agreement so that all participants can immediately be certain of the outcome, without any intermediary's involvement or time loss.</p>
<p><strong>Some benefits of using a Smart Contract</strong></p>
<ul>
<li><p><strong>Speed, efficiency, and Accuracy:</strong> Once the conditions are met smart contracts are executed immediately as they are digital and automated, and there's no paperwork to process or filling/refilling documents which can lead to human errors.</p>
</li>
<li><p><strong>Trust and Transparency:</strong> Smart Contract establishes trust as there is no third party involved and once Smart Contracts are deployed it's immutable meaning no one can change the conditions of the contract.</p>
</li>
<li><p><strong>Security:</strong> Blockchain is immutable in nature hence anything deployed on the blockchain is also immutable. On top of the immutability, a Smart contract is highly encrypted and can't be hacked by using current technologies available to humankind.</p>
</li>
<li><p><strong>Savings:</strong> Smart contracts are fully automated and hence do not requires any intermediately to handle transactions, which automatically decreases the time and fees associated with them.</p>
</li>
</ul>
<h2 id="heading-how-blockchain-works">How Blockchain Works</h2>
<p>I have already written an extensive blog about how blockchain works <a target="_blank" href="https://blog.theashishmaurya.me/everything-you-should-know-about-blockchain">here</a>. But In case you don't want to read it below is a point-by-point summary.</p>
<h3 id="heading-blocks-in-blockchain">Blocks in Blockchain</h3>
<p><strong>A Blockchain is made of smaller chunks of transactions called Blocks</strong>. Each transaction creates a new block which is then added to the Blockchain. A block in the blockchain roughly looks like below and has some properties like <strong>pevHash, Timestamp, Merkle Root,</strong> etc like below. This creates an unbreakable chain of blocks that cannot be altered, ensuring the security and integrity of the data. We will look at <strong>Merkle Tree and Hash Pointer</strong> later in this article.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631476105347/a9mYl_Xyp.png?auto=compress,format&amp;format=webp" alt="Merkel Tree Example" /></p>
<h3 id="heading-transactions">Transactions</h3>
<p>A blockchain transaction is a transfer of value between two parties on a blockchain network. It is a fundamental concept of blockchain technology and is critical to the functioning of any blockchain-based system.</p>
<p>When a transaction occurs on the blockchain, it is validated, verified, and then recorded on the blockchain ledger. Each transaction is recorded as a block on the blockchain network, and these blocks are linked together in a chain using cryptographic hash functions.</p>
<p>This linkage is what makes blockchain immutable and increases security. If a Hacker wants to change the data in Blockchain they have to change the linkage of each block through out the Blockchain network.</p>
<p><strong>Below is a representation of How Transactions work in Blockchain.</strong></p>
<p><img src="https://www.euromoney.com/learning/~/media/4305AB9860D34A26ACBD34FCC9422684.png?la=en&amp;hash=31AFCC82578BB687B747D53597B8487825DC2CFA" alt="Blockchain Explained: How does a transaction get into the blockchain? |  Euromoney Learning" /></p>
<h3 id="heading-distributed-consensus">Distributed Consensus</h3>
<p>With the rise of computers and the Internet, data started to be stored in a distributed way this solved a lot of problems but came with its challenges. One of the challenges we faced was the validation of the data which is added and this needed some consensus algorithms.</p>
<p>In Blockchain we also need a consensus mechanism/ algorithm to validate each transaction to be added to the distributed ledger i.e Blockchain. Famously <strong>Proof of Work (POW)</strong> is used in blockchains like bitcoin. Ethereum has moved to <strong>Proof of Stake (POS)</strong> for its consensus mechanism. There are other ways to validate the transaction and once the transaction is validated, it is added to the Blockchain.  </p>
<p><img src="https://devopedia.org/images/article/71/5658.1522506087.jpg" alt="Blockchain Consensus" /></p>
<h3 id="heading-public-vs-private-blockchain">Public Vs Private Blockchain</h3>
<p>Private Blockchains are also known as permission network similarly Public Blockchain network is known as Permisionless Network. A blockchain supporting a cryptocurrency is public in the sense that anyone can participate without a specific identity. Such blockchains typically use a consensus protocol based on <strong>Proof of Work (PoW).</strong></p>
<p>In contrast, permissioned blockchains have evolved as an alternative way to run a blockchain between a group of known, identified participants. A permissioned blockchain provides a way to secure interactions between a group of entities that share a mutual goal but don't fully trust each other, such as businesses that exchange funds, goods, or information. A permissioned blockchain relies on the identities of its peers, and in so doing can use the traditional <strong>Byzantine-fault tolerant (BFT)</strong> consensus.</p>
<p>To understand more about it you can watch the following video:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=VWG9xcwjxUg&amp;t=4s">https://www.youtube.com/watch?v=VWG9xcwjxUg&amp;t=4s</a></div>
<p> </p>
<h3 id="heading-understanding-crypto-currency-to-blockchain">Understanding Crypto Currency to Blockchain</h3>
<p>A cryptocurrency is a form of digital currency that is secured using cryptography, making it difficult to counterfeit or double-spend. Cryptocurrencies operate independently of a central bank and use a decentralized ledger called a blockchain to record transactions. Blockchain technology uses a distributed network of computers to maintain a secure and transparent record of transactions, which cannot be altered without consensus from the network.</p>
<p>Cryptocurrencies like Bitcoin, Ethereum, and Litecoin are among the most popular examples of cryptocurrencies. Bitcoin, the first cryptocurrency, was created in 2009 by an unknown person or group using the pseudonym Satoshi Nakamoto. Bitcoin and other cryptocurrencies have grown in popularity and are now widely accepted as payment by many merchants.</p>
<h3 id="heading-permissioned-model-of-blockchain">Permissioned Model of Blockchain</h3>
<p>A permissioned blockchain is a type of blockchain that restricts access to authorized users. It is sometimes referred to as a private blockchain, as it is not open to the public. In a permissioned blockchain, participants must be granted permission to view or modify the blockchain data.</p>
<p>Permissioned blockchains are often used by businesses and organizations that require more control over their data. For example, a financial institution might use a permissioned blockchain to manage its records and transactions. This would allow the institution to maintain control over its data while still benefiting from the security and transparency of blockchain technology.</p>
<p>In a permissioned blockchain, the consensus is often achieved through a smaller group of nodes or validators, rather than a larger network of nodes as in a public blockchain. This allows permissioned blockchains to be more efficient, as consensus can be reached more quickly.</p>
<p>Overall, permissioned blockchains offer a way for businesses and organizations to benefit from the security and transparency of blockchain technology while still maintaining control over their data. This makes permissioned blockchains an attractive option for many industries, including finance, healthcare, and supply chain management.</p>
<h1 id="heading-overview-of-security-aspects-of-blockchain">Overview of security aspects of Blockchain</h1>
<p>Security is a critical aspect of blockchain technology, as it involves the storage and management of sensitive data. Blockchain technology offers several security measures, including cryptography, consensus mechanisms, and immutability.</p>
<h3 id="heading-basic-crypto-primitives">Basic Crypto Primitives</h3>
<p>Cryptography is a central concept in blockchain technology. It is the science of secure communication in the presence of third parties. Some of the basic crypto primitives used in blockchain technology include:</p>
<ol>
<li><p>Cryptographic Hash Function: A cryptographic hash function is a mathematical function that takes input data of arbitrary size and produces a fixed-size output known as a hash. The output is a unique representation of the input data, and even a slight change in the input data will result in a different hash output. This property makes cryptographic hash functions ideal for securing data integrity in blockchain technology.</p>
</li>
<li><p>Digital Signature: A digital signature is a mathematical scheme used to verify the authenticity of digital documents or messages. It is similar to a handwritten signature but uses digital keys instead of a pen. Digital signatures are used to verify the authenticity of blockchain transactions.</p>
</li>
<li><p>Public Key Cryptography: Public key cryptography, also known as asymmetric cryptography, uses a pair of keys (a public key and a private key) to encrypt and decrypt messages. The public key is used to encrypt the message, while the private key is used to decrypt it. Public key cryptography is used to secure blockchain transactions and ensure the privacy and confidentiality of data.</p>
</li>
</ol>
<h3 id="heading-cryptographic-hash-function">Cryptographic Hash Function</h3>
<p>A cryptographic hash function is a mathematical function that takes input data of arbitrary size and produces a fixed-size output known as a hash. The output is a unique representation of the input data, and even a slight change in the input data will result in a different hash output. Cryptographic hash functions are used in blockchain technology to ensure data integrity and security.</p>
<h3 id="heading-properties-of-the-hash-function">Properties of the Hash Function:</h3>
<p>The properties of the hash function include:</p>
<ol>
<li><p>Deterministic: The same input data will always produce the same hash output.</p>
</li>
<li><p>One-Way: It is computationally infeasible to find the input data from the hash output.</p>
</li>
<li><p>Collision Resistance: It is computationally infeasible to find two different inputs that produce the same hash output.</p>
</li>
<li><p>Fixed Output Length: The hash output is always of a fixed length, regardless of the input data size.</p>
</li>
</ol>
<h3 id="heading-hash-pointer-and-merkle-tree">Hash Pointer and Merkle Tree</h3>
<p>A hash pointer is a pointer that contains the hash of the data it is pointing to. Hash pointers are used in blockchain technology to link blocks together in a chain. A Merkle tree is a data structure that uses hash pointers to efficiently verify the integrity of large amounts of data. In blockchain technology, Merkle trees are used to verify the integrity of transactions.</p>
<h3 id="heading-digital-signature">Digital Signature</h3>
<p>A digital signature is a mathematical scheme used to verify the authenticity of digital documents or messages. It is similar to a handwritten signature but uses digital keys instead of a pen. Digital signatures are used to verify the authenticity of blockchain transactions.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631569095992/rFrz7FzKr.png?auto=compress,format&amp;format=webp" alt="Blockchain Transaction" /></p>
<h3 id="heading-public-key-cryptography">Public Key Cryptography</h3>
<p>Public key cryptography, also known as asymmetric cryptography, is a cryptographic technique that uses a pair of keys - a public key and a private key - to encrypt and decrypt messages. The keys are mathematically related, but it is computationally infeasible to derive the private key from the public key.</p>
<p>In public key cryptography, the public key is widely distributed and can be freely shared with anyone who wants to communicate with the owner of the private key. The private key, on the other hand, is kept secret and only known to the owner.</p>
<p>To encrypt a message, the sender uses the recipient's public key to scramble the message, making it unreadable to anyone who intercepts it. The recipient then uses their private key to decrypt the message, making it readable again.</p>
<p>To sign a message, the sender uses their private key to generate a unique digital signature for the message. The recipient can then use the sender's public key to verify the authenticity of the signature and the message.</p>
<p>Public key cryptography has several advantages over symmetric key cryptography, where the same key is used for both encryption and decryption. One of the main advantages is that public key cryptography does not require the exchange of secret keys, which can be a vulnerability in symmetric key cryptography. Another advantage is that public key cryptography allows for digital signatures, which can be used to verify the authenticity of messages and ensure that they have not been tampered with.</p>
<p>Public key cryptography is widely used in blockchain technology to secure transactions and ensure the privacy and confidentiality of data. In a blockchain network, each user has a unique public key and private key pair, which they use to sign and verify transactions. Transactions are broadcast to the network and verified by other nodes using the sender's public key. Once a transaction is verified, it is added to the blockchain and becomes part of the permanent record.</p>
<h3 id="heading-a-basic-crypto-currency">A basic Crypto Currency</h3>
<p>A basic cryptocurrency is a digital currency that uses cryptography to secure and verify transactions. Bitcoin is the most well-known cryptocurrency, but there are many others, such as Ethereum, Litecoin, and Ripple. Cryptocurrencies use blockchain technology to create a decentralized, peer-to-peer payment network that is not controlled by any central authority. Cryptocurrencies offer several advantages over traditional currencies, including lower transaction fees, faster processing times, and greater transparency. However, they also present some risks, such as</p>
<h2 id="heading-tldr">TL;DR</h2>
<p>The article provides an overview of blockchain technology, including its key features and benefits. It explains the concept of public ledgers, smart contracts, and how blockchain works, including blocks, transactions, and distributed consensus. The article also discusses the difference between public and private blockchains, as well as the security aspects of blockchain technology, including basic crypto primitives, cryptographic hash functions, digital signatures, and public key cryptography. Finally, the article provides a brief overview of cryptocurrencies and their advantages and risks.</p>
]]></content:encoded></item><item><title><![CDATA[Resources to Boost Your Career as a Self-Taught Developer: A Reading List]]></title><description><![CDATA[Introduction
Well, I don't belong to a Tier-1 college, and neither I have a pretty good mentor to guide me, I spent most of my college days stuck in my home (No Thanks to the Pandemic) without proper guidelines and structure and was still able to bag...]]></description><link>https://blog.theashishmaurya.me/resources-to-boost-your-career-as-a-self-taught-developer-a-reading-list</link><guid isPermaLink="true">https://blog.theashishmaurya.me/resources-to-boost-your-career-as-a-self-taught-developer-a-reading-list</guid><category><![CDATA[Developer]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Self Improvement ]]></category><category><![CDATA[Self-taught ]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 24 Mar 2023 06:07:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679638017171/66b534c0-766c-4be6-88b5-e0e3e5b0dfd7.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Well, I don't belong to a Tier-1 college, and neither I have a pretty good mentor to guide me, I spent most of my college days stuck in my home (No Thanks to the Pandemic) without proper guidelines and structure and was still able to bag a first class job as Product Engineer by the end of my last sem of college.</p>
<p>If you are in a similar situation to me or a self-taught developer here is my 2 Penny advice you should listen to, <strong>READ.</strong></p>
<p><strong>Reading can excel your career more than any course can.</strong></p>
<p>Here are my Top suggestion to Read some are biased toward web developers and others are Pretty generic.</p>
<h2 id="heading-design-patterns-and-advance-web-dev-stuff">Design Patterns and Advance Web dev stuff.</h2>
<h3 id="heading-webdevhttpswebdev"><a target="_blank" href="https://web.dev/">Web.dev</a></h3>
<p>If you are obsessed with web performance and good practices this website is the go-to. Web.dev is all about writing cross-browser performant web applications. This is mostly written by the developer and other team members of chrome.</p>
<p>The website offers various resources for web developers, including blog articles, courses, code patterns, case studies, podcasts, and recordings of sessions with the Chrome team. The content covers different areas of web development and includes information on UI, performance, and cross-browser compatibility. The website emphasizes the importance of supporting multiple browsers, and many articles include data on browser compatibility from MDN's Browser Compat Data project.</p>
<p><img src="https://web-dev.imgix.net/image/jxu1OdD7LKOGIDU7jURMpSH2lyK2/R8GB4ZvgVvy4gimaqrXs.png?auto=format" alt="Guidance from Chrome Developer Relations" /></p>
<h3 id="heading-refactoring-guruhttpsrefactoringguru"><a target="_blank" href="https://refactoring.guru/">Refactoring Guru</a></h3>
<p>If you already haven't heard about it you should definitely check it out, this is number one website that can make you better at writing code. This website talks mostly about two things how to <strong>refactor code</strong> and the <strong>design patterns</strong> which you should use.<br />And if you are new, take my word for both are very important to understand while building large-scale systems.  </p>
<p><img src="https://refactoring.guru/images/content-public/logos/logo-new.png?id=97d554614702483f31e38b32e82d8e34" alt="Refactoring.Guru" /></p>
<h2 id="heading-news-and-latest-updates">News and Latest Updates.</h2>
<p>If you are in the Tech world you need to be updated on what's hot in the market and what is happening and for that below is perfect.</p>
<h3 id="heading-devbyteshttpsdevbytescoin"><a target="_blank" href="https://devbytes.co.in/">DevBytes</a></h3>
<p>In this busy world who has the type for reading long news? <strong>DevBytes</strong> fix this issue by crunching down the only important part of Tech news/ blogs in just 64 words. Sick Right?</p>
<p>Wait.. Wait that's not just it, <strong>DevBytes</strong> is a relatively new platform and understands your pain so not only 64 words sort blog DevBytes also have other options like <strong>Daily Digest</strong>, <strong>Code Snippet, Latest Jobs, Tech news,</strong> and whatnot.</p>
<p>If you are busy and juggling between multiple things you might want to try their app and get the most out of your time. Here is the link for the <a target="_blank" href="https://play.google.com/store/apps/details?id=com.candelalabs.devbytes&amp;pcampaignid=pcampaignidMKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1">App</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679594095803/9867114a-5040-481f-9471-6c5855aa6d50.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-hackernewshttpsnewsycombinatorcom"><a target="_blank" href="https://news.ycombinator.com/">HackerNews</a></h3>
<p>HackerNews is a community-driven news aggregator website backed by <strong>Ycombinator</strong> where users submit and vote on technology-related stories. The site covers various topics, including web development, programming, startups, and tech industry news.</p>
<p>It has the most basic UI but it covers almost everything related to Tech, <strong>"If it's happening in Tech is in HN".</strong></p>
<h2 id="heading-personal-blogs">Personal Blogs</h2>
<p>Now, this is totally biased, but here are some of my favorite Author blogs. Which I keep an 👀 on. (You get it right? Eyes on)</p>
<h3 id="heading-josh-w-comeauhttpswwwjoshwcomeaucom"><a target="_blank" href="https://www.joshwcomeau.com/">Josh W. Comeau</a></h3>
<p>If you are a front-end developer and ever thought of building the sickest Blog ever build dude let me tell you, you have already lost to Josh. I mean look at all the personal customization and CSS.<br />Well it's true you might never build a sick blog like him but you can learn a ton from him. The blog covers front-end development, CSS, JavaScript, and design topics. It also features in-depth tutorials and code snippets.</p>
<p><strong>Pro tip</strong>: He also runs a newsletter ✉️ so you don't miss anything from him.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679594878285/818b2178-2a6e-46b8-9b1c-5b17af5f0c47.png" alt class="image--center mx-auto" /></p>
<p>There are tons of blogs out there but it's totally up to you if you find yourself reading this blog now. <strong>Mind giving me a follow?</strong></p>
<h2 id="heading-newsletters">Newsletters</h2>
<p>Newsletters are my favorite, I mean getting the best blogs right into your email? What else do you want? <strong>Chill and Relax.</strong><br />The pain point for Newsletters are they are mostly paid :( but good news mine is not. You can subscribe to my <a target="_blank" href="https://blog.theashishmaurya.me/newsletter">newsletter</a> for free.</p>
<h3 id="heading-bytebytegohttpsblogbytebytegocom"><a target="_blank" href="https://blog.bytebytego.com/">ByteByteGO</a></h3>
<p>This newsletter is Run by Alex Xu a Teacher, A programmer, and A technical writer. He has been delivering amazing blogs and videos around System Design and Interview preparation. If you like looking at the depth of a system or are just curious about how something works definitely check him out.</p>
<h3 id="heading-the-pragmatic-engineerhttpsnewsletterpragmaticengineercomabout"><a target="_blank" href="https://newsletter.pragmaticengineer.com/about">The Pragmatic Engineer</a></h3>
<p>Well, this is another newsletter I closely follow and Like, this has a pinch of knowledge that contains pure Technical topics, as well as business, build around tech and other General topics.<br /><strong>FUN FACT:</strong> While writing this I just received the latest edition to their newsletter, Fate? I don't think so.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So in conclusion! If you're a self-taught developer like me, or if you don't have a mentor to guide you, I've got some advice for you that has helped me become a better developer. My top suggestion is to read! Reading can help excel in your career more than any course can. In this article, I've shared some of my favorite resources for web developers, such as <strong>Web.dev</strong> and <strong>Refactoring Guru</strong>, as well as news and the latest updates sources like <strong>DevBytes</strong> and <strong>HackerNews</strong>. I've also recommended some personal blogs, like <strong>Josh W. Comeau's blog</strong>, and newsletters like <strong>ByteByteGO</strong> and <strong>The Pragmatic Engineer</strong>. By leveraging these resources, you can improve your skills and stay updated with the latest tech trends. So, start reading and enhancing your career prospects!</p>
]]></content:encoded></item><item><title><![CDATA[How to Minimize React Bundle Size for Faster Loading Times]]></title><description><![CDATA[Introduction
Hello 👋, I am Ashish Maurya a software developer and part-time freelance developer. Recently I was given a task to minimize the React bundle size and optimize the whole application as much as possible. Well, this might seem like an easy...]]></description><link>https://blog.theashishmaurya.me/how-to-minimize-react-bundle-size-for-faster-loading-times</link><guid isPermaLink="true">https://blog.theashishmaurya.me/how-to-minimize-react-bundle-size-for-faster-loading-times</guid><category><![CDATA[DebuggingFeb]]></category><category><![CDATA[React]]></category><category><![CDATA[optimization]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ #DebuggingFeb Writeathon]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 10 Mar 2023 17:24:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678468532624/78544a3d-c4da-4406-bb43-b11b1c317ec2.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello 👋, I am Ashish Maurya a software developer and part-time freelance developer. Recently I was given a task to minimize the React bundle size and optimize the whole application as much as possible. Well, this might seem like an easy job but finding the right solution for your test case can be daunting. I am just gonna mention some of the tried and tested methods we used to reduce our React bundle size from 7 MB (main.js) to ~700kb (main.js) and reduced the Initial loading time from more than the 20s to ~1s in fast 3G.</p>
<h3 id="heading-importance-of-fast-loading-times">Importance of fast loading times</h3>
<blockquote>
<p>A one-second delay in page load time has been shown to cause a 7 percent loss in conversion and 11 percent fewer page views. For an online store earning $50,000 a day, that one-second delay adds up to more than $1 million in lost sales each year .</p>
</blockquote>
<p>You can understand how big of a change even 1s can make when it comes to loading time in a large-scale business.</p>
<blockquote>
<p>Amazon found that every 100 milliseconds of latency cost them 1% in sales.</p>
</blockquote>
<p>Below are some of the comparisons I found on <a target="_blank" href="https://www.semrush.com/blog/how-fast-is-fast-enough-page-load-time-and-your-bottom-line/">Rush.com</a> while researching this article.</p>
<ul>
<li><p><strong>if your site loads in 5 seconds, it is faster than approximately 25% of the web</strong></p>
</li>
<li><p><strong>if your site loads in 2.9 seconds, it is faster than approximately 50% of the web</strong></p>
</li>
<li><p><strong>if your site loads in 1.7 seconds, it is faster than approximately 75% of the web</strong></p>
</li>
<li><p><strong>if your site loads in 0.8 seconds, it is faster than approximately 94% of the web</strong></p>
</li>
</ul>
<p>We were able to achieve a very low loading time as of now using the following method and I am gonna show you how can you do that too.<br />Here is a BrowserStack speed lab report.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678034974079/348ad1d4-889d-4615-b889-0801dda61b08.png" alt class="image--center mx-auto" /></p>
<p>We are still working to get a better ranking and will update more optimization methods as we explore them.</p>
<h3 id="heading-react-bundle-size-as-a-factor">React bundle size as a factor</h3>
<p>Let's try to understand how the browser loads our React page. From the server, we ship the HTML file and if you clearly observe the HTML file you will see a script tag that is calling your <code>main.js</code> a chunk that is eventually responsible for everything in your React if you are not using <code>SSR</code>.</p>
<p>The bigger is the <code>main.js</code> chunk also <code>main.css</code> chunk the more time it will take to load and parse. Meaning reducing our React bundle size can eventually reduce the initial page loading time.</p>
<h2 id="heading-analyzing-the-react-bundle">Analyzing the React bundle</h2>
<p>Analyzing the react bundle should be the entry point in optimizing the website's load time. React bundle contains several components and it's important to identify them and pick out the largest bundle to optimize them.</p>
<h3 id="heading-tools-for-analyzing-the-bundle">Tools for analyzing the bundle</h3>
<p>Several tools are available for analyzing the React bundle. Webpack Bundle Analyzer and Source Map Explorer are popular tools that can be used to analyze the bundle's components and their sizes.</p>
<p>In this article, we will be taking a glance at some tools, and then we will learn how to use them to Optimize our React bundle size.</p>
<h4 id="heading-webpack-bundle-analyzerhttpswwwnpmjscompackagewebpack-bundle-analyzer"><a target="_blank" href="https://www.npmjs.com/package/webpack-bundle-analyzer">Webpack bundle Analyzer</a></h4>
<p>If you are using webpack as a bundler this should be your go-to point for getting a better look at your bundle. It is very easy to install and use.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678121318330/9178d2ca-579e-4fb1-af8a-27d0ddca1469.gif" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash"><span class="hljs-comment"># NPM</span>
npm install --save-dev webpack-bundle-analyzer
<span class="hljs-comment"># Yarn</span>
yarn add -D webpack-bundle-analyzer
</code></pre>
<p>for Webpack config:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> BundleAnalyzerPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'webpack-bundle-analyzer'</span>).BundleAnalyzerPlugin;

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-comment">// other webpack config options</span>
  <span class="hljs-attr">plugins</span>: [
    <span class="hljs-comment">// other plugins</span>
    <span class="hljs-keyword">new</span> BundleAnalyzerPlugin(),
  ],
};
</code></pre>
<p>You might be using Craco to extend the webpack plugins in that case you can use the below code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> BundleAnalyzerPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'webpack-bundle-analyzer'</span>).BundleAnalyzerPlugin;

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-comment">// other webpack config options</span>
  <span class="hljs-attr">plugins</span>: [
    <span class="hljs-comment">// other plugins</span>
    <span class="hljs-keyword">new</span> BundleAnalyzerPlugin(),
  ],
};
</code></pre>
<h4 id="heading-source-map">Source Map</h4>
<p>Similarly, you can use a generated Source Map to analyze the bundle and I identify the big chunks in your javascript bundle.<br />Here is a good <a target="_blank" href="https://www.npmjs.com/package/source-map-explorer">npm library</a> to achieve that.</p>
<h2 id="heading-strategies-for-minimizing-react-bundle-size-andamp-implementation">Strategies for minimizing React bundle size &amp; Implementation</h2>
<p>I have compiled a list of effective strategies that have proven successful for us and can benefit your business as well.</p>
<h3 id="heading-using-smaller-libraries">Using smaller libraries</h3>
<p>As you already saw above the bigger bundle can drastically increase your React Bundle size and can negatively impact your loading time. Finding a better alternative is always recommended.</p>
<p>Let's see an example :</p>
<p>A popular library for formatting is Date's Momentjs which is approx 4 MB instead you can use another library that satisfies your needs and has a smaller size.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678128373022/5cb017bb-e905-4237-aea2-94e3a4d681b9.png" alt class="image--center mx-auto" /></p>
<p>I understand there are gonna be times you don't have any option to change the library in our case we were using <code>Monaco</code> one whose uncompressed size is 82 MB and we don't have any other alternative to go with. The following methods will help you solve the issue.</p>
<h3 id="heading-code-splitting">Code splitting</h3>
<p>Now if the above does not work for you or you want to reduce the React bundle size further you can do some Code Splitting. As the project grows the size of the application grows as well, especially when you are using third-party libraries. We can split that code into chunks and only load the chunk needed for the initial page load; the rest are loaded on a need basis. This doesn't reduce the size of your application but divides the React bundle size into chunks which can be <code>lazy</code> loaded as we need them.</p>
<p>If you are using React you can achieve it using <code>React.lazy()</code> but if you want you can use webpack to do this.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// webpack.config.js</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">'./app.js'</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">'bundle.js'</span>,
    <span class="hljs-attr">path</span>: __dirname + <span class="hljs-string">'/dist'</span>,
  },
  <span class="hljs-attr">optimization</span>: {
    <span class="hljs-attr">splitChunks</span>: {
      <span class="hljs-attr">chunks</span>: <span class="hljs-string">'all'</span>,
      <span class="hljs-attr">minSize</span>: <span class="hljs-number">10000</span>,
      <span class="hljs-attr">maxSize</span>: <span class="hljs-number">250000</span>,
    },
  },
};
</code></pre>
<p>Additionally, we will explore how to utilize Code splitting and React's Lazy loading to diminish the overall size.</p>
<h3 id="heading-lazy-loading">Lazy loading</h3>
<p><strong>Lazy loading</strong> is a strategy to identify resources as non-blocking (non-critical) and load these only when needed. It's a way to shorten the length of the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Performance/Critical_rendering_path">critical rendering path</a>, which translates into reduced page load times.</p>
<p>Once the code is split we need to asynchronously load them to the browser on a need basis. React has a method that does it out of the box hence we don't need to take the case or split the code and lazy load them.</p>
<p>For example :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { lazy, Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> MyLazyComponent = lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./MyLazyComponent'</span>));

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">MyLazyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyComponent;
</code></pre>
<p>In the above example, we are Lazy Loading a component. Meaning the Lazy loaded component will not be bundled in the main chunk and will be served by the server when the MyComponent will render.<br />This significantly reduces the React bundle size and optimizes the overall behavior if done right. It's best to have a better insight into user behavior on your website to optimize better using this method.</p>
<p>In my opinion, it's best to start with Route-based splitting and then move on to Component-based splitting.</p>
<p>You can read more about them <a target="_blank" href="https://reactjs.org/docs/code-splitting.html">here</a>.</p>
<h3 id="heading-tree-shaking">Tree shaking</h3>
<p><strong>Tree shaking</strong> is a term commonly used within a JavaScript context to describe the removal of dead code.</p>
<p>It relies on the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export">export</a> statements to detect if code modules are exported and imported for use between JavaScript files.</p>
<p>In modern JavaScript applications, we use module bundlers (e.g., <a target="_blank" href="https://webpack.js.org/">webpack</a> or <a target="_blank" href="https://github.com/rollup/rollup">Rollup</a>) to automatically remove dead code when bundling multiple JavaScript files into single files. This is important for preparing code that is production ready, for example with clean structures and minimal file size.</p>
<h3 id="heading-minification">Minification</h3>
<p><strong>Minification</strong> is a process in which the bundlers try to minimize the code further by removing Whitespaces, and comments, or shortening the long variable names into smaller names.<br />This can be done easily in Webpack by including a minifier plugin called <a target="_blank" href="https://terser.org/">Terser</a>.</p>
<p>You simply install the plugin</p>
<pre><code class="lang-bash">npm install terser-webpack-plugin --save-dev
</code></pre>
<p>or,</p>
<pre><code class="lang-bash">yarn add -D terser-webpack-plugin
</code></pre>
<p>or</p>
<pre><code class="lang-bash">pnpm add -D terser-webpack-plugin
</code></pre>
<p>Then add the plugin to your <code>webpack</code> config. For example:</p>
<pre><code class="lang-bash">const TerserPlugin = require(<span class="hljs-string">"terser-webpack-plugin"</span>);

module.exports = {
  optimization: {
    minimize: <span class="hljs-literal">true</span>,
    minimizer: [new TerserPlugin()],
  },
};
</code></pre>
<p>You can read more about this plugin and its uses <a target="_blank" href="https://webpack.js.org/plugins/terser-webpack-plugin/">here</a>. So that you can tweak it as per your need.</p>
<h3 id="heading-compression">Compression</h3>
<p><strong>Compression</strong> is a technique that is used mostly by servers to compress the assets before serving them over to the network. This makes a whole lot of difference ass such as 70% of your React bundle size can be optimized using this method if your server already not doing them.</p>
<p>Widely accepted Algorithms are Gzip, Brotli, and Deflate. Where Gzip is accepted by all browsers nowadays.</p>
<p>This method is not related to React but it's standard practice, Below we will be using two examples below:</p>
<p>For express servers:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> compression = <span class="hljs-built_in">require</span>(<span class="hljs-string">'compression'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// add compression middleware</span>
app.use(compression());

<span class="hljs-comment">// serve static assets from the build folder</span>
app.use(express.static(path.join(__dirname, <span class="hljs-string">'build'</span>)));

<span class="hljs-comment">// serve index.html for all remaining routes</span>
app.get(<span class="hljs-string">'*'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.sendFile(path.join(__dirname, <span class="hljs-string">'build'</span>, <span class="hljs-string">'index.html'</span>));
});

<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;
app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is listening on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<p>For Nginx Server :</p>
<pre><code class="lang-bash">gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
</code></pre>
<p>You can add the above code to Nginx.config to make all the requests Gziped.</p>
<h2 id="heading-advance-concepts-to-minimize-react-bundle-size">Advance Concepts to minimize React bundle size</h2>
<h3 id="heading-ssr">SSR</h3>
<p>One of the most well-established methods for rendering web content is server-side rendering (SSR). When a user requests a page, SSR generates the complete HTML for the content, which may incorporate information from a datastore or external API.</p>
<p>Simply your React application gets rendered to HTML by the server and then sent to the Browser. By this method, we reduce the huge chunk of Javascript that is needed in the first place to initially load the website.</p>
<p>Once the content is loaded then by the method of <code>hydration</code> we add the javascript to the rendered HTML and the functionality can take place.</p>
<p>SSR has several benefits like better SEO, FP, FCP, TTI being shorter, and FCP = TTI. But it's a complicated process you can use NextJS which does it out of the box and saves a lot of time.</p>
<h3 id="heading-server-component-experimental">Server Component [ Experimental ]</h3>
<p>Server components are the new talk in the town which is supposed to be Zero-bundled Size. Learn more about it <a target="_blank" href="https://reactjs.org/blog/2020/12/21/data-fetching-with-react-server-components.html">here</a>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/TQQPAU21ZUw">https://youtu.be/TQQPAU21ZUw</a></div>
<p> </p>
<h2 id="heading-testing-and-measuring-results">Testing and measuring results</h2>
<h3 id="heading-importance-of-testing">Importance of testing</h3>
<p>After all the optimization how are you gonna know if there's a performance boost or reduction in size or if all the work was in vain or if we really got the result we wanted?</p>
<p>Here are some ways you can check the performance of your react web app.</p>
<h3 id="heading-tools-for-measuring-load-times">Tools for measuring load times</h3>
<ul>
<li><p><strong>Dev Tools:</strong> Almost every famous browser except Safari has this tool inbuilt into the browser itself. You can rich click right now and see inspect right now,</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678466660035/5be7848c-7402-4b34-ae5c-da8966245961.png" alt class="image--center mx-auto" /></p>
<p>  this tool offers several tabs to have better insights but to see the decrease in our React bundle size you should head to the Network tab and filter to JS and CSS like below.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678466776648/4ef2f49c-6b18-432a-a25a-9cd144f3cd71.jpeg" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Google Light House:</strong> This tool gives a full analysis of your web page and extra info like TTL, FCP, SEO, Performance, etc. This is only available in google chrome only.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678466943593/f46cb167-66a7-4c15-bb92-23ae8e078c33.png" alt class="image--center mx-auto" /></p>
</li>
<li><p><a target="_blank" href="https://search.google.com/test/mobile-friendly"><strong>Mobile-Friendly Test</strong></a>: This is especially for mobile pages If your client base is mostly mobile users. You should definitely check it out. This is more used for SEO and how your page is seen by the crawlers.<br />  You can read more about SEO and SEO optimization in the below blog.</p>
</li>
</ul>
<p><a target="_blank" href="https://zainabkhan.hashnode.dev/crack-the-code-of-search-engine-success">crack-the-code-of-search-engine-success</a></p>
<h3 id="heading-comparing-results-before-and-after-implementation">Comparing results before and after implementation</h3>
<p>Here are some of the screenshots I took while debugging the speed and size of the main chunk.</p>
<p>Before Optimization and after code splitting.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678467541954/168b581e-d6a8-4849-86ef-6156c1d493a1.jpeg" alt class="image--center mx-auto" /></p>
<p>After all the optimization.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678467630572/456e03f2-c768-4af7-839b-2875c643a11b.png" alt class="image--center mx-auto" /></p>
<p>The main chunk size is 740kb and the loading time is 2.50s which is in server cold start.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, optimizing React bundle size is crucial for faster loading times, which can significantly impact a business's revenue and user experience. By analyzing the bundle, identifying the largest components, and implementing strategies such as using smaller libraries, code splitting, lazy loading, tree shaking, minification, and compression, developers can reduce React bundle size and improve performance. Additionally, advanced concepts such as server-side rendering and server components can further optimize React applications. Continuous monitoring and optimization are also essential to ensure sustained performance improvements. By implementing these strategies and continuously optimizing, developers can create fast and efficient React applications that provide an excellent user experience.</p>
<h3 id="heading-recap-of-strategies">Recap of strategies</h3>
<p>A recap of strategies mentioned in the article to minimize React bundle size for faster loading times are:</p>
<ol>
<li><p>Analyzing the React bundle</p>
</li>
<li><p>Identifying the largest components</p>
</li>
<li><p>Using smaller libraries</p>
</li>
<li><p>Code splitting</p>
</li>
<li><p>Lazy loading</p>
</li>
<li><p>Tree shaking</p>
</li>
<li><p>Minification</p>
</li>
<li><p>Compression</p>
</li>
<li><p>SSR</p>
</li>
<li><p>Server Component (Experimental)</p>
</li>
</ol>
<p>By implementing these strategies, developers can reduce the initial page loading time and provide a better user experience.</p>
<h3 id="heading-final-thoughts">Final thoughts</h3>
<p>React Bundle size should be kept as less as possible and we should always try to achieve it in a number of possible ways. In this article, I have given you generic strategies which are applicable to all React apps to reduce the React bundle Size.</p>
<p>However, if you have a huge codebase this might not solve all your problems in the next blog I will be talking about the Optimization you can do which is based on the user behavior and how they interact with your website.</p>
<p>If you read my blog so far and enjoyed it try following me on Twitter my handle is <a target="_blank" href="https://twitter.com/theysayamaurya">@theysaymaurya</a>. Or if you need any consulting for your application feel free to reach out to me.</p>
]]></content:encoded></item><item><title><![CDATA[How to Set Up Multiple Git Accounts on the Same Machine Using SSH Keys.]]></title><description><![CDATA[Hello everyone! I'm Ashish Maurya, a full-time software developer and part-time freelancer. With the different projects I work on for different clients, I often have to set up work emails with Git. Unfortunately, it can be tricky to set up multiple G...]]></description><link>https://blog.theashishmaurya.me/how-to-set-up-multiple-git-accounts-on-the-same-machine-using-ssh-keys</link><guid isPermaLink="true">https://blog.theashishmaurya.me/how-to-set-up-multiple-git-accounts-on-the-same-machine-using-ssh-keys</guid><category><![CDATA[Developer]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Git]]></category><category><![CDATA[Freelancing]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Tue, 28 Feb 2023 18:31:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677608068376/040fbd4e-28ca-4ab0-9a20-a04c47abbac0.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello everyone! I'm Ashish Maurya, a full-time software developer and part-time freelancer. With the different projects I work on for different clients, I often have to set up work emails with Git. Unfortunately, it can be tricky to set up multiple Git accounts on the same machine. In this article, I'll show you how to use multiple Git accounts on the same machine using SSH keys.</p>
<h3 id="heading-the-problem">The Problem 😒</h3>
<p>Well setting up one git account is easy setting up multiple accounts is not so much especially when you have to keep switching between the different git accounts. (As I mentioned part-time freelance developer)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676491092855/6102937e-fcab-4d92-8b02-fe05373e6e16.gif" alt class="image--center mx-auto" /></p>
<h3 id="heading-solution">Solution 👌</h3>
<p>There is a way to set up multiple accounts in Git on the same machine using <code>ssh</code> keys. This article will show how to set up numerous git accounts on the same Machine.</p>
<h2 id="heading-setting-up-the-ssh-keys">Setting Up the SSH keys</h2>
<h3 id="heading-generating-ssh-keys">Generating <code>SSH</code> keys.</h3>
<ul>
<li>To generate SSH keys just open your favorite terminal or you can open Git bash and write the following command.</li>
</ul>
<pre><code class="lang-bash">$ ssh-keygen -t ed25519 -C <span class="hljs-string">"your_email@example.com"</span>
</code></pre>
<ul>
<li>Once that is done, you will be prompted to enter a file name. You can name it anything but in case you already have <code>.ssh</code> keys, don't name it the same or else it will be overwritten.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676824877839/07c8a2e7-26b8-4d40-910a-724625707a5d.png" alt class="image--center mx-auto" /></p>
<p>For this article, I will use <code>test</code> it as a dummy username but you can name it anything you like. In case you want to check for existing keys follow this <a target="_blank" href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/checking-for-existing-ssh-keys">Link</a>.</p>
<ul>
<li>After this, you will be asked to enter a passphrase. You can read more about the passphrase <a target="_blank" href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh/working-with-ssh-key-passphrases">here</a>.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676825067064/0d10e611-286c-4dfe-a467-63b2590d844d.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>With SSH keys, if someone gains access to your computer, the attacker can gain access to every system that uses that key. To add an extra layer of security, you can add a passphrase to your SSH key. To avoid entering the passphrase every time you connect, you can securely save your passphrase in the SSH agent.</p>
</blockquote>
<ul>
<li>You will see a key fingerprint will be generated.</li>
</ul>
<h3 id="heading-adding-ssh-key">Adding <code>SSH</code> key</h3>
<ul>
<li>Once you are done with the above steps you will be needing to add the SSH key. For that, you can run the following command.</li>
</ul>
<pre><code class="lang-bash">$ <span class="hljs-built_in">eval</span> <span class="hljs-string">"<span class="hljs-subst">$(ssh-agent -s)</span>"</span>
&gt;&gt; Agent pid 375
</code></pre>
<ul>
<li>Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace the <em>test</em> in the command with the name of your private key file.</li>
</ul>
<pre><code class="lang-bash">$ ssh-add ~/.ssh/<span class="hljs-built_in">test</span>
Identity added: /c/Users/Lenovo/.ssh/<span class="hljs-built_in">test</span> (your_email@example.com)
</code></pre>
<h3 id="heading-adding-the-above-ssh-key-to-github">Adding the above <code>SSH</code> key to GitHub</h3>
<ul>
<li><p>Copy the above SSH public key to your clipboard.</p>
<pre><code class="lang-bash">  $ clip &lt; ~/.ssh/test.pub
    <span class="hljs-comment"># Copies the contents of the test.pub file to your clipboard</span>
</code></pre>
</li>
<li><p>Open the setting in your GitHub account.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676826649834/e7b9ff0a-1ac1-4f71-a076-75b779b9b313.png" alt class="image--center mx-auto" /></p>
<ul>
<li>Open the SSH key &amp; GPG keys from the sidebar.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676826827600/02c0a9e4-cf0b-4b1a-b213-1381822260a4.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Click on add New Key and a prompt will open in that text area paste the keys and Add them.</p>
</li>
<li><p>Once that is added you have added the key Successfully.</p>
</li>
</ul>
<h2 id="heading-adding-more-accounts-and-managing-them">Adding more Accounts and Managing them.</h2>
<h3 id="heading-adding-account">Adding Account</h3>
<p>Now repeat the same process for your work account or personal account. And once done.</p>
<h3 id="heading-maintaining-multiple-accounts">Maintaining multiple Accounts</h3>
<ol>
<li><p>Edit/Create ssh config file (<code>~/.ssh/config</code>):</p>
<pre><code class="lang-bash"> <span class="hljs-comment"># Default github account: personal</span>
 Host github.com
    HostName github.com
    IdentityFile ~/.ssh/personal <span class="hljs-comment"># your personal SSH key</span>
    IdentitiesOnly yes

 <span class="hljs-comment"># Other github account: test</span>
 Host github-test
    HostName github.com
    IdentityFile ~/.ssh/<span class="hljs-built_in">test</span> <span class="hljs-comment">#Your test/ Organization key</span>
    IdentitiesOnly yes
</code></pre>
</li>
<li><p>Adding SSH private key to your agent.</p>
<pre><code class="lang-bash"> $ ssh-add ~/.ssh/personal
 $ ssh-add ~/.ssh/<span class="hljs-built_in">test</span>
</code></pre>
</li>
<li><p>Test the connection.</p>
<pre><code class="lang-bash"> $ ssh -T git@github.com
 $ ssh -T git@github-test
</code></pre>
<p> you will get the following prompt with each command, you might see this kind of warning type <code>yes</code> in each case.</p>
<pre><code class="lang-bash"> The authenticity of host <span class="hljs-string">'github.com (192.30.252.1)'</span> can<span class="hljs-string">'t be established.
 RSA key fingerprint is xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:
 Are you sure you want to continue connecting (yes/no)?</span>
</code></pre>
</li>
<li><p>If everything is OK, you will see these messages:</p>
<pre><code class="lang-yaml"> <span class="hljs-string">Hi</span> <span class="hljs-string">personal!</span> <span class="hljs-string">You've</span> <span class="hljs-string">successfully</span> <span class="hljs-string">authenticated,</span> <span class="hljs-string">but</span> <span class="hljs-string">GitHub</span> <span class="hljs-string">does</span> <span class="hljs-string">not</span> <span class="hljs-string">provide</span> <span class="hljs-string">shell</span> <span class="hljs-string">access.</span>
</code></pre>
<pre><code class="lang-yaml"> <span class="hljs-string">Hi</span> <span class="hljs-string">test!</span> <span class="hljs-string">You've</span> <span class="hljs-string">successfully</span> <span class="hljs-string">authenticated,</span> <span class="hljs-string">but</span> <span class="hljs-string">GitHub</span> <span class="hljs-string">does</span> <span class="hljs-string">not</span> <span class="hljs-string">provide</span> <span class="hljs-string">shell</span> <span class="hljs-string">access.</span>
</code></pre>
</li>
<li><p>Now all are set, just clone your repositories</p>
<pre><code class="lang-bash"> $ git <span class="hljs-built_in">clone</span> git@github-test:org2/project2.git /path/to/project2
 $ <span class="hljs-built_in">cd</span> /path/to/project2
 $ git config user.email <span class="hljs-string">"test@org2.com"</span>
 $ git config user.name  <span class="hljs-string">"Test"</span>
</code></pre>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In conclusion, setting up multiple Git accounts on the same machine can be tricky, but it is possible with the use of SSH keys. By following the steps outlined in this article, you can easily manage multiple Git accounts from the same machine. With SSH keys, you can securely access multiple accounts without having to constantly enter and store passwords.</p>
<h3 id="heading-references">References</h3>
<p>https://github.com<br /><a target="_blank" href="https://gist.github.com/oanhnn/80a89405ab9023894df7">https://gist.github.com/oanhnn/80a89405ab9023894df7</a><br /><a target="_blank" href="https://www.freecodecamp.org/news/manage-multiple-github-accounts-the-ssh-way-2dadc30ccaca/">https://www.freecodecamp.org/news/manage-multiple-github-accounts-the-ssh-way-2dadc30ccaca/</a></p>
]]></content:encoded></item><item><title><![CDATA[How to copy Objects in Javascript]]></title><description><![CDATA[Hello Reader,If you don't already know I am Ashish Maurya, a frontend developer, and all-time learner. I have been building web apps and servers in Javascript enough to write this article.
Note: In javascript everything thing ( well almost everything...]]></description><link>https://blog.theashishmaurya.me/how-to-copy-objects-in-javascript</link><guid isPermaLink="true">https://blog.theashishmaurya.me/how-to-copy-objects-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[tips]]></category><category><![CDATA[js]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sat, 04 Feb 2023 17:14:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675530764318/064852cd-da60-4230-89ed-811d065c3e7d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Reader,<br />If you don't already know I am Ashish Maurya, a frontend developer, and all-time learner. I have been building web apps and servers in Javascript enough to write this article.</p>
<p><mark>Note</mark>: In javascript everything thing ( well almost everything! ) is an Object.</p>
<p>Meaning when I am talking about copying an object that includes, string, arrays, objects, functions, and other data types except null and undefined.</p>
<p>But why do we need to copy an Object in Javascript one may ask?</p>
<p>consider :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj1 = {
    <span class="hljs-attr">a</span> : <span class="hljs-string">"1234"</span>
}

<span class="hljs-keyword">let</span> obj2 = obj1 

obj1.a <span class="hljs-comment">// "1234"</span>
obj2.a <span class="hljs-comment">// "1234"</span>
</code></pre>
<p>Here, we already had an <code>obj1</code> which has a property <code>a</code> we want to have this exact value to be stored in another object say <code>obj2</code>. Now the simplest thing to do is to an assignment operation <code>obj2 = obj1</code> now <code>obj2</code> also has <code>a</code> a property in it.</p>
<p>but, let's change the value <code>obj1.a</code> to something else and see how it affects the <code>obj2</code>.</p>
<p>consider :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj1 = {
    <span class="hljs-attr">a</span> : <span class="hljs-string">"1234"</span>
}

<span class="hljs-keyword">let</span> obj2 = obj1 

obj1.a <span class="hljs-comment">// "1234"</span>
obj2.a <span class="hljs-comment">// "1234"</span>

obj1.a = <span class="hljs-string">"something else"</span>
</code></pre>
<p>Expected behavior :</p>
<pre><code class="lang-javascript">
obj1.a <span class="hljs-comment">// "something else"</span>
obj2.a <span class="hljs-comment">// "1234"</span>
</code></pre>
<p>Actual behavior :</p>
<pre><code class="lang-javascript">obj1.a <span class="hljs-comment">// "something else"</span>
obje2.a <span class="hljs-comment">// "something else"</span>
</code></pre>
<p>That's might seem like a weird side-effect to you but it just means you don't yet understand how javascript stores the values in Input. Let's understand it in the further article.</p>
<h2 id="heading-understanding-javascript-object-mechanisms">Understanding Javascript Object Mechanisms</h2>
<p>To understand the above behavior you need to understand how Javascript Objects work and how the values are stored in the Javascript. Well, Javascript does not store the exact value but instead, it contains a reference to the memory where the value is stored.</p>
<p>Does it make sense? If not below illustration may help you to understand better.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675522394143/e235ced5-3b4d-409d-8bee-a9bbb5aaa5bd.png" alt class="image--center mx-auto" /></p>
<p>As in Above Diagram you can see in <code>MyObject.a</code> and <code>MyObject.b</code> have a value stored where values are <code>Object1</code> and <code>arr1</code> . But In actuality, the value is not stored instead the reference to memory is saved.</p>
<p>So in our previous example when we changed the value of <code>obj1.a</code> to something else the value is changed but <code>obj2</code> still referred to <code>obj1</code> hence it changes with it.</p>
<h2 id="heading-deepcopy-vs-shallowcopy">DeepCopy VS ShallowCopy</h2>
<p>Let's understand these two ways to fully understand how we can finally be able to understand how to copy an object in Javascript.</p>
<ol>
<li><h3 id="heading-shallow-copy">Shallow Copy</h3>
<p> A shallow copy of an object only creates a new reference to the same object, not a completely new object. This means that if you modify a property of the shallow copy, the original object will also be modified because both objects reference the same underlying object.</p>
<p> Example:</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> originalObj = {<span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: {<span class="hljs-attr">c</span>: <span class="hljs-number">2</span>}};
<span class="hljs-keyword">let</span> shallowCopy = <span class="hljs-built_in">Object</span>.assign({}, originalObj);
<span class="hljs-built_in">console</span>.log(originalObj.b === shallowCopy.b) <span class="hljs-comment">// outputs: true</span>
shallowCopy.b.c = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(originalObj.b.c) <span class="hljs-comment">// outputs: 3</span>
</code></pre>
<ol>
<li><h3 id="heading-deep-copy">Deep Copy</h3>
<p> A deep copy, on the other hand, is a copy of an object that is completely independent of the original object. Changes made to the properties of the deep copy will not affect the properties of the original object.</p>
<p> Example:</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> originalObj = {<span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: {<span class="hljs-attr">c</span>: <span class="hljs-number">2</span>}};
<span class="hljs-keyword">let</span> deepCopy = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(originalObj));
<span class="hljs-built_in">console</span>.log(originalObj.b === deepCopy.b) <span class="hljs-comment">// outputs: false</span>
deepCopy.b.c = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(originalObj.b.c) <span class="hljs-comment">// outputs: 2</span>
</code></pre>
<p>Note: Using the above method may cause some problems with <code>Date Object</code> as it's a Javascript Object.</p>
<p>Hence while deep copying it is advised to use the popular OSS library's lodash `<code>_.cloneDeep()` </code> method or write a program that recursively does copy in each level of a nested Javascript Object.</p>
<h2 id="heading-methods-to-copy-objects">Methods to copy Objects.</h2>
<p>In JavaScript, there are several methods to copy an object:</p>
<ol>
<li><h3 id="heading-shallow-copy-using-the-spread-operator">Shallow copy using the spread operator <code>...</code></h3>
</li>
</ol>
<pre><code class="lang-javascript">goCopy codeconst original = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> copy = { ...original };
</code></pre>
<p>Pros:</p>
<ul>
<li><p>Easy to use</p>
</li>
<li><p>Works with all enumerable properties, including arrays and objects</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li>Only creates a shallow copy, meaning that any nested objects or arrays are still referenced and not copied.</li>
</ul>
<ol>
<li><h3 id="heading-shallow-copy-using-objectassign">Shallow copy using Object.assign()</h3>
</li>
</ol>
<pre><code class="lang-javascript">javascriptCopy codeconst original = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> copy = <span class="hljs-built_in">Object</span>.assign({}, original);
</code></pre>
<p>Pros:</p>
<ul>
<li><p>Easy to use</p>
</li>
<li><p>Works with all enumerable properties, including arrays and objects</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li>Only creates a shallow copy, meaning that any nested objects or arrays are still referenced and not copied</li>
</ul>
<ol>
<li><h3 id="heading-deep-copy-using-jsonparsejsonstringifyobj">Deep copy using <code>JSON.parse(JSON.stringify(obj))</code></h3>
</li>
</ol>
<pre><code class="lang-javascript">javascriptCopy codeconst original = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: { <span class="hljs-attr">d</span>: <span class="hljs-number">3</span> } };
<span class="hljs-keyword">const</span> copy = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(original));
</code></pre>
<p>Pros:</p>
<ul>
<li><p>Easy to use</p>
</li>
<li><p>Creates a deep copy, meaning that any nested objects or arrays are also copied</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Will not work for objects with circular references or for non-JSON data types (e.g. functions, symbol properties)</p>
</li>
<li><p>Can be slow for large objects</p>
</li>
</ul>
<ol>
<li><h3 id="heading-deep-copy-using-a-custom-function">Deep copy using a custom function</h3>
</li>
</ol>
<pre><code class="lang-javascript">scssCopy codefunction deepCopy(obj) {
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj !== <span class="hljs-string">'object'</span> || obj === <span class="hljs-literal">null</span>) {
    <span class="hljs-keyword">return</span> obj;
  }

  <span class="hljs-keyword">let</span> copy;
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Array</span>.isArray(obj)) {
    copy = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; obj.length; i++) {
      copy[i] = deepCopy(obj[i]);
    }
  } <span class="hljs-keyword">else</span> {
    copy = {};
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj) {
      <span class="hljs-keyword">if</span> (obj.hasOwnProperty(key)) {
        copy[key] = deepCopy(obj[key]);
      }
    }
  }

  <span class="hljs-keyword">return</span> copy;
}
</code></pre>
<p>Pros:</p>
<ul>
<li><p>Creates a deep copy, meaning that any nested objects or arrays are also copied</p>
</li>
<li><p>Can handle objects with circular references or non-JSON data types</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>More complicated to implement</p>
</li>
<li><p>Slower for large objects compared to JSON.parse(JSON.stringify(obj))</p>
</li>
</ul>
<ol>
<li><h3 id="heading-deep-copy-using-lodashs-clonedeep-method">Deep copy using Lodash's <code>_.cloneDeep()</code> method</h3>
</li>
</ol>
<pre><code class="lang-javascript">javascriptCopy codeconst _ = <span class="hljs-built_in">require</span>(<span class="hljs-string">'lodash'</span>);
<span class="hljs-keyword">const</span> original = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">c</span>: { <span class="hljs-attr">d</span>: <span class="hljs-number">3</span> } };
<span class="hljs-keyword">const</span> copy = _.cloneDeep(original);
</code></pre>
<p>Pros:</p>
<ul>
<li><p>Easy to use</p>
</li>
<li><p>Creates a deep copy, meaning that any nested objects or arrays are also copied</p>
</li>
<li><p>Can handle objects with circular references or non-JSON data types</p>
</li>
<li><p>Generally faster for large objects compared to a custom deep copy function</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Requires the Lodash library to be installed</p>
</li>
<li><p>Adds extra size to your codebase if you only need this single function.</p>
</li>
</ul>
<ol>
<li><h3 id="heading-using-javascripts-native-structuredclone-method">Using Javascript's Native <code>structuredClone()</code> method</h3>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create an object with a value and a circular reference to itself.</span>
<span class="hljs-keyword">const</span> original = { <span class="hljs-attr">name</span>: <span class="hljs-string">"MDN"</span> };
original.itself = original;

<span class="hljs-comment">// Clone it</span>
<span class="hljs-keyword">const</span> clone = structuredClone(original);

<span class="hljs-built_in">console</span>.assert(clone !== original); <span class="hljs-comment">// the objects are not the same (not same identity)</span>
<span class="hljs-built_in">console</span>.assert(clone.name === <span class="hljs-string">"MDN"</span>); <span class="hljs-comment">// they do have the same values</span>
<span class="hljs-built_in">console</span>.assert(clone.itself === clone); <span class="hljs-comment">// and the circular reference is preserved</span>
</code></pre>
<p>Pros :</p>
<ul>
<li>Javascript Native Support hence no library is required.</li>
</ul>
<p>Cons:</p>
<ul>
<li>This method is not a part of ECMAScript it was added to the platform-specific parts.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, copying an object in JavaScript can be a complex task due to its nature of storing references instead of actual values. Shallow copy is created by methods such as spread operator (...), Object.assign(), and only creates a new reference to the same object, modifying the property in the shallow copy will affect the original object. On the other hand, a deep copy creates a completely independent copy of an object, and changes made to the properties of the deep copy will not affect the properties of the original object. It is advised to use popular libraries like lodash to create a deep copy or to write a program that recursively copies each level of a nested Javascript object.</p>
]]></content:encoded></item><item><title><![CDATA[Using Tailwind CSS in NEXTJS 13  with TurboPack]]></title><description><![CDATA[Hello Guys,
I hope you all have seen the NEXTJS conference and all the new things that are shipped with the release of NEXTJS 13, NEXTJS 13 had breaking changes and it changes how we used to work with NEXTJS before and  React in general
Introduction ...]]></description><link>https://blog.theashishmaurya.me/using-tailwind-css-in-nextjs-13-with-turbopack</link><guid isPermaLink="true">https://blog.theashishmaurya.me/using-tailwind-css-in-nextjs-13-with-turbopack</guid><category><![CDATA[Tailwind CSS]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[React]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sat, 29 Oct 2022 08:45:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1667030130547/gojLJCoUr.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Guys,</p>
<p>I hope you all have seen the NEXTJS conference and all the new things that are shipped with the release of NEXTJS 13, NEXTJS 13 had breaking changes and it changes how we used to work with NEXTJS before and  React in general</p>
<h1 id="heading-introduction-to-nextjs-13">Introduction to NEXTJS 13</h1>
<p>Here are some cool features which are launched with NEXTJS 13 launch.</p>
<h2 id="heading-1-turbo-pack">1. Turbo Pack</h2>
<blockquote>
<p>Introducing Turbopack: Rust-based successor to Webpack</p>
</blockquote>
<p>Turbo Pack is a bundler-like web pack but it's powered by Rust and It is said to be 700x faster than Webpack and 10x faster than the famous bundler Vite. </p>
<p>below is the comparison drawing for the turbo pack and other bundlers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666948936704/5q_QsZv67.png" alt="Turbo pack comparison.png" /></p>
<p>Though Turbo might feel amazing, webpack has a vast plugin ecosystem that turbopack lacks for now but Vercel Team is working hard to build those. This is also the reason we can't use preprocessor and Tailwind like we used to use in the Next 12 and earlier versions.</p>
<h2 id="heading-2-nested-routes">2. Nested Routes</h2>
<p>Nested routes are the best and most awaited feature we developers were waiting for though it is already been used in several other frameworks like Remix and it's finally in NEXTJS 13 now.</p>
<p>You will be having a simple app directory that is still in beta where you can define the layout and nested routes easily.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1666949276993/pTVltlvBn.png" alt="Nested Routes.png" /></p>
<p>there are other features like dynamic OG image generation, Image, Layout, server components, and so on.., but with new technology, there is some trade-off as well, and one is we can't use Tailwind like we used to but there is a workaround to do that. </p>
<p>In this article, we will be discussing that workout and will be implementing that too.</p>
<h1 id="heading-installing-tailwindcss-with-nextjs-13">Installing TailwindCSS With NEXTJS 13</h1>
<p>Let's get started with the TailwindCSS and NEXTJS 13 with turbo pack</p>
<blockquote>
<p>Note: Tailwind works fine with the simple command npm run dev but with flag --turbo it won't work as the turbo pack doesn't support the tailwind yet.</p>
</blockquote>
<p>Now that we know that let's start with the basic installation.</p>
<p>if you are liking this article till now let's connect on Twitter :).</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/theysaymaurya/status/1438924150588915716?s=20&amp;t=kyRt69Oek_pc86i07IReRg">https://twitter.com/theysaymaurya/status/1438924150588915716?s=20&amp;t=kyRt69Oek_pc86i07IReRg</a></div>
<h2 id="heading-installing-nextjs-13">Installing NEXTJS 13</h2>
<p>Open your favorite terminal and let's get started with the installation of NEXTJS 13. The following command will also generate the app directory where you can perform nested routes and other new features. </p>
<pre><code>npx create-next-app@latest --experimental-app
</code></pre><p>Once that you can cd into the <code>my-app</code> which is now created.</p>
<h2 id="heading-installing-tailwind-css-in-nextjs-13">Installing tailwind CSS in NEXTJS 13</h2>
<p>Now we will install Tailwind in NEXTJS 13.</p>
<pre><code>npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
</code></pre><p>run the above code inside your terminal which will create a new tailwind.config.js file for you.</p>
<h2 id="heading-setting-up-tailwind-css-in-nextjs-13">Setting Up Tailwind CSS in NEXTJS 13</h2>
<p>Once the installation is done we need to set up the tailwind with PostCSS. Create a new file called <code>postcss.config.js</code> and paste the following content into that.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// postcss.config.js</span>

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">plugins</span>: {
    <span class="hljs-attr">tailwindcss</span>: {},
    <span class="hljs-attr">autoprefixer</span>: {},
  },
};
</code></pre>
<p>once that is done we will configure the <code>tailwind.config.js</code> as per NEXTJS 13 requirements. Here we will be adding an experimental app dir too.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// tailwind.config.js</span>

<span class="hljs-comment">/** <span class="hljs-doctag">@type <span class="hljs-type">{import('tailwindcss').Config}</span> </span>*/</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">content</span>: [<span class="hljs-string">"./pages/**/*.{js,ts,jsx,tsx}"</span>, <span class="hljs-string">"./app/**/*.{js,ts,jsx,tsx}"</span>],
  <span class="hljs-attr">theme</span>: {
    <span class="hljs-attr">extend</span>: {},
  },
  <span class="hljs-attr">plugins</span>: [],
};
</code></pre>
<h2 id="heading-add-the-tailwind-directives-to-your-css">Add the Tailwind directives to your CSS</h2>
<p>once that is done Add the Tailwind directives to your CSS, just open the <code>./app/global.css</code> and paste the below code on top.</p>
<pre><code class="lang-css"><span class="hljs-comment">/* ./app/global.css */</span>

<span class="hljs-keyword">@tailwind</span> base;
<span class="hljs-keyword">@tailwind</span> components;
<span class="hljs-keyword">@tailwind</span> utilities;
</code></pre>
<h2 id="heading-setting-up-the-input-and-output-css-files-for-the-postcss-process">Setting up the input and output CSS files for the postCSS process.</h2>
<p>Now the trick is to concurrently compile our Tailwind CSS and add that to our file using the npm package called <code>concurrently</code>.</p>
<p>Go ahead and install concurrently by running the following command.</p>
<pre><code>npm i concurrently
</code></pre><p>once that is done make a new file in the <code>app directory</code> and call it <code>output.css</code> after that open your <code>package.json</code> and make changes as follows </p>
<pre><code class="lang-json"><span class="hljs-comment">// package.json</span>

<span class="hljs-string">"dev"</span>: <span class="hljs-string">"concurrently \"next dev\" \"tailwindcss --input ./app/globals.css --output ./app/output.css --watch\""</span>,
<span class="hljs-string">"build"</span>: <span class="hljs-string">"tailwindcss ./app/globals.css --output ./app/output.css &amp;&amp; next build"</span>,
</code></pre>
<h2 id="heading-add-compiled-css-to-layouttsx">Add Compiled CSS to <code>layout.tsx</code></h2>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">"next/head"</span>;
<span class="hljs-comment">// import "./globals.css";</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"./output.css"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RootLayout</span>(<span class="hljs-params">{
  children,
}: {
  children: React.ReactNode;
}</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">'en'</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Create Next App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'description'</span> <span class="hljs-attr">content</span>=<span class="hljs-string">'Generated by create next app'</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">'icon'</span> <span class="hljs-attr">href</span>=<span class="hljs-string">'/favicon.ico'</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
  );
}
</code></pre>
<p>as you can see that I have commented on the <code>global.css</code> and imported <code>output.css</code>.</p>
<h2 id="heading-testing-our-code">Testing our Code</h2>
<p>Open the <code>page.tsx</code> inside the app directory and add some TailwindCSS utility classes to your codebase and run <code>npm run dev --turbo</code> to see those changes.</p>
<blockquote>
<p>Note: Make sure you are adding --turbo flag to use the turbo pack.</p>
</blockquote>
<pre><code><span class="hljs-comment">// page.tsx</span>

<span class="hljs-keyword">import</span> Image <span class="hljs-keyword">from</span> <span class="hljs-string">"next/image"</span>;
<span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./page.module.css"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'w-full bg-black'</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'flex justify-center items-center m-auto h-screen flex-col'</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'text-8xl '</span>&gt;</span>
          Welcome to <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">'https://nextjs.org'</span>&gt;</span>Next.js 13!<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'text-4xl my-10 '</span>&gt;</span>
          This is a Tailwind Example with Next.js 13
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">footer</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.footer}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
          <span class="hljs-attr">href</span>=<span class="hljs-string">'https://vercel.com?utm_source=create-next-app&amp;utm_medium=default-template&amp;utm_campaign=create-next-app'</span>
          <span class="hljs-attr">target</span>=<span class="hljs-string">'_blank'</span>
          <span class="hljs-attr">rel</span>=<span class="hljs-string">'noopener noreferrer'</span>
        &gt;</span>
          Powered by{" "}
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.logo}</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">Image</span> <span class="hljs-attr">src</span>=<span class="hljs-string">'/vercel.svg'</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">'Vercel Logo'</span> <span class="hljs-attr">width</span>=<span class="hljs-string">{72}</span> <span class="hljs-attr">height</span>=<span class="hljs-string">{16}</span> /&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">footer</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><h2 id="heading-preview">Preview</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1667028729639/2IFWn-Df3.png" alt="image.png" /></p>
<h1 id="heading-tldr">TL;DR</h1>
<p>Use concurrently with <code>postCSS</code> so that each time it gets compiled the commands are as follows</p>
<pre><code class="lang-JSON"><span class="hljs-comment">// package.json</span>

<span class="hljs-string">"dev"</span>: <span class="hljs-string">"concurrently \"next dev\" \"tailwindcss --input ./app/globals.css --output ./app/output.css --watch\""</span>,
<span class="hljs-string">"build"</span>: <span class="hljs-string">"tailwindcss ./app/globals.css --output ./app/output.css &amp;&amp; next build"</span>,
</code></pre>
<p>If you liked this post and got to learn something new give it a like and let's connect on Twitter.
%[https://twitter.com/theysaymaurya/status/1438924150588915716?s=20&amp;t=kyRt69Oek_pc86i07IReRg]</p>
]]></content:encoded></item><item><title><![CDATA[Flatting An object and Array Using Recursion and other Methods]]></title><description><![CDATA[Hello Guys,
How are you? I decided to write small snippets of code and hacks I find while developing things that might help you guys too.
So Today I Will be showing a recursive way to flatten an array and object . This gonna be a short tutorial for y...]]></description><link>https://blog.theashishmaurya.me/flatting-an-object-and-array-using-recursion-and-other-methods</link><guid isPermaLink="true">https://blog.theashishmaurya.me/flatting-an-object-and-array-using-recursion-and-other-methods</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[hacking]]></category><category><![CDATA[JS Tricks]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Tue, 27 Sep 2022 02:24:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/FXFz-sW0uwo/upload/v1664132611900/U73C0lTqA.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Guys,</p>
<p>How are you? I decided to write small snippets of code and hacks I find while developing things that might help you guys too.</p>
<p>So Today I Will be showing a <strong>recursive way to flatten an array and object</strong> . This gonna be a short tutorial for you guys.</p>
<h1 id="heading-accesing-a-nested-object-using-recursion">Accesing a nested object using Recursion.</h1>
<p>We will be flattening the below Object using our custom-built recursive Function.</p>
<p>sample object</p>
<pre><code class="lang-JSON">
{
  <span class="hljs-attr">"isbn"</span>: <span class="hljs-string">"123-456-222"</span>,
  <span class="hljs-attr">"author"</span>:
  {
    <span class="hljs-attr">"lastname"</span>: <span class="hljs-string">"Doe"</span>,
    <span class="hljs-attr">"firstname"</span>: <span class="hljs-string">"Jane"</span>,
    <span class="hljs-attr">"address"</span>: {
      <span class="hljs-attr">"street"</span>:<span class="hljs-string">"3856 Pooz Street"</span>,
      <span class="hljs-attr">"city"</span>:<span class="hljs-string">"South River"</span>,
      <span class="hljs-attr">"state"</span>:<span class="hljs-string">"New Jersey"</span>,
      <span class="hljs-attr">"counrty"</span>:<span class="hljs-string">"United State"</span>, 
    }
  },
  <span class="hljs-attr">"title"</span>: <span class="hljs-string">"The Ultimate Database Study Guide"</span>,
  <span class="hljs-attr">"category"</span>: [<span class="hljs-string">"Non-Fiction"</span>, <span class="hljs-string">"Technology"</span>]
}
</code></pre>
<h2 id="heading-the-source-code-for-the-recursive-function">The source Code for the Recursive function</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> flat_an_object =<span class="hljs-function">(<span class="hljs-params">object</span>)=&gt;</span>{

  <span class="hljs-keyword">let</span> result = {}

  <span class="hljs-keyword">const</span> recursiveFunction = <span class="hljs-function">(<span class="hljs-params">obj</span>)=&gt;</span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj){
      <span class="hljs-keyword">if</span>(<span class="hljs-keyword">typeof</span> obj[key] === <span class="hljs-string">"object"</span> &amp;&amp; 
         <span class="hljs-built_in">Array</span>.isArray(obj[key]) ===<span class="hljs-literal">false</span>){
        recursiveFunction(obj[key])
      }
      <span class="hljs-keyword">else</span>{
        result ={...result, [key] : obj[key] }
      }
    }
  }
  recursiveFunction(object);
  <span class="hljs-keyword">return</span> result; 
}
</code></pre>
<p>you might ask why I have used the <code>Array.isArray()</code> method in the condition, let's see what is the reason if we remove this method from the Array then what kind of nested object we will get and how that flatten
the object will look like.</p>
<p>This is the result of the flattened Object.</p>
<pre><code class="lang-JSON">
{
  '0': 'Non-Fiction',
  '1': 'Technology',
  isbn: '<span class="hljs-number">123</span><span class="hljs-number">-456</span><span class="hljs-number">-222</span>',
  lastname: 'Doe',
  firstname: 'Jane',
  street: '<span class="hljs-number">3856</span> Pooz Street',
  city: 'South River',
  state: 'New Jersey',
  counrty: 'United State',
  title: 'The Ultimate Database Study Guide'
}
</code></pre>
<p>Here you can see that the object contains an array and it's also getting flattened. I recently posted a tweet about this too and you can see it here to know more about this behavior in Javascript.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/theysaymaurya/status/1574073106863632384?s=20&amp;t=NvwSOYvu9w41BYU_K9DDYA">https://twitter.com/theysaymaurya/status/1574073106863632384?s=20&amp;t=NvwSOYvu9w41BYU_K9DDYA</a></div>
<p>after using that Array.isArray() method we will be getting the flattened Object. Now the object is not a nested object anymore.</p>
<p>results:</p>
<pre><code class="lang-JSON">{
  isbn: '<span class="hljs-number">123</span><span class="hljs-number">-456</span><span class="hljs-number">-222</span>',
  lastname: 'Doe',
  firstname: 'Jane',
  street: '<span class="hljs-number">3856</span> Pooz Street',
  city: 'South River',
  state: 'New Jersey',
  counrty: 'United State',
  title: 'The Ultimate Database Study Guide',
  category: [ 'Non-Fiction', 'Technology' ]
}
</code></pre>
<h1 id="heading-flattening-an-array-or-accessing-a-nested-array">Flattening An Array or Accessing a nested Array</h1>
<p>The same method can be applied to flatten an Array to the thing we change is instead of saying <code>typeof Object   === "object"</code> we will use <code>Array.isArray(key)</code>.</p>
<p>Let's see the code.</p>
<p>sample array</p>
<pre><code class="lang-javascript">

<span class="hljs-keyword">const</span> sampleArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>]]]
</code></pre>
<p>to flatten this array we will just use our previous function and recursively traverse them.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> flatAnArray = <span class="hljs-function">(<span class="hljs-params">array</span>) =&gt;</span> {

  <span class="hljs-keyword">let</span> result = []

  <span class="hljs-comment">// Todo : Define a level </span>

  <span class="hljs-keyword">const</span> recursiveFunction = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> arr) {
      <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Array</span>.isArray(arr[key])) {
        recursiveFunction(arr[key])
      }
      <span class="hljs-keyword">else</span> {
        result.push(arr[key])
      }
    }
  }
  recursiveFunction(array);
  <span class="hljs-keyword">return</span> result;
}
</code></pre>
<p>the output of our code is as follows, we flattened our nested Array.</p>
<pre><code>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>,<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]
</code></pre><h1 id="heading-other-ways-of-flattening-an-array">Other ways of flattening an Array.</h1>
<p>There are several ways to flatten a nested Array in javascript and some inbuild methods are <code>Array.flat()</code> method with a depth infinity.</p>
<pre><code><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>]]]

<span class="hljs-built_in">console</span>.log(arr.flat(infinity))
</code></pre><p>output :</p>
<pre><code>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>,<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]
</code></pre><h3 id="heading-flattening-with-a-depth-of-1">Flattening with a depth of 1</h3>
<p> 1 . using <code>reduce()</code></p>
<pre><code><span class="hljs-keyword">let</span> flatArray = arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, curVal</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> acc.concat(curVal)
}, []);

<span class="hljs-built_in">console</span>.log(flatArray)
</code></pre><ol>
<li>using <code>concat()</code> with <code>apply()</code></li>
</ol>
<pre><code><span class="hljs-keyword">let</span> flatArray1  = [].concat.apply([], arr);
</code></pre><p>outputs:</p>
<pre><code>
[ <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, [ <span class="hljs-number">7</span>, <span class="hljs-number">8</span> ] ]
</code></pre><h1 id="heading-tldr">TL;DR</h1>
<ol>
<li><p>Use recursion to flat a nested object by looping over each property and checking if the <code>typeof</code> the property is of type object, then recursively loop over that object and keep adding the result to the result object. </p>
</li>
<li><p>Use <code>Array.flat()</code> method in case of flattening a nested Array.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[How to Read and Write from CSV File in Nodejs]]></title><description><![CDATA[Hello Guys, here goes another tutorial from my side, today I was building an application, and there I had to read and write from Nodejs.
After a couple of minutes, I quickly come up with a solution thanks to Github Copilot. Well, let's get started on...]]></description><link>https://blog.theashishmaurya.me/how-to-read-and-write-from-csv-file-in-nodejs</link><guid isPermaLink="true">https://blog.theashishmaurya.me/how-to-read-and-write-from-csv-file-in-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[csv]]></category><category><![CDATA[Express.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[hacks]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Fri, 23 Sep 2022 18:40:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1663786455478/Q9TO-Q34o.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Guys, here goes another tutorial from my side, today I was building an application, and there I had to read and write from Nodejs.</p>
<p>After a couple of minutes, I quickly come up with a solution thanks to Github Copilot. Well, let's get started on this tutorial.</p>
<h1 id="heading-reading-writing-to-a-csv-file-using-a-nodejs">Reading writing to a CSV file using a Nodejs</h1>
<h1 id="heading-building-a-nodejs-application">Building a Node.js application</h1>
<p>Let's go ahead and build a simple NodeJs application using npm. If you don't already have Nodejs installed in your system please go ahead and do that.</p>
<pre><code>npm init --y
</code></pre><p><code>--y</code> is an optional flag to start with the default configuration. Once that is done you can put any CSV file you want to read from or write to.</p>
<h2 id="heading-reading-from-csv-file">Reading from CSV file</h2>
<p>First, of all let's look at how we can read the data and parse it in the way we want that, I will be trying only to parse the data in form of the object. Shall we get started?</p>
<h3 id="heading-1-without-using-a-npm-package-and-creating-your-own-csv-parser">1. Without Using a npm package and Creating your own CSV parser</h3>
<pre><code class="lang-javascript">
<span class="hljs-comment">// Importing fs module to read the file </span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>)
<span class="hljs-keyword">const</span> data = fs.readFileSync(<span class="hljs-string">"sample.csv"</span>, <span class="hljs-string">"utf8"</span>) <span class="hljs-comment">// using 'utf8' encoding</span>


<span class="hljs-comment">// splitting the CSV by row as "\n" represents new row</span>
<span class="hljs-keyword">let</span> rows = data.split(<span class="hljs-string">"\n"</span>) 

<span class="hljs-comment">// Getting the attribute from the index 0 of the rows</span>
<span class="hljs-keyword">const</span> getAttribute = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> rows[<span class="hljs-number">0</span>].split(<span class="hljs-string">','</span>)
}

<span class="hljs-comment">// Further splitting the Rows </span>
<span class="hljs-keyword">const</span> getRowData = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> rowData = []
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; rows.length; i++) {
    <span class="hljs-keyword">const</span> row = rows[i].split(<span class="hljs-string">','</span>)
    rowData.push(row)
  }
  <span class="hljs-keyword">return</span> rowData;
}


<span class="hljs-comment">//  The CSV parser </span>
<span class="hljs-keyword">const</span> CSVToObject = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> attributes = getAttribute(data)
  <span class="hljs-keyword">const</span> rowData = getRowData()

  <span class="hljs-keyword">let</span> rowsObj = []
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; rowData.length; i++) {

    <span class="hljs-keyword">let</span> rowObj = {}

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt; rowData[i].length; j++) {
      rowObj[attributes[j]] = rowData[i][j]; <span class="hljs-comment">// converting to object as attribute as key.</span>
    }

    rowsObj.push(rowObj)
  }

  <span class="hljs-keyword">return</span> rowsObj
}

<span class="hljs-keyword">let</span> newData = CSVToObject()

<span class="hljs-built_in">console</span>.log(newData) <span class="hljs-comment">// Output of the data</span>
</code></pre>
<p>In the above code, we are just taking a CSV file reading it, and then splitting it into rows by using the logic that each row is distinguished by "\n". Once that is done we are storing the first row or the 0th index of the array as attributed used in the CSV. Once that is done we are then splitting the rows further by <code>,</code> by using the fact each column in a row is split by  <code>,</code>.</p>
<p>here are the results,</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663786621782/6Pb63uR-Y.png" alt="image.png" /></p>
<h3 id="heading-2-using-3rd-party-library-like-fast-csv">2. Using 3rd Party Library Like Fast CSV.</h3>
<p>Well, if you are not into much programming or you don't have much time to write the logic on your own you can use the npm library like <code>Fast-CSV</code>. It has all the features out of the box and can be easily used with Nodejs.</p>
<p>You can read more about it here. </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.npmjs.com/package/fast-csv">https://www.npmjs.com/package/fast-csv</a></div>
<pre><code>npm install fast-csv

<span class="hljs-comment">//or </span>

yarn add fast-csv
</code></pre><p>once done we will write further code which just consoles logs each row in a format of object</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> csv = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fast-csv"</span>) <span class="hljs-comment">// Importing the Librabry </span>

<span class="hljs-comment">// options which needed for the fast-csv</span>
<span class="hljs-keyword">const</span> options = { <span class="hljs-attr">headers</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">trim</span>: <span class="hljs-literal">true</span> } 

fs.createReadStream(path.resolve(__dirname, <span class="hljs-string">'sample.csv'</span>))
.pipe(csv.parse(options))
  .on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error))
  .on(<span class="hljs-string">'data'</span>, <span class="hljs-function"><span class="hljs-params">row</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(row))
  .on(<span class="hljs-string">'end'</span>, <span class="hljs-function">(<span class="hljs-params">rowCount</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Parse <span class="hljs-subst">${rowCount}</span> rows`</span>))
</code></pre>
<p>further, you can save them as an array of objects by adding a small line of code.</p>
<p>Here are the result :)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663951779328/XX98beNeD.png" alt="image.png" /></p>
<h2 id="heading-writing-to-a-csv-file">Writing to a CSV file</h2>
<p>In this, we will be simply writing a line into a CSV file, and then we will use fast-CSV to achieve the same, logic is similar.</p>
<h3 id="heading-1-creating-your-method-to-write-to-file">1. Creating your method to write to file</h3>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> writeTofile = <span class="hljs-function">()=&gt;</span>{

  <span class="hljs-keyword">let</span> header = <span class="hljs-string">"id ,firstName, LastName,email \n"</span>;

  <span class="hljs-keyword">let</span> data = <span class="hljs-string">"1 ,Ashish,Maurya,ashish.1999vns@gmail.com \n"</span>
  <span class="hljs-keyword">let</span> csv_data = header + data

  <span class="hljs-built_in">console</span>.log(csv_data)
  fs.writeFileSync(<span class="hljs-string">"output.csv"</span> , csv_data , <span class="hljs-string">"utf-8"</span>)
}

writeTofile()
</code></pre>
<p>Output : </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663958180355/0G5tMPOAw.png" alt="image.png" /></p>
<h1 id="heading-the-end">The End</h1>
<p>I hope you learned something new and would love to use these. If you find this meaning full consider following me on Twitter. </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/theysaymaurya/status/1438924150588915716?s=20&amp;t=2kn7s78l866Vd2liXQOvaw">https://twitter.com/theysaymaurya/status/1438924150588915716?s=20&amp;t=2kn7s78l866Vd2liXQOvaw</a></div>
]]></content:encoded></item><item><title><![CDATA[The Need for Modern Professional Network for Developers: Peerlist]]></title><description><![CDATA[Well, hello everyone how are you?  If you are in tech you might have heard about this startup Peerlist; if you haven't, Peerlist is a Professional Network for people in tech. 
You might as but why Peerlist and what's the need when platforms like Gith...]]></description><link>https://blog.theashishmaurya.me/the-need-for-modern-professional-network-for-developers-peerlist</link><guid isPermaLink="true">https://blog.theashishmaurya.me/the-need-for-modern-professional-network-for-developers-peerlist</guid><category><![CDATA[peerlist]]></category><category><![CDATA[Developer]]></category><category><![CDATA[portfolio]]></category><category><![CDATA[recruiters]]></category><category><![CDATA[recruitment]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sun, 18 Sep 2022 09:38:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1663493252290/5I54ap_6E.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Well, hello everyone how are you?  If you are in tech you might have heard about this startup Peerlist; if you haven't, Peerlist is a Professional Network for people in tech. </p>
<p>You might as but why Peerlist and what's the need when platforms like Github, Linkedin even Hashnode is there to showcase our work? Well, let me tell the exact words of the founders and why they are building Peerlist.</p>
<h1 id="heading-why-peerlist">Why Peerlist?</h1>
<p>In a blog post, the co-founder mentioned what was the core problem they were facing so they come up with the idea of a single source of truth Peerlist, where all your blogs and links can be showcased. It's more like a portfolio but very to easy to update and create.</p>
<blockquote>
<p>She (Yogini) had to update her resume and share her work links. EVERY BLOODY TIME. Her work was distributed on different platforms, like Github and DEV. And her LinkedIn profile was useless to showcase her work. Building a personal portfolio website was not feasible, as she was busy with coding assignments and interviews.</p>
</blockquote>
<p>you can read more about this here <a target="_blank" href="https://blog.peerlist.io/why-are-we-building-peerlist">why-are-we-building-peerlist</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663493397671/imogAE3ik.png" alt="image.png" /></p>
<p>Now you might think but if that's the case there are other services like the famous platform LinkedIn. Well, I agree LinkedIn is such a great website to find work and connect with people but there are a lot of things are changed with LinkedIn and now it's not the same LinkedIn we used to remember.</p>
<h1 id="heading-the-expectations-and-reality-check-from-linkedin">The Expectations and Reality check from Linkedin</h1>
<h3 id="heading-expectation-from-linkedin">Expectation from LinkedIn</h3>
<ul>
<li>Gain of Exposure and Job opportunity.</li>
<li>Meeting Peers with the same goals.</li>
<li>Gaining social proof of skills and work.</li>
<li>Getting offered and visible to Recruiters.</li>
</ul>
<p>Well, these might be working still same for a lot of people but you might also agree it's not the same as it used to be and had changed a lot in recent years.</p>
<h3 id="heading-the-linkedin-reality-check">The LinkedIn Reality check</h3>
<ul>
<li><strong> Too Much Motivation</strong>, If you are a dev like me you don't wanna see every post as some kind of random motivational story. A few numbers are kinda ok and they usually do motivate us but the sheer number of motivational posts I see these days are insanely a lot. That kinda ruined the purpose of scrolling and learning about something new or collaborating. </li>
</ul>
<ul>
<li><strong>Random Job Alerts</strong> Getting Radom job updates from in your feed asking you to mention your email in the comment. Well, it's probably fake no recruiter gonna go through the post comment and mail you about your work and establish contact with you. It's mostly as a way of tricking the algorithm into making their post viral and gaining followers.</li>
</ul>
<ul>
<li><strong>Scams</strong>  Idk if you come up with these posts or not but a lot of people are scamming by getting your data and portraying themselves as recruiters and posting jobs.</li>
</ul>
<p>The list goes on .... Well I m not saying LinkedIn is bad but Trust me as a developer you need something which is specially tweaked as per your need.</p>
<h1 id="heading-the-modern-professional-network-for-developers-peerlist">The Modern Professional Network for Developers: Peerlist</h1>
<h2 id="heading-peerlist-for-developers">Peerlist for developers</h2>
<p>Peerlist is not just a portfolio website but has much to offer to developers. Let's see what Peerlist has that makes it unique from other platforms.</p>
<h3 id="heading-1-portfolio-for-developers">1. Portfolio for developers</h3>
<p>Well, It has an amazing portfolio for developers with Integration with other famous platforms such as Hashnode, Github, Dribble, etc.</p>
<p>Here is a funny meme I just created :). Hope it cracks a laugh for you </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663491535567/pGeVWBlPL.png" alt="image.png" /></p>
<p>But, seriously guys it's this easy now to share everything about your dev work with a single work just like as a portfolio but better.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663491807473/2akFGlwsp.png" alt="Peerlistnew.png" /></p>
<p>well doesn't this look good, everything a recruiter might want to see it's there to see?</p>
<h3 id="heading-2-jobs-for-you">2. Job's for you</h3>
<p>Recently Peerlist's new feature is also a Job portal and Applying to them is just one click away. Well, don't believe me go and check out your self it has plenty of jobs for you and the good thing is the recruiter profile is inviting only so getting scammed is out of the box.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663492012787/j_Ran3l1t.png" alt="image.png" /></p>
<h3 id="heading-3-scroll">3. Scroll</h3>
<p>It's a simple feed like most social networking website but there is fewer motivational speaker and more developers. So if you are a developer you might wanna go through this to learn a ton lot of stuff as people are sharing their blogs and repositories or dribble shots to get reviewed and showcased. 
Personally speaking, it's a great place to get inspired and motivated.</p>
<h3 id="heading-4-analytics">4. Analytics</h3>
<p>Well, they also have good analytics inbuilt to give you an idea of how much you are growing on their website and how many people are noticing you.</p>
<h2 id="heading-peerlist-for-recruiters">Peerlist for Recruiters</h2>
<p>This website has hidden gems to offer to recruiters which make their life easy and that is Proof of Work. No recruiter wanna hire someone who bluffs their resume so proof of work is the best way to hire talent from the talent pool. </p>
<p>Recruiters have transparent access to the work a candidate has done in their repository, their project, and blog post ever the candidate has shared in one glance which can be very beneficial for recruiters to judge a candidate in the first round itself.</p>
<p>If that's not something that excites you so let me again mention there is a job portal where you can post jobs and easily filter candidates. </p>
<p>If you are a recruiter go and check out the Peerlist.</p>
<p>I hope you got a sense of what Peerlist is and what they are doing if you like their Idea and want a portfolio or a job. Go check them out and make a profile on their website.</p>
<h1 id="heading-tldr">TL;DR</h1>
<p>Peerlist is awesome if you haven't joined do join them <a target="_blank" href="https://Peerlist.io/">Join Peerlist</a></p>
]]></content:encoded></item><item><title><![CDATA[Validating your React Forms with Zod and no-hooks]]></title><description><![CDATA[Guys, I read this amazing tweet today and this blew my mind 🤯, I am not sure if this is the optimal way to do this but I just felt to document this.
Here is the original tweet 👇
https://twitter.com/davidkpiano/status/1569361453928300545?s=46&t=DcVc...]]></description><link>https://blog.theashishmaurya.me/validating-your-react-forms-with-zod-and-no-hooks</link><guid isPermaLink="true">https://blog.theashishmaurya.me/validating-your-react-forms-with-zod-and-no-hooks</guid><category><![CDATA[React]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Productivity]]></category><category><![CDATA[ReactHooks]]></category><dc:creator><![CDATA[Ashish maurya]]></dc:creator><pubDate>Sat, 17 Sep 2022 08:37:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/nCk22aqZjlM/upload/v1663403724632/xzpb2H8Ca.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Guys, I read this amazing tweet today and this blew my mind 🤯, I am not sure if this is the optimal way to do this but I just felt to document this.</p>
<p>Here is the original tweet 👇</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/davidkpiano/status/1569361453928300545?s=46&amp;t=DcVcr9zqMuG2PK6IqiweWA">https://twitter.com/davidkpiano/status/1569361453928300545?s=46&amp;t=DcVcr9zqMuG2PK6IqiweWA</a></div>
<h1 id="heading-setting-up-a-cra-and-creating-a-form">Setting Up a CRA and creating a form</h1>
<p>I am just gonna get ahead and create a simple form, the basic barebone and structure using JSX</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-string">"./styles.css"</span>;

export default <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>div className<span class="hljs-operator">=</span><span class="hljs-string">"App"</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>form className<span class="hljs-operator">=</span><span class="hljs-string">"form"</span> onSubmit<span class="hljs-operator">=</span>{handleSubmit}<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>label <span class="hljs-keyword">for</span><span class="hljs-operator">=</span><span class="hljs-string">"firstName"</span><span class="hljs-operator">&gt;</span> First name : <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>input
            id<span class="hljs-operator">=</span><span class="hljs-string">"firstName"</span>
            name<span class="hljs-operator">=</span><span class="hljs-string">"firstName"</span>
            <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"text"</span>
            placeholder<span class="hljs-operator">=</span><span class="hljs-string">"John"</span>
          <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>label <span class="hljs-keyword">for</span><span class="hljs-operator">=</span><span class="hljs-string">"lastName"</span><span class="hljs-operator">&gt;</span> last name : <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>input name<span class="hljs-operator">=</span><span class="hljs-string">"lastName"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"text"</span> placeholder<span class="hljs-operator">=</span><span class="hljs-string">"Doe"</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>label htmlFor<span class="hljs-operator">=</span><span class="hljs-string">"email"</span><span class="hljs-operator">&gt;</span> email : <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>input
            id<span class="hljs-operator">=</span><span class="hljs-string">"email"</span>
            name<span class="hljs-operator">=</span><span class="hljs-string">"email"</span>
            <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"email"</span>
            placeholder<span class="hljs-operator">=</span><span class="hljs-string">"john@email.com"</span>
          <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>label <span class="hljs-keyword">for</span><span class="hljs-operator">=</span><span class="hljs-string">"password"</span><span class="hljs-operator">&gt;</span> Password : <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>

          <span class="hljs-operator">&lt;</span>input name<span class="hljs-operator">=</span><span class="hljs-string">"password"</span> <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"password"</span> placeholder<span class="hljs-operator">=</span><span class="hljs-string">"********"</span> <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>div<span class="hljs-operator">&gt;</span>
          <span class="hljs-operator">&lt;</span>label <span class="hljs-keyword">for</span><span class="hljs-operator">=</span><span class="hljs-string">"confirm password"</span><span class="hljs-operator">&gt;</span> Confirm Password : <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>

          <span class="hljs-operator">&lt;</span>input
            name<span class="hljs-operator">=</span><span class="hljs-string">"confirmPassword"</span>
            <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"password"</span>
            placeholder<span class="hljs-operator">=</span><span class="hljs-string">"********"</span>
          <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
        <span class="hljs-operator">&lt;</span>button<span class="hljs-operator">&gt;</span>Submit<span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>button<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>form<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>div<span class="hljs-operator">&gt;</span>
  );
}
</code></pre><p>Preview : </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663401288252/cVTgdrrMz.png" alt="image.png" /></p>
<p>Once this is done your basic non-styled form will look something like this and all you need is to get the user data from the From.</p>
<p>let's create a handle submit function now, if you know react this will be very easy for you but here it goes.</p>
<pre><code>const handleSubmit <span class="hljs-operator">=</span> (e) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    e.preventDefault();
    const formData <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> FormData(e.target);
    const data <span class="hljs-operator">=</span> Object.fromEntries(formData);
    console.log(data);
  };
</code></pre><p>so what is happening here is we are getting the form element and creating a new <code>Form Data</code> once that is done we are converting it into Objects using the javascript method <code>Object.fromEntries(formData)</code></p>
<p>Once that is done let's test our App so far.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1663401795469/f7XXhioC9.gif" alt="formWithZod.gif" /></p>
<h1 id="heading-installing-and-validating-zod">Installing and Validating Zod</h1>
<pre><code>npm i zod

  <span class="hljs-comment">// or</span>

yarn <span class="hljs-keyword">add</span> zod
</code></pre><p>once Zod is installed let's define our schema for the form inputs and then we will try to validate it. In my use case, we will be adding only for firstName, lastName, email, password and confirmPassword.</p>
<pre><code>
const validateSchema <span class="hljs-operator">=</span> z
    .object({
      firstName: z.string().<span class="hljs-built_in">min</span>(<span class="hljs-number">3</span>),
      lastName: z.string(),
      email: z.string().email(),
      password: z.string().<span class="hljs-built_in">min</span>(<span class="hljs-number">6</span>),
      confirmPassword: z.string().<span class="hljs-built_in">min</span>(<span class="hljs-number">6</span>)
    })
    .refine((data) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> data.password <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> data.confirmPassword, {
      message: <span class="hljs-string">"Password doesn't match"</span>,
      path: [<span class="hljs-string">"confirmpassword"</span>]
    });
</code></pre><p>this is a schema on that basis we will be validating our form like below and our new handle submit will look something like this. Now you can add different validation and show the user error message and handle logic of what to do after submitting.</p>
<pre><code>

<span class="solidity">const handleSubmit <span class="hljs-operator">=</span> (e) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    e.preventDefault();
    const formData <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> FormData(e.target);
    const data <span class="hljs-operator">=</span> Object.fromEntries(formData);
    <span class="hljs-keyword">try</span> {
      const validatedForm <span class="hljs-operator">=</span> validateSchema.parse(data);
      console.log(validatedForm);
    } <span class="hljs-keyword">catch</span> (err) {
      console.log(err);
    }
    <span class="hljs-comment">// console.log(data);</span>
  };</span>
</code></pre><h2 id="heading-here-is-our-completed-app">Here is our completed App</h2>
<iframe src="https://codesandbox.io/embed/handling-form-in-react-without-react-hooks-oj9h5p?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe>


<p>Try this out :P</p>
]]></content:encoded></item></channel></rss>