<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Boro on Medium]]></title>
        <description><![CDATA[Stories by Boro on Medium]]></description>
        <link>https://medium.com/@sdotboro?source=rss-4a966f7715b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*05NQHlisIWewlG_seizvDg.png</url>
            <title>Stories by Boro on Medium</title>
            <link>https://medium.com/@sdotboro?source=rss-4a966f7715b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 15:53:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdotboro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AWS image recognition pipeline using S3, SQS, and Rekognition.]]></title>
            <link>https://medium.com/geekculture/aws-image-recognition-pipeline-using-s3-sqs-and-rekognition-6cd5d3aebed8?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cd5d3aebed8</guid>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 20:31:48 GMT</pubDate>
            <atom:updated>2023-01-08T20:31:48.706Z</atom:updated>
            <content:encoded><![CDATA[<p>An image recognition pipeline in AWS, using two parallel EC2 instances, S3 for cloud storage, SQS to communicate between VMs, and Rekognition for the machine learning algorithm to detect objects and texts.</p><p><strong>Goal</strong>: The purpose of this project is to learn how to use the Amazon AWS cloud platform and to develop an AWS application that uses existing cloud services. Specifically, we will learn:</p><ol><li>How to create VMs (EC2 instances) in the cloud.</li><li>How to use cloud storage (S3) in your applications.</li><li>How to communicate between VMs using a queue service (SQS).</li><li>How to program distributed applications in Java on Linux VMs in the cloud.</li><li>How to use a machine learning service (AWS Rekognition) in the cloud.</li></ol><p><strong>Description</strong>: We are building an image recognition pipeline in AWS, using two EC2 instances, S3, SQS, and Rekognition. The project is written in Java on Amazon Linux VMs. For the rest of the description, you should refer to the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qeB3Qwc_a8pKIUAXl45NuQ.png" /><figcaption>Project flow diagram</figcaption></figure><p>We will create two EC2 instances (EC2-A and EC2-B as in the figure), with Amazon Linux AMI, that will work in parallel. Each instance will run a Java application. Instance EC2-A will read 10 images from an S3 bucket (since the S3 bucket was provided by my school I cannot share it in public, but feel free to create an S3 bucket and add 10 images) and performs object detection in the images.</p><p>When a car is detected using Rekognition, with confidence higher than 90%, the index of that image (e.g., 2.jpg) is stored in SQS. Instance EC2-B reads indexes of images from SQS as soon as these indexes are available in the queue, and performs text recognition on these images (i.e., downloads them from S3 one by one and uses Rekognition for text recognition).</p><p>Note that the two instances work in parallel: For example, Instance EC2-A is processing image 3, while Instance EC2-B is concurrently processing image 1 that was recognized as a car by instance A. When Instance EC2-A terminates its image processing, it adds index -1 to the queue to signal to instance EC2-B that its work has been done. When instance EC2-B finishes, it prints to a file, in its associated EBS, the indexes of the images that have both cars and text, and also prints the actual text in each image next to its index.</p><h3>Attempted Solution</h3><p>The following solution was attempted using the AWS account provided by my school. If you have an individual account things should be a little different, but the idea is basically the same.</p><ol><li>Login to your AWS account.</li><li>Once you login to your AWS Lab under Courses &gt; Modules, select <strong>Learner Lab</strong>.</li><li>Start Lab and follow the <strong>Readme</strong> tab (located on top-right along with <strong>Start Lab</strong>, <strong>End Lab</strong>, <strong>AWS Details</strong>, and <strong>Reset</strong> buttons) to start your AWS environment. To start the AWS console make sure you click the AWS button with the green circle. Red circle means the lab is inactive and green circle means the lab is active.</li><li>Make sure you copy the AWS <strong>access_key</strong>, <strong>secret_key</strong>, and <strong>session_token</strong> (can be found in <strong>AWS details </strong>button) and paste it on your ~/.aws/credentials file. Along with that download the <strong>PEM file</strong> under <strong>SSH key</strong> to authenticate later when you access the EC2 instances through terminal. (Copy your AWS keys. These keys are available regardless of a student or an individual account).</li><li>Head over to the AWS Management console and search for EC2. Once you head over to the EC2 Dashboard, the following steps will help create two instances.</li></ol><h3>Create two EC2 instances to work parallelly:</h3><ol><li>Click on Launch instance.</li><li>Enter the name of the EC2 instance you want to create.</li><li>Under the AMI select <strong>Amazon Linux 2 AMI (HVM) — Kernel 5.10, SSD Volume Type</strong>.</li><li>Select Instance type to be <strong>t2.micro</strong>. T2 instances are a low-cost, general purpose instance type that provides a baseline level of CPU performance with the ability to burst above the baseline when needed.</li><li>Select <strong>vockey</strong> as a Key-Pair value which should be pre-populated. Note, you can create your own Key-Pair value with required permissions.</li><li>Under Network Settings, select Create security group and check the below settings.</li></ol><ul><li>Allow SSH traffic from</li><li>Allow HTTPs traffic from the internet</li><li>Allow HTTP traffic from the internet</li><li>And instead of <strong>Anywhere</strong>, select <strong>My IP</strong> to only send traffic from your IP address.</li></ul><p><strong>Note: </strong>It is recommended to not change settings under <strong>Configure storage</strong> and <strong>Advanced details</strong> unless you know what you are doing. Follow the above step twice to create two instances. My instances are named <strong>EC2-A</strong> and <strong>EC2-B</strong> and looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvBuzoO4HNqqlqIArSwI5Q.png" /><figcaption>Running EC2 instances</figcaption></figure><h3>Add IAM roles to the created instances:</h3><ol><li>Once you create your instances, head over to EC2 instances to see your instances. If your instances aren’t running select an instance, click on <strong>Instance state</strong> dropdown and <strong>Start instance</strong>.</li><li>Once instances are running, select an instance (one-by-one) head over to Actions &gt; Security &gt; Modify IAM role.</li><li>From the dropdown select the <strong>**LabInstanceProfile**</strong> which is pre-populated. Please note, this role might not have access to S3, SQS, or Rekognition which is required for the project). And update the IAM role.</li><li>If the IAM role doesn’t have access to S3, SQS, or Recognition, head over to IAM &gt; Roles &gt; LabRole and provide the following permissions as policies:</li></ol><ul><li><a href="https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonSQSFullAccess">AmazonSQSFullAccess</a></li><li><a href="https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonS3FullAccess">AmazonS3FullAccess</a></li><li><a href="https://us-east-1.console.aws.amazon.com/iam/home#/policies/arn:aws:iam::aws:policy/AmazonRekognitionFullAccess">AmazonRekognitionFullAccess</a></li></ul><p>Once the policies are attached you are all set to access the EC2 instances.</p><h3>Working with the JAVA programs:</h3><ul><li>We will have two different programs, one is to recognize <strong>Object</strong> and the other is to recognize <strong>Text</strong>. Please read the project description to understand why we need two programs.</li><li>The object detection program will run on the first instance while the second instance will run the text detection program.</li><li>Please make sure you have the executable JAR files for each of the programs, as we will upload the JAR files in the instances.</li><li>Once you have the JAR files ready you can upload it to the respective EC2 instances using <strong>Cyberduck</strong> (Mac) or <strong>WinSCP</strong> (Windows). I am using Cyberduck for the project since I’m working with a Mac system.</li><li>If you want to learn how to upload file in EC2 instance using Cyberduck, follow the link — <a href="http://www.brianhoshi.com/blog/how-to-ftp-into-your-ec2-instance-with-cyberduck/">FTP into your EC2-instance with Cyberduck</a></li></ul><p><strong>Note</strong>: The username while you FTP to your EC2 instance using Cyberduck should be <strong>ec2-user</strong>.</p><h3>SSH Access from Mac:</h3><p>We will now SSH from Mac to access both our EC2 instances.</p><p><strong>Note</strong>: These instructions are for Mac/Linux users only.</p><ul><li>Please read through the second and third point in this before you start to complete the actions, because you will not be able see these instructions when the AWS Details panel is open.</li><li>Choose the <strong>AWS Details</strong> link.</li><li>Choose the <strong>Download PEM</strong> button and save the <strong>labsuser.pem</strong> file. (Typically your browser will save it to the Downloads directory.)</li><li>Open a terminal window, and change directory cd to the directory where the .pem file was downloaded. For example, run this command, if it was saved to your Downloads directory:</li></ul><pre>cd Downloads</pre><ul><li>Change the permissions on the key to be read only, by running the command:</li></ul><pre>chmod 400 labsuser.pem</pre><ul><li>Return to the AWS Management Console, and in the EC2 service, choose <strong>Instances</strong>. Check the box next to the instance you want to connect.</li><li>In the <em>Description</em> tab, copy the <strong>IPv4 Public IP</strong> value.</li><li>Return to the terminal window and run this command (replace <strong>public-ip</strong> with the actual public IP address you copied):</li></ul><pre>ssh -i &lt;filename&gt;.pem ec2-user@&lt;public-ip&gt;</pre><ul><li>Type yes when prompted to allow a first connection to this remote SSH server. Because you are using a key pair for authentication, you will not be prompted for a password.</li></ul><p>Once we SSH to the two EC2 instances we will have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQvEyq72wNVT2CCOIilS0g.png" /><figcaption>SSH to EC2 instances</figcaption></figure><h3>Run the programs on respective EC2 instance:</h3><ol><li>Make sure to update your <strong>access_key</strong>, <strong>secret_key</strong>, and <strong>default_region</strong> on your AWS terminal.<br>- To update the above information, type <strong>aws configure</strong> on the AWS terminal.<br>- The default region should be <strong>us-east-1</strong>.</li><li>Once you are done with the configuration, run the programs using the command `<strong>java -jar &lt;NAME_OF_YOUR_JAR_FILE&gt;.jar</strong>`.</li><li>For the second program since we want to output the result in a text file, we can use the command `<strong>java -jar &lt;NAME_OF_YOUR_JAR_FILE&gt;.jar &gt; output.txt</strong>`.</li></ol><ul><li>An <strong>output.txt</strong> file will be created and the output of the second program (running on the second instance) will be recorded on the file.</li><li>The file will have the necessary data about the indexes of the images that have both cars and text, and also prints the actual text in each image next to its index.</li></ul><h4>Running program on EC2-A instance (First EC2 instance):</h4><ul><li>Once you run the <strong>AWSObjectDetection.jar</strong> on EC2-A instance the images that satisfies the condition will be pushed to the SQS (Queue).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0XbNEyPwdClLUYa1MB5Jg.png" /><figcaption>Item — 5 pushed to the SQS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V-A48Q90vUnjDkEyPRvrw.png" /><figcaption>Item — 6 pushed to the SQS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jGDGg1vlXGQfKof7VWcVQ.png" /><figcaption>Item — 7 pushed to the SQS</figcaption></figure><ul><li>We have 6 items that are pushed to the queue, since only 6 items satisfies the condition (<strong>Label = “Car” and Confidence &gt; 90</strong>).</li><li>The queue is created like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKVTxgCXJvnXZ9D9kQ94ZA.png" /><figcaption>Queue created</figcaption></figure><ul><li>And the contents of the queues can be obtained by long polling:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQOf3-RZi9VcfBVGE9Vm7g.png" /><figcaption>Queue contents</figcaption></figure><p>Once we populate the queues we can see how does it look when we run the <strong>AWSTextRekognition</strong> program on EC2-B instance.</p><h4>Running program on EC2-B instance (Second EC2 instance):</h4><ul><li>We run the <strong>AWSTextRekognition.jar</strong> on EC2-B instance like so:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*MqFTu8hcyonY8HA-TTRnHw.png" /><figcaption>Snapshot of pogram running on EC2-B instance</figcaption></figure><ul><li>When instance B finishes, it prints to a file (output.txt), the indexes of the images that have both cars and text, and also prints the actual text in each image next to its index.</li><li>The final output stored in output.txt looks like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*_wl2fsEIVLU6GBWvmji1ow.png" /><figcaption>Final output</figcaption></figure><h4>Resources:</h4><ul><li><a href="https://github.com/Boro23-wq/AWS-Image-Recognition-Pipeline">https://github.com/Boro23-wq/AWS-Image-Recognition-Pipeline</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cd5d3aebed8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/aws-image-recognition-pipeline-using-s3-sqs-and-rekognition-6cd5d3aebed8">AWS image recognition pipeline using S3, SQS, and Rekognition.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I built a Pokedex to demonstrate Next.js’ data fetching techniques.]]></title>
            <link>https://medium.com/geekculture/i-built-a-pokedex-to-demonstrate-next-js-data-fetching-techniques-c77a94df8239?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c77a94df8239</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 15:02:53 GMT</pubDate>
            <atom:updated>2021-09-28T15:02:53.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iZQHuLde5nxd9cp1QP2vg.png" /><figcaption>CSR, SSR, SSG w/ Next.js</figcaption></figure><h3>Overview</h3><p>One of the many reasons behind Next.js’s traction is due to the ability to render an application on the client-side (in the browser), on the server-side as well as the ability to statically generate pages during build time. Let us have a good look at what each of these terms means:</p><p><strong>1. Client-side rendering:</strong> In a client-side rendered application, the server essentially sends a blank HTML page (loading state) to the client without any dynamic content. You won’t really see anything meaningful for split seconds. While the loading state is being rendered, the client (the browser) sends multiple API requests to the desired server to fetch the dynamic content and later rehydrates the application with the dynamic data.</p><p><strong>2. Server-side rendering:</strong> In a server-side rendered application, the server pre-renders the page with dynamic data, and eventually once the hydration is done on the server-side, it delivers a fully populated HTML page with dynamic data to the client. Server-side rendering essentially generates the entire HTML for a page on the server.</p><p><strong>3. Static-site regeneration:</strong> Static-site generation generates the pages during build time. Basically, a site that is statically generated will produce the HTML pages ahead of time even before any user requests. And, with Next.js’ Incremental-static regeneration (ISR), we can statically generate on a per-page basis, without needing to rebuild the entire site, which means that you can update the static pages incrementally as new data comes in.</p><h3>How CSR works?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnwpzdUw2SEWGZqbANMOZw.png" /><figcaption>Client-side rendering</figcaption></figure><ul><li>When a client sends a request to the server for a webpage, the server sends a blank HTML page (without any dynamic data) to the client.</li><li>The client immediately serves the blank HTML page with the loading state. (We would notice loading animations most of the time). That is when the client is making those API requests to fetch the dynamic data.</li><li>Once the dynamic data is available the client-side/browser re-hydrates the application with the dynamic/new data.</li></ul><h3>How SSR works?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PgPVcFq6-bhgeDtK8kuQw.png" /><figcaption>Server-side rendering</figcaption></figure><ul><li>When a client sends a request to the server for a webpage, the server essentially pre-renders and prepares the HTML page with all the dynamic data.</li><li>That is the reason why server-side rendering tends to have slow Time To First Byte (TTFB) since they are doing work on the server.</li><li>Once the server sends the pre-rendered page to the client, the client displays the HTML page. This helps avoid multiple trips to request data from the client-side as well.</li></ul><h3>How SSG works?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LKCPWX5-pm_Nx5aeyXKZVA.png" /><figcaption>Static-site generation</figcaption></figure><ul><li>The basic static-site generation involves pre-generating or generating the pages (with/without dynamic data) during the build time even before any user requests.</li><li>The client displays the statically generated page instantly. But there is a certain caveat to this approach. By any chance, if we have a lot of pages to pre-generate, that will significantly increase the build time of the application.</li><li>There’s another really interesting approach involving static-site generation which is called Incremental Static Regeneration (ISR). ISR allows to statically generate on a per-page basis, without needing to rebuild the entire site.</li><li>Which means that an application will serve all the pre-built page as requested, but if the user requests for a page that wasn’t pre-generated, it will serve a fallback version (or a loading state), meanwhile Next.js will make API requests to generate the requested page on the server.</li><li>And on subsequent requests to the same page, Next.js will serve the already generated page and won’t regenerate it.</li></ul><h3>Usecases of CSR, SSR, and SSG</h3><h4>Client-side rendering</h4><ul><li>Authenticated pages or paywall/private dashboard pages.</li><li>Pages with frequent data updates. For eg. Pages with real-time data updates.</li><li>Banking websites where data is requested on-demand.</li><li>Pages that don’t require SEO optimizations.</li></ul><h4>Server-side rendering</h4><ul><li>Can be used with pages that require a heavy workload.</li><li>Websites that require link previews.</li><li>Websites with lots of pages (only render on request).</li><li>Pages that do require SEO optimizations.</li></ul><h4>Static-site generation</h4><ul><li>Documentation pages where data is not frequently updated.</li><li>Blog sites.</li><li>Great for isomorphic applications/websites.</li><li>Pages that do require SEO optimizations.</li></ul><h3>Demo</h3><p>I’ve built a basic application that demonstrates client-side rendering, server-side rendering, and static-site generation using Next.js. You can go ahead and check out the application at <a href="https://pokedexwnext.netlify.app/">Pokedex w/ Next</a>. The application was built in order to implement and help explain Next.js’ data fetching techniques. Next.js provides a really great developer experience by allowing the developers to choose how they want to render the application per-page basis.</p><h3>References</h3><ul><li>Next.js’ data fetching <a href="https://nextjs.org/docs/basic-features/data-fetching">techniques</a>.</li><li>Demo application <a href="https://github.com/Boro23-wq/Pokedex-w-Next">repo</a>.</li><li><a href="https://www.toptal.com/front-end/client-side-vs-server-side-pre-rendering">Toptal</a> — CSR vs SSR vs SSG</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c77a94df8239" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/i-built-a-pokedex-to-demonstrate-next-js-data-fetching-techniques-c77a94df8239">I built a Pokedex to demonstrate Next.js’ data fetching techniques.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload image to AWS S3 (Localstack) using Nest + Typescript.]]></title>
            <link>https://medium.com/geekculture/upload-image-to-aws-s3-localstack-using-nest-typescript-1104bcb5d9ec?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1104bcb5d9ec</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 16:32:08 GMT</pubDate>
            <atom:updated>2021-07-26T16:32:08.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCuR5hFu47zr16tiTtkjzw.png" /></figure><p>At some point in time as a developer, you would very well come across using AWS S3 bucket as storage for uploading files. And that’s what we try to accomplish today. I will take you through the entire flow and let you know the exact setup/configuration I use to start storing any type of files in S3. I’ll be using Nest.js and Typescript for the demonstration. Although you can store anything in an S3 bucket (text files, images, videos, blobs), we will be dealing explicitly with images since we only want to store image files for the demonstration.</p><p>On a side note, we will not require any access/secret AWS config keys since we will be using localstack as the development environment. Localstack, if you don’t know already basically helps us avoid the tedious upfront work that you would generally put in configuring the development environment which I’d say can be a lot time-consuming. In case if you do want to have the access/secret keys, you are great to have those. Include them in a .env file and make sure to pull it out in the S3 config provider file.</p><p>Also, I am using the <a href="https://hub.docker.com/r/localstack/localstack">localstack docker image</a> that will help me support the AWS cloud services like S3. Go ahead and pull the localstack docker image if you don’t have it already. Once you install that, you will be ready to keep going. If you are looking for a guide that will help you install and configure localstack you can visit their <a href="https://github.com/localstack/localstack">Github</a>.</p><h4>Quick steps to install localstack</h4><ul><li>Download the Docker Desktop for your system. You can find the downloadable files <a href="https://www.docker.com/products/docker-desktop">here</a>.</li><li>Pull the localstack docker image from Docker Hub. You can find the image <a href="https://hub.docker.com/r/localstack/localstack">here</a>.</li></ul><h4>S3 Config Provider</h4><p>We have the S3 config provider that does all the setups that we require to get started. Since we don’t actually require any real access/secret keys we can hardcode the keys like so or if you have the keys be sure to pull it out from the .env file. We now have the S3 object with the required config. We have the methods getS3() and getBucketName() to export the S3 object and the name of the bucket to be used anywhere in the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94b18f194115288864f6a84b2576d4f7/href">https://medium.com/media/94b18f194115288864f6a84b2576d4f7/href</a></iframe><p>Also, be sure to run the createBucket() method once to create a bucket for you with the bucket name <strong>testbucket</strong>. You can make use of the last line to create a bucket.</p><h4>Defining the DTO</h4><p>Let us define the DTO of the image file object along with the response object that we will receive once we upload the image to the S3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb6816bd677899f7c810de6d19619c90/href">https://medium.com/media/fb6816bd677899f7c810de6d19619c90/href</a></iframe><p>We are all set with the DTO. Now we can go ahead and define the only route that will handle the HTTP POST request in the controller.</p><h4>Controller Class</h4><p>Inside the controller file, we define the route or path prefix <strong>/upload</strong> that will take care of the action to upload the image file to S3. We are using FileInterceptors to only intercept files with a specific key. The <strong>upload</strong> method below will delegate the rest of the operation to the service file by calling the upload method inside the service file which performs the required logic to upload the image to S3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c6df5107a7d1ae8cc6ebb22d2197d09/href">https://medium.com/media/2c6df5107a7d1ae8cc6ebb22d2197d09/href</a></iframe><p>The primary objective of a controller is to handle incoming requests to one of its endpoints and return responses back to the client. Here, we finally return a response success/error object notifying if the image was uploaded or not. Let us now write the logic to actually upload the image to S3 inside the service class.</p><h4>Service Class</h4><p>The service class (ImageUploadService) is responsible for uploading the image to S3 and is designed to be used by the UploadImageController. What we have here is a basic service class. It creates an instance of the S3 provider to grab the actual S3 object to perform the upload operation on it.</p><p>The essence of a service class or a provider is to organize and share business logic, data, or functions with multiple components within an application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30aa9409abdad777b112a3265b84268f/href">https://medium.com/media/30aa9409abdad777b112a3265b84268f/href</a></iframe><p>We finally return a promise with the resolve/reject object based on if the operation was successful. The very next step is to bundle up the controller and the service file under one roof. A module is commonplace to group components, and services, which are related to the application. Let us do it using the module class.</p><h4>Module Class</h4><p>The <strong>UploadImageModule</strong> class creates a module with the controller and provider files that we’ve created earlier. Every module that we create inside a project can be shared. For example, if we had another module importing the <strong>UploadImageModule</strong>, it would have access to the <strong>UploadImageService</strong> and its methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdeb703dabc2f3f946aad5c5943e68db/href">https://medium.com/media/fdeb703dabc2f3f946aad5c5943e68db/href</a></iframe><p>The very last step is to actually import this module (UploadImageModule) into the root app module. Let us do just that for the final step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53178d47005c130f453c000191f412eb/href">https://medium.com/media/53178d47005c130f453c000191f412eb/href</a></iframe><p>Once we are done importing the UploadImageModule to the root AppModule we are good to test the application. We will be using the <a href="https://www.thunderclient.io/">Thunder Client </a>VSCode extension to test the endpoint. Before firing up the Thunder client make sure to run the Nest server and localstack using the commands below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21bb665fa20d485333a6cced27716c37/href">https://medium.com/media/21bb665fa20d485333a6cced27716c37/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIbjc-j4ImrnXHYg3CRLyg.png" /><figcaption>Thunder Client (Testing the `/upload` endpoint)</figcaption></figure><p>We can see from the image above we receive a response back with the data object containing the Link (URL) of the image uploaded to S3. The image is now accessible from the URL. There you go we are now finally done with implementing a service that uploads image files to an S3 bucket.</p><p>Thanks for sticking around.</p><h4>References</h4><ul><li><a href="https://docs.nestjs.com/">NestJS documentation</a></li><li><a href="https://localstack.cloud/">Localstack</a></li><li><a href="https://www.onixnet.com/insights/aws-101-what-is-amazon-s3-and-why-should-i-use-it">S3 101</a>: What is an S3 and why should I use it?</li><li><a href="https://aws.amazon.com/s3/">AWS S3</a> official website</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1104bcb5d9ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/upload-image-to-aws-s3-localstack-using-nest-typescript-1104bcb5d9ec">Upload image to AWS S3 (Localstack) using Nest + Typescript.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript — Supercharged features of a typed-system]]></title>
            <link>https://medium.com/geekculture/typescript-supercharged-features-of-a-typed-system-b5efafbb0346?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5efafbb0346</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 14:31:11 GMT</pubDate>
            <atom:updated>2021-06-07T14:31:11.478Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typescript — Supercharged features of a typed-system</h3><figure><img alt="Cover" src="https://cdn-images-1.medium.com/max/1024/1*Ce7wNIMZMC_nROx6iPerFA.png" /></figure><p>I have been writing Typescript a lot lately. I’m using it when I work on personal projects or when I’m working with a team. At first, I was just snowed under the fact that I would have to write so much more code and that didn’t really motivate me to pick it up. But that didn’t really stop me from not trying at all. I’ve read so many compelling blogs that proved why Typescript is a must-try and how it helps build scalable web applications, that I couldn’t help but try and get a taste for myself.</p><p>I wanted a resource that will help me get started. I went through the <a href="https://react-typescript-cheatsheet.netlify.app/">React Typescript Cheatsheet</a> which helped me learn the essence right away. I also used a course from <a href="https://www.educative.io/">educative.io</a> that helped me understand the building blocks and pieces. Once I was there I almost instantly knew that even though I was writing more code, I made my codebase very predictable and maintainable so to speak.</p><p>So here I am trying to get across the features that helped me adopt Typescript almost instantly. I’m pretty sure there are tons of benefits of a typed system, but I would just mention a few that I’m liking the most.</p><h4>1. Code Navigation</h4><p>We have a <strong>users.service</strong> file that imports a <strong>User</strong> class. A lot of times it might happen that you can’t quite remember or not sure what the shape of the <strong>User</strong> object might be, or a teammate of yours wanted to check out your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrvWsdEJja3xy17J20BPdg.gif" /><figcaption>Code Navigation</figcaption></figure><p>In that case, you can almost instantly switch between files (or navigate between files). Typescript can help you conveniently navigate between files in your codebase. You can also make use of the shortcuts below to easily navigate between files.</p><ul><li>Go to Definition <strong>(F12)</strong> — Go to the source code of a symbol definition.</li><li>Peek Definition <strong>(Option or Alt + F12)</strong> — Bring up a Peek window that shows the definition of a symbol.</li><li>Go to References <strong>(Shift + F12)</strong> — Show all references to a symbol.</li><li>Go to Implementation <strong>(Cmd or Win + F12)</strong>— Go to the implementations of an interface or abstract method.</li></ul><h4>2. Code Predictability</h4><p>With code-predictability TypeScript assures that variable/function types don’t change and it would only accept the type it was initially defined. If a variable is explicitly given the type - string, it can only hold values of the type - string. All of this makes the codebase so much predictable as you now don’t have to worry about things breaking down due to mismatch in types and assignments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrP732kIvQlERn6Y3z3Fpw.gif" /><figcaption>Code Predictability</figcaption></figure><p>In the gif above, we notice we have a method called <strong>createUser</strong> that accepts a parameter to create a user. Now, there’s definitely a question as to what params it will accept. We try to insert a number but we are instantly thrown a squiggly notifying us about the type-mismatch.</p><p>To know more about the type the method accepts we can navigate to the service file. As we can see, the method <strong>createUser</strong> accepts a param of type string. And, now we are pretty sure about the params when we create couple more users in the future.</p><h4>3. Code Refactoring</h4><p>We have a class called <strong>Users</strong> that we export, which we are using in a lot of files on our codebase. The thing to notice here is that we want to change the <strong>Users</strong> class to be called a <strong>User</strong> (renaming for better naming convention) which makes sense because the <strong>User</strong> class represents the shape of a specific user. Let us try to rename the class and see what we run into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*esDQgpMVLbIFaEB4KQ_g3g.gif" /><figcaption>Code Refactoring</figcaption></figure><p>As you can tell right away from the gif, the controller file turns all red. Not just the controller file but all the files that import the <strong>Users</strong> class will throw an error since the class doesn’t exist anymore.</p><p>This is how convenient code refactoring is with Typescript. We now just need to rename the class in each of the files it is being imported, rather than trying to figure out where you might have used that class. Also with Typescript, if you change the path to a file, the relative import to that file will be updated without you even having to update, which might be well intimidating if you have a lot of imports for the same file.</p><h4>4. Less-error code</h4><p>In a paper published by Microsoft, it has been stated that TypeScript could have helped prevent 15% of the public bugs for public projects on GitHub. This number can be quite significant in terms of saving time during the inspection of common bugs. It helps mitigate the situation where you are trying to figure out the common bugs and your focus is completely diverted which is not really ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rnKRR_38kJGF3NLeJ6b4Lw.gif" /><figcaption>Less-error code</figcaption></figure><p>Typescript helps to check types during compile time which now means that you’ll instantly be thrown an error that could have potentially break your code. It helps prevent shipping buggy code to the production while helping fix bugs relatively faster and with more efficiency.</p><h4>5. Better IntelliSense</h4><p>IntelliSense helps developers be more efficient while writing code. It provides features such as code completion, parameter info, and quick info, which is essentially a way of hinting you about what’s next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZOQRdeLWs2fDAgqPcux_Q.gif" /><figcaption>Code IntelliSense</figcaption></figure><p>In the gif above we assign the <strong>props</strong> to be of type <strong>addNumbers</strong>. We have defined the type of <strong>addNumbers</strong>. Since we have defined the type of the props, we can now have IntelliSense help us with code completion with the right values and methods.</p><p>IntelliSense can do so much more. It can help us with automatic imports, smart renaming of variables, fixing imports when changing relative paths to a file, and removing unused variables/methods.</p><h4>Wrap Up</h4><p>I would highly encourage you to try using TypeScript to have a first-hand experience and to try all the features that it enables, as we discussed earlier. It will very much help skyrocket the productivity levels while you write code and makes your codebase maintainable and scalable. If you are looking for a starting point I highly recommend you to visit the <a href="https://www.typescriptlang.org/docs/">Typescript — Getting started</a> guide to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5efafbb0346" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/typescript-supercharged-features-of-a-typed-system-b5efafbb0346">Typescript — Supercharged features of a typed-system</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nest.js — Architectural Pattern, Controllers, Providers, and Modules.]]></title>
            <link>https://medium.com/geekculture/nest-js-architectural-pattern-controllers-providers-and-modules-406d9b192a3a?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/406d9b192a3a</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Sat, 15 May 2021 06:48:08 GMT</pubDate>
            <atom:updated>2021-05-18T20:48:18.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nest.js — Architectural Pattern, Controllers, Providers, and Modules.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xr5SMRyS8LEuu76UU4JE1g.png" /></figure><h3>Introduction.</h3><blockquote><em>Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, and is built with and fully supports TypeScript. — </em><a href="https://docs.nestjs.com/"><em>NestJS Docs</em></a></blockquote><p>Essentially, NestJS is a layer on top of Node that has supercharged methods and implementations that can help us write server-side applications quick and easy. Nest is very convenient to content all your needs. It is highly customizable and by default uses Express under the hood but can be optionally configured to use Fastify as well!</p><h3>Why might we need Nest.js when we have Node.js?</h3><ul><li>Nest provides a layer of abstraction on top of Node, which means that it can now leverage the features of Node as well as expose supercharged APIs for better performance and efficiency.</li><li>Developers love features and when you know you got more of them, you simply can’t deny it. That’s the case with Nest.js. You have now access to tons of third-party modules that can speed up your development process.</li><li>I believe it’s not at all a complete deviation from the back-end paradigm. We are still writing the same kind of code, a very similar structure but with an added layer of robustness.</li><li>NestJS is also highly configurable with ORM’s (like TypeORM) which we can make use of to work with databases. This again means that you also have great TypeORM features like Active Record and Data Mapper pattern that you can now leverage easily. The Active Record pattern can necessarily help you obtain simplicity while the Data Mapper pattern can help your code be more maintainable.</li><li>Another point to add is that Nest admits that its architecture is heavily inspired by the Angular framework. It’s always a good idea of having effortless testing available when in need and a way to maintain the codebase efficiently. And, Nest provides you just that. A much-needed structure!</li></ul><h3>3-Tier Architecture Nest.js is predisposed towards.</h3><p>When we talk about laying down a firm architecture, the most we care about is how we isolate different parts of an application such that the part that makes sense together lives together. Following an architectural pattern can supposedly help resolve spaghetti code that you might be writing.</p><p>For example: Considering the flow diagram below, we realize that controllers and service layer work together to carry out a logic but are entirely two different things. Controllers essentially deal with the routes of your application. A controller may have few different routes and it all depends on the routing mechanism to control which controller receives what request. But what if you dump all your business logic inside of the controllers. Maybe register a new user if the user is not yet registered or carry out validation checks just within the controllers.</p><p>That doesn’t make too much sense after all. It wouldn’t probably make much difference if you just have a small application. But when the application grows and you have to register more controllers and routes and have to write more business logic, that’s where things seem to get out of control and are certainly not maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*iO7R3erL7nquWs6vfm3cMA.png" /><figcaption>Fig: 3-layer architecture.</figcaption></figure><p>1. <strong>Controllers:</strong> A controller’s sole purpose is to receive requests for the application and deal with routes.</p><p>2. <strong>Service Layer:</strong> This part of the block should only include business logic. For example, all the CRUD operations and methods to determine how data can be created, stored and updated.</p><p>3. <strong>Data Access Layer: </strong>This layer takes care and provides logic to access data stored in persistent storage of some kind. For example an ODM like Mongoose.</p><h3>NestJS Project Directory structure.</h3><p>Once you scaffold a new NestJS project using its CLI, it gives you a few boilerplate files to start with. These are the core files that you would normally work with. The directory structure would look something like this:</p><pre>src<br>| — app.controller.spec.ts<br>| — app.controller.ts<br>| — app.module.ts<br>| — app.service.ts<br>| — main.ts</pre><p><strong><em>app.controller.ts:</em></strong> Controller file that will contain all the application routes.</p><p><strong><em>app.controller.spec.ts:</em></strong> This file would help writing out unit tests for the controllers.</p><p><strong><em>app.module.ts:</em></strong> The module file essentially bundles all the controllers and providers of your application together.</p><p><strong><em>app.service.ts:</em></strong> The service will include methods that will perform a certain operation. For example: Registering a new user.</p><p><strong><em>main.ts:</em></strong><em> </em>The entry file of the application will take in your module bundle and create an app instance using the NestFactory provided by Nest.</p><p>Right away you know that there’s a certain structure laid out that you need to follow. And that is what helps developers write clean, scalable, and maintainable code.</p><h3>Let us look at some code.</h3><p>Let us create a service file and export a class called CatsService which will implement a few methods which we can import and utilize in our controller file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc880cf99603cf68d89439a2e6d7233d/href">https://medium.com/media/dc880cf99603cf68d89439a2e6d7233d/href</a></iframe><p>Here we are exporting a class called CatsService and have defined three different methods. We also use @Injectable() which is a decorator. The decorator attaches metadata and marks a class available to be provided and injected as a dependency. Since we have injected this class as a dependency, let&#39;s use it inside of the controller to retrieve the cats.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e34736a6872eec18874b51ad281d1a98/href">https://medium.com/media/e34736a6872eec18874b51ad281d1a98/href</a></iframe><p>In the controller file, we are importing the CatsService and have instantiated the service inside of the constructor. The CatsService dependency is injected through the class constructor (Dependency Injection). This will expose all the various methods that we have defined inside the CatsService. We can now retrieve the cats using the controller.</p><blockquote><em>Dependencies are services or objects that a class needs to perform its function. Dependency injection, or DI, is a design pattern in which a class requests dependencies from external sources rather than creating them. — </em><a href="https://angular.io/guide/dependency-injection"><em>Angular</em></a></blockquote><p>Here the decorator <strong>@Get()</strong> takes an argument (the method being decorated, in this case, getCats and getOneCat) and returns the same function with added functionality (or a return value in this case, which is a string).</p><p>Also, the <strong>@Get()</strong> decorator accepts a pathname that we can make use of to request a particular route. For example, a request to <strong>/cats/allCats </strong>will invoke the method <strong>getCats</strong> and return all the cats.</p><h4>Making a request to the endpoint</h4><p>Let’s request to the endpoint <strong>getAllCats</strong> that we just defined and see what we get returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LmcnqhbiYBvi1FRbNQ9iqQ.png" /><figcaption>Fig: POSTMAN GET response</figcaption></figure><p>As we can tell the return result is received as expected. This is technically the pattern that we are going to see a lot with Nest. We have a service file that will implement all the methods/logic of our application while the controller file will take care of returning the results from the services using appropriate routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/866a21cf043f77c75ff1036206b1eb19/href">https://medium.com/media/866a21cf043f77c75ff1036206b1eb19/href</a></iframe><p>The module file above bundles all our controllers and providers/services together and exports a class that can be imported to instantiate our application. Every application has at least one root module. Nest uses this root module to create the application graph — the internal data structure Nest uses to resolve module and dependencies.</p><p>We can also create multiple feature modules that will help us organize the code relevant to a specific feature. All the feature modules can then be imported inside the root app model. For demonstration, we only have one root module above (the cats.module.ts file in this case).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/816f6a66de5be9f1ee29cb6d98997076/href">https://medium.com/media/816f6a66de5be9f1ee29cb6d98997076/href</a></iframe><p>The main file bootstraps a Nest application for us while creating the module (CatsModule) we just created. The main file is the entry point of our application. To create a Nest application instance, Nest uses the core NestFactory class. NestFactory exposes static methods that allow creating an application instance.</p><p>There we have it. We have a simplistic NestJS application that pretty much describes the best practices and patterns that NestJS follows and how it can help build scalable, maintainable, and testable code. I hope this introduction to NestJS was fairly simple and can help you understand the blocks and pieces that work together within NestJS.</p><h3>References</h3><ul><li>NestJS <a href="https://docs.nestjs.com/">Documentation</a>.</li><li>Node.js project <a href="https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf">architecture</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=406d9b192a3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/nest-js-architectural-pattern-controllers-providers-and-modules-406d9b192a3a">Nest.js — Architectural Pattern, Controllers, Providers, and Modules.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zustand — A simple, fast, and convenient state-management solution using Hooks API.]]></title>
            <link>https://medium.com/weekly-webtips/zustand-a-simple-fast-and-convenient-state-management-solution-using-hooks-api-c09c65963c68?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09c65963c68</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 07:02:11 GMT</pubDate>
            <atom:updated>2021-03-08T19:51:16.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Zustand — A simple, fast, and convenient state-management solution using Hooks API.</h3><figure><img alt="Zustand — A simple, fast, and convenient state-management solution using Hooks API." src="https://cdn-images-1.medium.com/max/1024/1*eMQd_WAaqgpzrbrv46F8Zg.png" /></figure><p><a href="https://github.com/pmndrs/zustand">Zustand</a> is a pretty neat state-management tool. When I say state-management, you might as well want it to be compared with Redux or Context. But, this blog wouldn’t be the typical rundown of pros and cons and comparing technologies as every technology has its own pros and cons. Instead, we are going to have a look at how Zustand makes it easy to get started with handling state on your applications.</p><p>By any chance, if you are looking for a top-hole definition of Zustand, here it is:</p><blockquote><em>It is a small, fast and scaleable barebones state-management solution. It has a pretty neat API based on hooks and isn’t boilerplatey at all to start with.</em></blockquote><h3>Get started</h3><p>To get started with Zustand you would need its npm package. You can download it from npm using:</p><pre>npm install zustand</pre><h4>Create a store</h4><p>Once we are done installing the package we can go ahead and create the store. Creating a store is as easy as it can get. We have a really basic example of how we can create a store and then access the store within components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d09d8aba93cd5968b8f2137cb8b186a/href">https://medium.com/media/6d09d8aba93cd5968b8f2137cb8b186a/href</a></iframe><p>‘create’ in Zustand provides us with two different methods ‘set’ and ‘get’. The naming is probably self-explanatory of its purpose. The ‘Set’ method is used to set/merge the state, while the ‘Get’ method helps us to access the state in the store.</p><h4>Bind within components</h4><p>Right after creating the store, we can access the hook anywhere in our component like so. Neat and easy! Note, there is no extra provider required to access the state. Just select the state you want access to and Zustand will take care of re-rendering the component when the state changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8596fec3b2e889b14adfd01a9df5e1bc/href">https://medium.com/media/8596fec3b2e889b14adfd01a9df5e1bc/href</a></iframe><p>Function ‘Counter’ grabs the value of count stored in the state and displays it within <em>p</em> tags, while ‘IncrementCounter’ performs mutation to the state by incrementing the state value.</p><p>Zustand simply makes life easier without needing to write too much code and its intuitive hooks API is sleek to be fair.</p><h3>Fetch everything or slices from multiple states</h3><p>While you can fetch the entire state entity all at once, it is not recommended since every state change will cause a re-render of the component. Fetching everything can be implemented as:</p><pre>const state = useStore();</pre><p>With Zustand we can also grab slices of multiple states without fetching everything right away. It is very helpful if you want to perform atomic state-picks.</p><pre>const <strong>nuts</strong> = <em>useStore</em>((state) =&gt; state.<strong>nuts</strong>);<br>const <strong>honey</strong> = <em>useStore</em>((state) =&gt; state.<strong>honey</strong>);</pre><p>Additionally, we can also define an object that performs multiple state-picks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95cb60dffddf3008de5c93e8a399a05e/href">https://medium.com/media/95cb60dffddf3008de5c93e8a399a05e/href</a></iframe><p>‘shallow’ allows us to trigger state update when keys of the object change or update. The above code will trigger a re-render when either of `state.nuts` or `state.honey` changes.</p><h3>Performing asynchronous actions</h3><p>Let’s not forget every time we build an application we somehow always need to reach out to an API for some data. And fortunately, Zustand has taken care of performing async actions for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eda45c1ddbf020a0ffee8edd176d2dc/href">https://medium.com/media/8eda45c1ddbf020a0ffee8edd176d2dc/href</a></iframe><p>I’m certainly mind-blown by how much work we can actually do with Zustand’s intuitive and clean API. I would highly recommend you to check out a few other features available with Zustand. For me, it was a kind experience for the fact that I didn’t need many configs to start with (literally zero-config upfront). It is pretty much convenient how simple the implementations are. If you want to try out a simple React application using Zustand, you can visit <a href="https://codesandbox.io/s/dazzling-moon-itop4">here</a> and get a taste of convenience for yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09c65963c68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/zustand-a-simple-fast-and-convenient-state-management-solution-using-hooks-api-c09c65963c68">Zustand — A simple, fast, and convenient state-management solution using Hooks API.</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Web Vitals Can Remediate Your Website’s Bad User Experience.]]></title>
            <link>https://medium.com/weekly-webtips/core-web-vitals-can-remediate-your-websites-bad-user-experience-9c712ecbfab4?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c712ecbfab4</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[seo]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[core-web-vitals]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 00:00:00 GMT</pubDate>
            <atom:updated>2021-06-09T09:42:48.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ufWBmpWmd81-Lrx.png" /></figure><p>We all want to create beautiful layouts, add exquisite animations, and want to deliver a top-notch user interface but let me be honest, how many of us are really aware of the web vitals that can help deliver a blazingly fast user experience. In short, Google uses these web vitals to provide quality standards on user experiences.</p><h3>What are Web Vitals?</h3><p>Web Vitals are essentially a way to quantify the user experience of one’s website, which if optimized can help deliver a great user experience. It is an initiative by Google and they have provided a few different tools to monitor the performance of websites. When one maintains a website it’s just not about delivering the website and putting forth the information for users to consume. But what we do need to take care of are the microscale details including “Does the user see what they want to see?” or “Did the same user visit your website for the second time?”.</p><p>Taking care of the modest details will surely take you a long way. In fact, it is a snowball effect. Small optimizations can lead the path to much larger optimizations going forward. Well even though there are a lot of things to consider while delivering a top-notch user experience, Core Web Vitals makes it relatively easy and simplifies the concept of user-centric design by helping us focus on metrics that matter the most.</p><h3>What are Core Web Vitals?</h3><p>Core Web Vitals primarily encompasses three specific measurements: Largest Contentful Paint (visibility), First Input Delay (interactivity), and Cumulative Layout Shift (stability).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgJpKkyK6Qs9o6qEpFGo9w.png" /><figcaption>Core Web Vitals — Image from <a href="https://web.dev/vitals/">Web.dev</a></figcaption></figure><p>Let us go through each of them and understand what they really mean.</p><ul><li><strong>Largest Contentful Paint (LCP):</strong> It measures how fast your website loads. Anything below 2.5s is deemed a good score.</li><li><strong>First Input Delay (FID):</strong> It measures how long a user has to wait before they can interact with your website. Anything below 100ms is a good FID score.</li><li><strong>Cumulative Layout Shift (CLS):</strong> It measures the visual stability of a website. It mainly occurs due when an asynchronous event fires and inserts DOM elements on the fly on top of existing content.</li></ul><h3>Tools to measure Core Web Vitals.</h3><p>There are a handful of developer tools that support Core Web Vitals. Below I have put up a picture just to display a few. You can make use of the tools to generate the Web Vitals score report and see how far you need to optimize your website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JzbfIYEp3jhW18J7.png" /><figcaption>Tools for measuring Web Vitals</figcaption></figure><p>There is a really descriptive workflow described in the <a href="https://web.dev/vitals-tools/">web.dev blog</a> that talks about how we can use all of the tools above to optimize the Core Web Vitals for a website. If you have some time and want to understand it better I would highly suggest you follow the link above. If not, let me write down the essence for you quickly.</p><ul><li>First of all, you can use Search Console’s Core Web Vitals that will generate a report to help you identify the number of pages that require optimizations. And, this is all generated based on field data. Field data is essentially Real User Metrics (RUM) data of real users over the course of a duration (usually a month).</li><li>Once you have the pages that require some digging, you can then use PageSpeed Insights (which I highly recommend) to generate lab and field data on the webpage.</li><li>If you are down to optimize your site locally, using tools like Lighthouse and Chrome DevTools can help you boil down every aspect of Core Web Vitals that requires optimization.</li></ul><p>A great resource would be to use <a href="https://web.dev/measure/">web.dev/measure</a> that can help prioritize a set of guides for optimization. Also, it is recommended that you use Lighthouse Continuous Integration (CI) on every pull request you make to make sure you have optimized the site before deploying the changes to production.</p><p>I would suggest you use <a href="https://developers.google.com/speed/pagespeed/insights/">PageSpeed Insights</a> to generate the Web Vitals score right away if you don’t know where to start.</p><h3>Get started with PageSpeed Insights</h3><p>To get started let us go ahead and see PageSpeed Insights’ typical report that records the core web vitals scores. PageSpeed Insights has an intuitive UI and the navigation is quite simple. Also, you will have an option to optimize for both Mobile and Desktop devices. Make sure you generate a report for both the device types as you will likely have different scores for different devices.</p><p>Once you have the URL of the site you want to generate the report for go ahead and click analyze. It might take a few seconds before you see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sLmPXpoY_vF42W3L.png" /><figcaption>Core Web Vital Scores based on Field Data</figcaption></figure><p>As you can see the result is based on the real-world field data and says if the page passes the Core Web Vitals assessment or not. The report records four different web vitals. They are First Contentful Paint (FCP), First Input Delay (FID), Largest Contentful Paint (LCP), and Cumulative Layout Shift (CLS). You can also view suggestions based on each page by analyzing individual page URLs. Suppose you want to generate a report for the About page of your portfolio, you can go ahead and check the About page (<a href="http://www.portfolio.com/about">www.portfolio.com/about</a>) and record its scores.</p><p>Additionally, you also receive a Lab score which essentially means that the scores are based on assumptions of user data. The lab score would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wqe6ae54DkzFjL-n.png" /><figcaption>Core Web Vital Scores based on Lab Data</figcaption></figure><p>Lab score comes along with a brief description of what these scores are and helps you visualize where you might need some digging. These scores are very helpful for testing your website and can help you to perform iterative optimizations along the way.</p><h3>What’s more? Suggestions and Improvements</h3><p>What if the web vitals score for your site isn’t too great the first time around. You don’t have to worry about not knowing where the problem in your site might be. In fact, PageSpeed Insights helps you with a diagnostic section that can perhaps act as a guide or a starting point. As you can see in the picture below, I have drawn out in red boxes to highlight places where PageSpeed Insights wants you to dig in and resolve some of these issues with your site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A-kSplXl13fJF0p5.png" /><figcaption>Core Web Vitals Diagnostics</figcaption></figure><p>These highlights are pretty helpful as you can now deal with solving the specific problem right away than just being baffled and not knowing where things are unsettled. Every diagnosis will also have a “Learn More” section that you can follow to learn how to tackle the specific problem.</p><p>Additionally, right at the bottom, you’d also have a “Passed Audits” section listing out where your site is doing great at.</p><h3>Improve Site Experience and Ranking</h3><p>You might have a question now that if we really need to care about the web vitals anyway? Let me clear up something. Web Vitals score is just one way or one of the ways Google ranks user sites essentially. Before you even get there and try to optimize your site for SEO, make sure your site has high-quality and relevant content. By relevance or high quality, I just mean a site that users would love to visit.</p><p>So in that case, you can’t expect a site to be ranked really high even with high-quality content because it somehow lacks in web vital assessment and vice versa. Definitely, it’s a mix of both that would make your site ranked higher.</p><p>There’s a quote from Google that says:</p><blockquote>A good page experience doesn’t override having great, relevant content. However, in cases where there are multiple pages that have similar content, page experience becomes much more important for visibility in Search.</blockquote><p>Very simply if there are multiple pages that have quality content the only deciding factor of one page being ranked higher than the other would be the Web Vitals score. So to sum up make sure you work on both quality and relevant content as well as the SEO optimizations for Google to rank your site.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c712ecbfab4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/core-web-vitals-can-remediate-your-websites-bad-user-experience-9c712ecbfab4">Core Web Vitals Can Remediate Your Website’s Bad User Experience.</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Styled Components in React]]></title>
            <link>https://medium.com/weekly-webtips/styled-components-in-react-a49bc113b0c0?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49bc113b0c0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[styled-components]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 11:44:34 GMT</pubDate>
            <atom:updated>2021-02-12T07:10:15.123Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Styled Components in React" src="https://cdn-images-1.medium.com/max/1024/1*rvlbziaqAONghHxpdXzPlg.png" /></figure><p>Not a very long time ago, CSS style sheets were the only appropriate way to paint any modern app. That is basically the traditional method of styling at the document level — creating a style.css file and referencing it on the HTML document for the styles to appear.</p><p>But with constant updates and improvements, we now have with us something known as styled-components. Styled components are basically an innovative way of using Javascript’s ES6 syntax, along with CSS which enables us to enhance our styling in React components. From very old and basic .css files to .scss files and styled-components, there have been some massive upgrades so to speak.</p><p>To put out in very simple terms, styled-components allow us to write CSS inside of JavaScript. That’s it! We can still use CSS/SCSS files that would still be compiled back into CSS modules.</p><p>Before we run through what styled-components can bring to the table let me clarify why do we even need them.</p><p>Well, imagine when an application grows and expands there are certainly a lot more things to consider being a developer. Worrying about dedicating a specific folder to encapsulate all the CSS related files, identifying how to scope them, and making very sure that there are no clashes in namespaces. These are a few of the many problems that styled-components are effectively intercepting right off the bat. Additionally, encapsulating CSS in JavaScript also means no more extensive HTTP requests to fetch all the CSS assets beforehand.</p><h3>Why Styled Components (Extended)?</h3><p>Styled components allow us to write CSS inside of JavaScript using tagged template literals (``) and it removes the overhead of mapping components and styles together.</p><p>Styled components were created to handle the following reasons:</p><ul><li>Styled components automatically monitor components that are rendered on a webpage and only injects the critically required styles. This means that there is no overhead of extra HTTP requests for fetching the CSS assets.</li><li>Styled components generate unique class names for the styles. Developers now don’t have to worry about namespace clashes.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7327d8497a5be1337b0b67486db353e4/href">https://medium.com/media/7327d8497a5be1337b0b67486db353e4/href</a></iframe><ul><li>Adapting the styling of a component based on its props or a global theme is simple and intuitive without having to manually manage dozens of classes.</li><li><strong>Automatic vendor prefixing:</strong> write your CSS to the current standard and let Styled components handle the rest. Styled components use the <a href="https://stylis.js.org/">stylis.js</a> package under the hood for prefixing the CSS rules.</li></ul><h3>Features of Styled-components</h3><h4>1. Passing Props:</h4><p>Props in styled-components act the same way as props passed into any React component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b76dff00c4a17e6deed4bc609ec241de/href">https://medium.com/media/b76dff00c4a17e6deed4bc609ec241de/href</a></iframe><h4>2. Dynamically Changing Elements:</h4><p>We can dynamically change elements using styled-components as demonstrated below. As you can see in the example below we convert a span element to act as link passing the &#39;as&#39; prop made available to us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3836149c80d7b5172bbc3a16dbdd2cb/href">https://medium.com/media/e3836149c80d7b5172bbc3a16dbdd2cb/href</a></iframe><p>Now, although CustomText is only a span, it will behave like a link.</p><h4>3. Leveraging Themes:</h4><p>Themes allow us to be consistent by making styles available to all our different components. We can now define a common style and apply it to any component we want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aae398139290243e499540a98ecf64d/href">https://medium.com/media/9aae398139290243e499540a98ecf64d/href</a></iframe><p>There are tons of handy features that styled-components come with. It also has a few advanced features like concurrent server-side-rendering and passing ref props, just to name a few. Please do check out their official docs by visiting <a href="https://styled-components.com/docs/">here</a> to know about all its features.</p><h3>References</h3><ul><li><a href="https://medium.com/@fionnachan/building-a-react-component-library-with-styled-components-input-field-c79c789387ad">Building a react component library using styled-components</a>.</li><li><a href="https://blog.cloudboost.io/getting-the-most-out-of-styled-components-7-must-know-features-acba3cc15b5">Getting most out of styled-components.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49bc113b0c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/styled-components-in-react-a49bc113b0c0">Styled Components in React</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write a Custom Reusable Hook (useFetch).]]></title>
            <link>https://medium.com/swlh/write-a-custom-reusable-hook-usefetch-1443d8d4e1e1?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1443d8d4e1e1</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 10:22:49 GMT</pubDate>
            <atom:updated>2021-06-05T13:43:58.469Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qH1Akkd_KOgpJb1dFdu_Jg.png" /></figure><p>Today we are going to write a reusable custom hook, and build a simple application that will make use of the hook. If you don’t already know hooks were a part of React from v16.8 onwards. They were essentially included as a feature to avoid using classes or class-based components. We can leverage state and other React features the same way we did while using React class-based components. Hooks are just a cleaner way to write programs in React.</p><p>What we will have by the end of the tutorial are two components mainly a User component and a Post component. Each of these components will pass an ID using fetch to make a request against the JSON Place holder API. If the user and the post with respective IDs exists, the data will be displayed. And, if they don&#39;t exist we&#39;ll display some kind of texts notifying that the data wasn&#39;t found.</p><p>Now one of the hunches that we will encounter while writing the component is that we’ll probably end up writing very similar code. So to avoid writing any repetitive code we write a custom hook component that our User and Post component concurrently leverages for requesting and retrieving data.</p><h3>Basic Setup</h3><p>The only setup you will need for this application is having a react app. Run the following command to get started:</p><pre>npx create-react-app .</pre><p><strong><em>Note: Make sure you have npm version &gt; 5.2, to be able to run npx.</em></strong></p><p>If not update your npm using:</p><pre>npm install -g npm@latest</pre><p>After you update the npm to the latest stable version, you can now use the npx command to create the react app.</p><h3>Folder Structure</h3><p>Everything that we will work on will reside inside the src directory, so we don&#39;t need to worry about anything else.</p><p>The basic folder structure after creating the react app will look something like this:</p><pre>src / App.js<br>---- App.css<br>---- index.js<br>---- index.css</pre><p>You might have more files than this. In case you do, go ahead and delete those files as we will no longer need them for this application.</p><p><strong><em>Note: I have only highlighted the src folder since we will only be working inside this directory.</em></strong></p><p>Now that we have the basic structure ready, we can keep going.</p><h3>Creating a components directory</h3><p>Create a /components directory inside of /src, that will hold all of our components.</p><p>Now inside the components directory, go ahead and create three different directories. The first one being card that will be the container holding the user and post data. The second directory will be the user directory that contains our user component while the third is the post directory that will contain the post component.</p><p>Inside card, user and post directories create the files card.component.jsx, user.component.jsx and post.component.jsx respectively.</p><p><strong><em>Note: The card directory will have a card.css file for styling the card container.</em></strong></p><p>The folder structure will look something like this after creating all the files:</p><pre>- src/<br>--- components/<br>----- card/<br>------- card.component.jsx<br>------- card.css<br>----- user/<br>------- user.component.jsx<br>----- post/<br>------- post.component.jsx</pre><h3>Card Component</h3><p>The card component essentially holds the User and the Post data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5acc0ff4c221c93de86643dafb1adb85/href">https://medium.com/media/5acc0ff4c221c93de86643dafb1adb85/href</a></iframe><p>Styling the card component to make it look decent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06c7d5184471f49d42b4180406d6e9fd/href">https://medium.com/media/06c7d5184471f49d42b4180406d6e9fd/href</a></iframe><h3>User Component</h3><p>The User component displays the user data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bef8633423bd1649e98d8c4c5e4a8e2b/href">https://medium.com/media/bef8633423bd1649e98d8c4c5e4a8e2b/href</a></iframe><p>We notice there is an import useFetch that we haven&#39;t written yet. Don&#39;t be surprised, but that will be the custom hook we will be writing a little later.</p><h3>Post Component</h3><p>The Post component will display the post data as expected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d77fcf2d2ee31793779366c4e7544fa/href">https://medium.com/media/7d77fcf2d2ee31793779366c4e7544fa/href</a></iframe><p>We import useFetch here as well. Let us now go ahead and create a separate component for the hook.</p><h3>useFetch Hook</h3><p>Inside components directory create another directory called effects and inside effects create a file named use-fetch.effect.js. The same file will hold all the logic of actually making a fetch request to the API and returning the response back to the components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a2082c7d5e054a240b306560e132b2/href">https://medium.com/media/c5a2082c7d5e054a240b306560e132b2/href</a></iframe><p>The useFetch custom hook accepts a ‘URL’ parameter, does the fetching, and returns the data to the components that requested the data. That is all the useFetch custom hook does pretty much. Instead of us fetching data from each of these components we now leverage useFetch as a reusable component. And next time we have another component that requires the same component logic, we already have useFetch that can do the trick for us.</p><h3>App.js</h3><p>Now for us to display the data on our browser we need to hook our components inside of App.js and pass the id as props that the components receive.</p><p>And after all that is done, we can now see something like this on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Pc9AyH6k1gH1YqXw.png" /></figure><p>There you go, we have our custom hook up and running. Understandably a custom hook is very much a necessity when we write components that use the same component logic. This process bares us from writing any repetitive code and instead write a reusable custom hook component that can be leveraged by various components at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1443d8d4e1e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/write-a-custom-reusable-hook-usefetch-1443d8d4e1e1">Write a Custom Reusable Hook (useFetch).</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two-Factor Authentication (2FA) Using Speakeasy and Express.]]></title>
            <link>https://medium.com/swlh/two-factor-authentication-2fa-using-speakeasy-and-express-fe6108b977af?source=rss-4a966f7715b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe6108b977af</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[two-factor-authentication]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[speakeasy]]></category>
            <dc:creator><![CDATA[Boro]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 07:56:05 GMT</pubDate>
            <atom:updated>2021-01-21T11:28:36.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoKqVKrCoZP_ScdJ-2UoWg.png" /></figure><p>Multi-factor authentication is an authentication method in which a user is granted access to a website or application only after successfully presenting two or more pieces of evidence to an authentication mechanism: knowledge, possession, and inherence.</p><p>In the same way, the two-factor authentication method requires you to enter additional data as evidence to access your account. The most common forms of two-factor authentication involve entering a code as used by Google and Facebook for additional security.</p><h3>Advantages of Two Factor Authentication</h3><ul><li>Added layer security and added protection against cyber attacks.</li><li>Do not incur any extra costs while setting up.</li><li>Easy and convenient setup. For most implementations, all a user has to do is enable two-factor authentication and scan a QR code or enter their cellphone number so they can view or receive authentication codes respectively</li></ul><p><strong><em>NOTE: </em></strong>In this tutorial, we will deal with a backend that implements the time-based one-time password (OTP) made available to us by the Speakeasy library. This tutorial only covers the backend implementation of the two-factor authentication.</p><h3>Setup</h3><p>The very first step is to make sure you have appropriate versions of Node and npm installed. If not already you can follow the below links to download the absolute essentials as the very first thing we will be doing is run a Node server.</p><ul><li><a href="https://nodejs.org/en/download/">Node</a></li><li><a href="https://www.npmjs.com/get-npm">NPM</a></li></ul><p>The next thing we do is create a project directory:</p><pre>$ mkdir 2-fa<br>$ cd 2-fa</pre><p>Now that we have our project folder, we will spin up a package.json using npm init:</p><pre>$ npm init -y</pre><p>After you go through a couple of ‘yes’ and customize the setup, you will have a package.json file that might look something like this:</p><pre>{</pre><pre>   &quot;name&quot;: &quot;2-fa&quot;,<br>   &quot;version&quot;: &quot;1.0.0&quot;,<br>   &quot;description&quot;: &quot;Two factor Authentication using Speakeasy&quot;,<br>   &quot;main&quot;: &quot;app.js&quot;,<br>   &quot;scripts&quot;: {<br>      &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>   },<br>   &quot;keywords&quot;: [],<br>   &quot;author&quot;: &quot;Sintu Boro&quot;,<br>   &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p>Run the following command to install the necessary dependencies:</p><pre>$ yarn add express body-parser node-json-db uuid speakeasy ||<br>$ npm install express body-parser node-json-db uuid speakeasy</pre><ul><li>Express is a Node.js web application framework that we’ll use to spin our server.</li><li>The middleware body-parser package allows us to parse encoded data from incoming HTTP requests and expose them as req.body, so we can extract the essential data.</li><li>Node-json-db will be used as a database instance for storage.</li><li>Speakeasy is a one-time passcode generator, that we require for the two-factor authentication demonstration.</li></ul><p>We now have all the necessary dependencies and are ready to create our server. In the project folder, create an index.js file that will act as an entry point to our project and add the following code to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zQkXkrx5rl0fspCTjK-MVw.png" /></figure><p>At the root of your project, run the app to make sure everything is working alright:</p><pre>$ node index.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*QC4vxePrgZFDkoxLU5ms2g.png" /></figure><p>And now if we hit the route /api, we receive the following as a JSON response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrP8NehUv0PQAlOBGcsOUA.png" /></figure><h4>Generate Secret Key</h4><p>We now need to generate a secret key that in turn generates us the two-factor authentication code through the Authenticator extension that we will be using. We will also have a route to register a user containing just the userID and the secret key generated by speakeasy.</p><p>To do this we will use Speakeasy’s generateSecret function. The response returns an object that has the secret in ASCII, hex, base32, and otpauth_url formats. We will only be using the base32 string to set up two-factor authentication. Paste the following code to create the register user route:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zha0S_HFe5RZP4Jp4in03Q.png" /></figure><p>Right after we add the routes we can now make a POST request to this route to register a user like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0dkj1DLc2DpMG3tUzfpMw.png" /></figure><p>Now open the Google Authenticator extension/app(this can be installed as an extension) and enter the secret key you just received like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*T3SR51IpSwH61gBtXG2ShA.png" /></figure><h4>Verify the secret</h4><p>We now have the code generated to us through the secret key by the authenticator app. We now need to verify this code. Notice we have stored the secret as a temporary secret on the storage/database. Only after relevant validation, we can go ahead and store it permanently.</p><p>To perform the validation, we need to create another endpoint. The endpoint that verifies the code for us looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMi_Vrb1KKdc9PR3DvFoDw.png" /></figure><p>Now open up the two-factor authentication extension and retrieve the code so we can verify the secret using a Postman request to the verify route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bYuwClHO-rfssUeem6qIg.png" /></figure><p>After the validation, the secret key is now stored permanently and is used to verify future codes.</p><h4>Verify User Tokens</h4><p>The final step in the two-factor authentication is verifying the code that the user enters from their authenticator app. We need to add another route that will confirm that the tokens entered by the user are valid. The verification is handled by the Speakeasy TOTP(Time Based One Time Password) verify function.</p><p>This receives an object that contains the secret, the encoding to use to verify the token, the token, and a window option. A window refers to the period of time that a token is valid. This is usually 30 seconds but can vary depending on the time selected by the developer of the two-factor process.</p><p>You want to be careful to now pass out a large window allowance as that would lead to the verification process becoming less secure. Copy the code below to add the endpoint to validate the tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CErHDRQVeNidVjUZQPxJdA.png" /></figure><p>Now hit the /validate route and verify the code from the authenticator using Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e53E9MjmJR_pMCKAgCCLwA.png" /></figure><p>And there you go! We have successfully implemented a two-factor authentication using Speakeasy. We looked into how we can register a user and create a secret shared between your server and the authenticator app; verifying the secret and using it to validate tokens.</p><p>The entire index.js file would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KgImRonveP06j2MPtl9sxg.png" /><figcaption>index.js</figcaption></figure><h3>References</h3><ul><li>Two-Factor Authentication using SpeakEasy — <a href="https://blog.logrocket.com/implementing-two-factor-authentication-using-speakeasy/">Logrocket.</a></li><li>For a video explanation of the tutorial please visit <a href="https://www.youtube.com/watch?v=KQya9i6czhM&amp;t=167s">Traversy Media — Two Factor Authentication</a> on Youtube.</li></ul><p><em>Originally published at </em><a href="https://boro-blogs.netlify.app/development/2fa-speakeasy/"><em>https://boro-blogs.netlify.app</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe6108b977af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/two-factor-authentication-2fa-using-speakeasy-and-express-fe6108b977af">Two-Factor Authentication (2FA) Using Speakeasy and Express.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>