<?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 Rafiur Rahman Protik on Medium]]></title>
        <description><![CDATA[Stories by Rafiur Rahman Protik on Medium]]></description>
        <link>https://medium.com/@rafiurrahmanprotik?source=rss-7abc0899f0fa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y4yJV_IE32T5yCTykhGkSg.jpeg</url>
            <title>Stories by Rafiur Rahman Protik on Medium</title>
            <link>https://medium.com/@rafiurrahmanprotik?source=rss-7abc0899f0fa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:13:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafiurrahmanprotik/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 Networking: From Packet to VPC]]></title>
            <link>https://towardsdev.com/aws-networking-from-packet-to-vpc-6319aa509430?source=rss-7abc0899f0fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6319aa509430</guid>
            <category><![CDATA[vpc]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-networking]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[subnet]]></category>
            <dc:creator><![CDATA[Rafiur Rahman Protik]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 14:40:58 GMT</pubDate>
            <atom:updated>2026-08-14T11:22:55.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVU9UwOMIPgz4Weepo-x-A.png" /><figcaption>A scalable server with multiple subnets in AWS infra</figcaption></figure><p>When I first started working with AWS, I could launch an EC2 instance inside a VPC, attach a security group, and deploy an application. But I realized that knowing how to configure these resources is very different than knowing how they actually communicate.</p><p>What happens when a user enters <a href="http://www.google.com/">www.example.com</a> in their browser?</p><p>How does the request find the AWS VPC?</p><p>Why can a private EC2 instance access the internet without being directly accessible from the internet?</p><p>And where do things like IP addresses, CIDR, route tables, Internet Gateways, NAT Gateways, and Security Groups fit into all of this?</p><p>This article is my attempt to build that understanding from the ground up.</p><p><strong>Let’s start with what actually happens when you type</strong> <a href="http://www.example.com/"><strong>www.example.com</strong></a></p><p>When you press Enter, providing a URL, the browser creates data like</p><pre>GET /<br>Host: google.com</pre><p>But this doesn’t travel as plain text. The OS wraps it into a packet, something like this:</p><pre><br>Destination: 142.250.xxx.xxx          <br>Source: 192.168.0.105<br>Payload: HTTP Request</pre><p>Notice three things: Destination IP, Source IP, Payload (Actual data). Your laptop asks: Can I send this directly to Google? And it compares it with its local network. Then it realizes Google is not in my local network, and it asks someone else to deliver this. That is the<strong> Default Gateway. <br></strong>A host (computer) typically has a <strong>Default Gateway</strong>. Imagine in your home: these are local devices such as a laptop, phone, TV, etc. And your wi-fi router acts as a <strong>Default Gateway. </strong>Your router takes the packet, and it sends it to your <strong>ISP; </strong>then the <strong>ISP </strong>sends the packet to the outer internet (more routers). Now the packet travels in this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXuF9_B6zr869Xy2gbv7Wg.png" /><figcaption>Packet flow from laptop to Google</figcaption></figure><p>When Google receives the <strong>GET / </strong>it generates the homepage and sends another packet, but now:</p><pre>Destination: Your Laptop         <br>Source: Google</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SfikDNKq56I4-NMX6dAvw.png" /><figcaption>Packet flow from Google to laptop</figcaption></figure><p>So far, we built the minimum foundation of packet flow through the internet. Now, let&#39;s uncover some network components.</p><h4>IP Address</h4><p>We know the internet is a global network of billions of computers, devices, and servers. In this whole network, to uniquely identify a computer or device, we need some sort of address. And that is what we call an IP address. In this whole network, every device must have an IP address so it can communicate with other computers or devices.</p><p>Imagine every device on earth had an IP address, such as your laptop, your phone, your TV, smart watch, camera, Alexa, etc. If we multiply that by billions of people, then it will be an enormous number. But there is a problem with IPv4 because the total number of IP addresses is <strong>4.3 billion. </strong>It sounds huge, but the world has 8+ billion people, multiple devices per person, servers, etc. So, we would run out, and in fact we did. To slow down IPv4 address exhaustion, techniques such as private IP addressing and NAT allow many devices to share a smaller number of public IPv4 addresses.</p><h4>Public IP &amp; Private IP</h4><p>An IP address that is globally reachable from the internet. Example:</p><pre>AWS EC2 (Public IP)<br><em>has</em><br>54.179.12.45<br><br>or<br><br>google.com<br><em>has</em><br>142.250.xxx.xxx</pre><p>Anyone on earth can send packets to these IP addresses. These are public.<br>Now, look at your laptop/phone. Probably it has: <strong>192.168.0.106, </strong>which is <strong>a Private IP</strong>. I want to ask you a question. Can someone from the USA directly send packets to <strong>192.168.0.106? </strong>The answer is<strong> “No”. </strong>Because Private IPs only exist inside a local network. They’re not routable on the public internet.<br><strong>N. B: Reserved private ranges are 10.0.0.0/8, 172.16.0.0–172.31.255.255, 192.168.0.0/16</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hD40K_EOUEW4a8XWFW9qtQ.png" /><figcaption>Your home network</figcaption></figure><p>The above picture is your home network. Notice something that your home has only one public IP but many private IP addresses. How is that possible? Enter NAT.</p><h4>NAT (Network Address Translation)</h4><p>The router performs NAT. Imagine your laptop wants to visit Google. Your laptop (192.168.0.105) sends a packet with:</p><pre>Source: 192.168.0.105<br>Destination: 142.250.xxx.xxx</pre><p>Google receives it, but Google cannot reply to <strong>192.168.0.105 </strong>because that address does not exist on the internet; rather, it exists in the local network. So the router changes it before sending the packet to Google.<br><strong>Before sending the packet:</strong></p><pre>Source: 192.168.0.105</pre><p><strong>After NAT:</strong></p><pre>Source: 203.76.120.15</pre><p>Now, Google sees <strong>203.76.120.15, </strong>and Google replies there. The router that performs <strong>NAT</strong> remembers “That response belongs to the laptop”. Then it forwards it back. So, with <strong>NAT</strong>, we don’t really need every device to have a public IP.</p><h4>Subnet</h4><p>To introduce the <strong>Subnet, </strong>let’s imagine a scenario. Your laptop has <strong>192.168.1.10, </strong>your mobile<strong> 192.168.1.50</strong>, and your father’s mobile has <strong>192.168.2.20<br>Question:</strong> How does your laptop know whether it should send packets directly to another device or send them to the router?</p><p>Here comes the <strong>subnet. </strong>A subnet is simply<strong> a</strong> group of IP addresses that belong to the same local network.<br>So how does the laptop decide?<br>Imagine your <strong>laptop (192.168.1.10)</strong> wants to communicate with your <strong>phone (192.168.1.50).</strong> Now the laptop compares with <strong>192.168.1, </strong>and it gets the same network, and then sends directly.<br><strong>Now another question</strong>: How does the laptop know what portion (we did 192.168.1) should be compared with? <br>That’s where <strong>CIDR</strong> comes in.</p><h4>CIDR</h4><p>Suppose I write:</p><pre>192.168.1.0/24</pre><p>It’s actually very simple. Every portion before the dot (.) is an octet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*a3LR0wjFgzKrTm8FFMl6Zw.png" /><figcaption>IP octets</figcaption></figure><p>Here, <strong>192.168.1 </strong>is the network.<strong> </strong>The <strong>/24 </strong>means the first 24 bits (we know 1 octet = 8 bits) are the <strong>network</strong> part. And the fourth octet is the <strong>host</strong> part. That means this part identifies individual devices.<br>So why “<strong>/24&quot;</strong>?<br>Because it means the last octet part will be changed. Example:</p><pre>192.168.1.1<br>192.168.1.2<br>192.168.1.30</pre><p>So, if we put “<strong>/16</strong>” instead of <strong>“/24”,</strong> that means it can hold large sige than <strong>“/24”.</strong></p><p>One of the fundamental things we do when we want to host something on AWS is to create a <strong>VPC</strong>. As we will host something on AWS, we need to know what a <strong>VPC</strong> is.</p><h4>VPC (Virtual Private Cloud)</h4><p>Think of a <strong>VPC</strong> as buying a large secured piece of land. When you launch a <strong>VPC</strong>, you establish an isolated private network inside AWS. No one can enter or see it unless you explicitly build a gate or give permission to them. There are four core parts of a <strong>VPC. <br></strong>i) CIDR<br>ii) Subnet<br>iii) Internet Gateway (will be covered moving forward)<br>iv) Route Table (will be covered moving forward)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Vn9-x5KO65r07pg5eDDSw.png" /><figcaption>VPC with multiple subnets</figcaption></figure><p>A VPC can have multiple subnets depending on the product requirements. Let’s see another VPC with an EC2 component. We’ve not covered EC2 yet. For now, consider this your laptop inside an AWS environment.</p><pre>VPC (10.0.0.0/16)<br>└── Subnet (10.0.1.0/24)<br>      EC2<br>      10.0.1.10</pre><p><strong>Question: </strong>Can this EC2 access Google? <br>The answer will be no! Why? Let’s compare it with your home network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1FitZfSWXcxb7AbdU_GUA.png" /><figcaption>Home network</figcaption></figure><p>In your home setup, your laptop does not magically send the packet to the internet; rather, it uses a router. Now think in AWS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYQOdpb7Z4KLvg7N9vV-LQ.png" /><figcaption>EC2 to internet</figcaption></figure><p>What’s acting as the router? That is the <strong>Internet Gateway.</strong></p><h4>Internet Gateway (IGW)</h4><p>It’s kind of a door for your VPC in the AWS environment. Without an <strong>IGW, </strong>there is no connection between your VPC and the internet. Having a public IP address in the VPC does not make it accessible from the internet. You’ve to create an Internet Gateway manually so that your EC2 can communicate with the outside internet.</p><p>But still there is a problem. If the above setup is what we need, then why do we even talk about “public subnet” and “private subnet”? Because we still have a missing component. That is the<strong> Route Table.</strong></p><h4>Route Table</h4><p>A Route Table is simply a list of directions. Example:</p><pre>Destination          Target<br><br>10.0.0.0/16          Local<br>0.0.0.0/0            Internet Gateway</pre><p>If we look into the above Route Table, we see there are two routes.<br><strong>1) 10.0.0.0/16 </strong>means that if the destination is inside this VPC, then stay inside. <strong>Example</strong>:</p><pre>EC2<br>↓<br>PostgreSQL<br>10.0.3.15</pre><p>Means traffic never leaves AWS’s private network.<br>2<strong>) 0.0.0.0/0 </strong>means that if you don’t know where to send the packet, send to the Internet Gateway. For instance, your EC2 wants to visit Google, then DNS returns something like this: <strong>142.xxx.xxx.xxx, </strong>and then EC2 checks the route table: Is 142.xxx.xxx.xxx<strong> </strong>inside the<strong> </strong>10.0.0.0/16? It immediately gets “No”. So, it matches with 0.0.0.0/0. Therefore, it is sent to the Internet Gateway. Now the flow becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g_gx0EWV4-sMW1Huzv7F1Q.png" /></figure><p>Now, there is a catch here. Suppose a subnet uses:</p><pre>Destination<br>0.0.0.0/0<br>↓<br>Internet Gateway</pre><p>AWS calls it a <strong>Public Subnet</strong>. Suppose another subnet uses only the route below. No Internet Gateway.</p><pre>10.0.0.0/16<br>↓<br>Local</pre><p>AWS calls it a <strong>Private Subnet.</strong></p><h4>Public Subnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4XvHzJBXF_FJPQX40DrlA.png" /><figcaption>Public Subnet</figcaption></figure><h4>Private Subnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9LW9sdwsKOTFRGQ4BwJ_Q.png" /><figcaption>Private Subnet</figcaption></figure><p>So, the private EC2 has no route to the Internet.</p><p>Now comes the interesting part. Suppose you have this:</p><pre>Private Subnet<br>↓<br>API Server (Assuming a Node.js server)</pre><p>Sometimes, you SSH into it (through a Bastion), and then you run:</p><pre>sudo apt update<br>OR<br>docker pull redis</pre><p>What is this actually? Didn’t we just say: <strong>“Private subnets have no route to the internet”?</strong> So, how can they download packages and pull Docker images if they truly have “no internet”? <br>That question leads to the component “<strong>NAT Gateway</strong>”.</p><h4>NAT Gateway</h4><p>There are two types of communication. Outbound and Inbound. Both are vice versa.</p><p><strong>Outbound: </strong>Server starts the conversation.</p><pre>API Server<br>↓<br>Google</pre><p><strong>Inbound: </strong>Someone else starts the conversation.</p><pre>Internet<br>↓<br>API Server</pre><p>Earlier, we established that <strong>“Private subnets have no route to the internet”. </strong>But we want to achieve this. How? With a <strong>NAT Gateway.<br></strong>Remember your home router. Your laptop has a private IP. Yet it accesses Google. But Google cannot directly access your laptop. Why? Because of NAT.<br>AWS gives a managed service called: NAT Gateway. Think of this as your home router.<br>Now, the flow becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3FOrHSJLXliuQsR-RPUPA.png" /><figcaption>From Private Subnet to Internet</figcaption></figure><p>Here you can see the EC2 in the private subnet never talks directly to the internet. Everything goes through the NAT Gateway.<br>Suppose your API server hosted in EC2 wants to call the Stripe API. When leaving the from Private Subnet source is <strong>10.0.2.15</strong>, then the NAT Gateway changes it to something like <strong>54.xxx.xxx.xxx</strong> (public IP), and Stripe receives it and replies accordingly. NAT Gateway remembers that, and responses belong to <strong>10.0.2.15. </strong>Exactly like your home router<strong>.</strong></p><p>Sending and getting packets is not the last thing. AWS tells you to add a security layer to the EC2 instance. AWS asks Should I let this packet into the EC2? That’s the job of the <strong>Security Group.</strong></p><h4>Security Group</h4><p>It’s simply a virtual firewall attached to AWS resources. Usually attached to: EC2, ALB (Load Balancer), RDS, etc. It is attached to the resources, not to the subnet.<br>Now let’s draw an SSH flow from your laptop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDj6lyTZNsY6u65QnxtnWQ.png" /><figcaption>SSH to EC2</figcaption></figure><p>Even if the packet reaches the EC2. The Security Group can still deny the request. Example: Suppose your EC2 runs a Node.js API server on port 3000. If your Security Group is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*7G0OMGutU3NuKZaIlhkEJA.png" /><figcaption>Security Group configuration</figcaption></figure><p>And someone tries to hit: <a href="http://ec2-public-ip:3000/"><strong>http://ec2-public-ip:3000</strong></a>,<strong> </strong>then AWS checks the Security Group. Port: 3000? Denied!</p><p>Now the last component we want to touch is <strong>EC2</strong>.</p><h4>EC2 (Elastic Cloud Compute)</h4><p>It’s basically an AWS service that lets you rent virtual computers in the AWS cloud. Instead of buying a physical server, placing it in a data center, and plugging in cables, you use EC2 to launch a virtual server in seconds with just a few clicks. There are core components of EC2, but those topics are beyond this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6319aa509430" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/aws-networking-from-packet-to-vpc-6319aa509430">AWS Networking: From Packet to VPC</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Full-Stack App on AWS EC2 with Nginx Load Balancer (Frontend & Backend on Separate…]]></title>
            <link>https://towardsdev.com/deploying-a-full-stack-app-on-aws-ec2-with-nginx-load-balancer-frontend-backend-on-separate-afaf910bb106?source=rss-7abc0899f0fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/afaf910bb106</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[ngnix]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Rafiur Rahman Protik]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 16:16:28 GMT</pubDate>
            <atom:updated>2026-02-16T12:11:44.465Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Full-Stack App on AWS EC2 with Nginx Load Balancer (Frontend &amp; Backend on Separate Instances)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90ihhGndihBoLgBUgRbwRw.png" /><figcaption>Load Balacning in EC2 Instances</figcaption></figure><p>Recently, I deployed a simple full-stack Todo application on AWS using EC2 instances, Docker, GitHub Actions for CI/CD, and Nginx as a load balancer. The goal wasn’t just to “make it work”, but to understand how different pieces fit together.</p><p>In this article, I’ll walk through how I deployed the <strong>frontend and backend on separate EC2 instances</strong>, used <strong>Nginx to load-balance multiple backend servers</strong>, and automated deployments with <strong>Docker and GitHub Actions</strong>.</p><p>Before diving into the setup, it helps to step back and look at the overall architecture and how the different pieces communicate with each other.</p><p>At a high level, this is how everything is structured:</p><ol><li><strong>Frontend EC2 instance<br></strong>The frontend (ReactJS) runs as a Dockerized application on its own EC2 instance.</li><li><strong>Two backend EC2 instances<br></strong>The backend API (Node.js) runs on two separate EC2 instances. This allows incoming requests to be distributed across servers</li><li><strong>PostgreSQL running in Docker<br></strong>The database runs inside a Docker container using a persistent volume.</li><li><strong>Nginx EC2 instance (Load Balancer)<br></strong>Nginx sits in front of the backend servers and acts as a reverse proxy and load balancer.</li><li><strong>GitHub Actions &amp; Docker Hub<br></strong>GitHub Actions handles CI/CD by building Docker images and pushing them to Docker Hub</li><li><strong>EC2 pulling and running images<br></strong>Each EC2 instance pulls the latest Docker image from Docker Hub and runs the container</li></ol><p>These are the components I had to introduce to make the deployment workable without tightly coupling everything together.</p><p>So far, I’ve discussed <strong>what the system is. </strong>Now, let’s see<strong> how I build it step by step.</strong></p><p>Before deploying anything to EC2, I needed a consistent way to run the applications across different environments. Docker solved this problem by packaging the frontend and backend along with their dependencies into portable images.</p><p>I’ll share how to Dockerize both frontend and backend applications on localhost first.</p><p><strong>Dockerizing Backend</strong></p><p>To dockerize the backend, we need multiple services together, such as PostgreSQL and Node.js. So, we’ll be using both <strong>Dockerfile </strong>and <strong>docker-compose.yml.</strong></p><p><strong>Dockerfile config:</strong></p><pre>FROM node:20<br><br>WORKDIR /usr/src/app<br><br># Install PostgreSQL client<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y gnupg2 software-properties-common postgresql-client &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br><br># Copy package files and install dependencies<br>COPY package*.json ./<br>RUN npm install<br><br># Copy the app code<br>COPY . .<br><br># Set port and startup script<br>EXPOSE 5000<br>COPY startup.sh .<br>RUN chmod +x startup.sh<br>CMD [&quot;./startup.sh&quot;]</pre><p><strong>docker-compose.yml config</strong></p><pre>version: &quot;3.8&quot;<br><br>services:<br>  app:<br>    image: &lt;dockerhub-username&gt;/todo-back-dockerize-ec2:latest<br>    container_name: todo-back-dockerize-ec2<br>    ports:<br>      - &quot;5000:5000&quot;<br>    environment:<br>      DATABASE_URL: ${DATABASE_URL}<br>      NODE_ENV: ${NODE_ENV}<br>      PORT: ${PORT}<br>    depends_on:<br>      db:<br>        condition: service_healthy<br>    restart: always<br>    networks:<br>      - app-network<br><br>  db:<br>    image: postgres:15<br>    container_name: postgres-dockerize<br>    environment:<br>      POSTGRES_USER: ${POSTGRES_USER}<br>      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}<br>      POSTGRES_DB: ${POSTGRES_DB}<br>    ports:<br>      - &quot;5433:5432&quot;<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U ${POSTGRES_USER}&quot;]<br>      interval: 5s<br>      timeout: 5s<br>      retries: 5<br>    restart: always<br>    networks:<br>      - app-network<br><br>volumes:<br>  postgres_data:<br><br>networks:<br>  app-neAtwork:<br>    driver: bridge</pre><p>As this writing is about showing how to deploy applications in server, we are not gonna explain the Docker file and setup in detail. If you are confused, you could ask any LLM or learn by yourself about Docker config.</p><p>We need two more things. One is <strong>startup.sh</strong> and a <strong>.env </strong>file because docker-compose.yml is getting the credentials from the <strong>.env file.</strong></p><p><strong>startup.sh config</strong></p><pre>#!/bin/bash<br><br># Wait for database to be ready<br>until pg_isready -h db -U postgres<br>do<br>  echo &quot;Waiting for database...&quot;<br>  sleep 2<br>done<br><br>echo &quot;Database is ready!&quot;<br><br># Run Prisma client generation (safe here)<br>npx prisma generate<br><br># Run migrations<br>npx prisma migrate deploy<br><br># Start the application<br>npm run start<br></pre><p><strong>Dockerizing Frontend</strong></p><p><strong>Dockerfile config:</strong></p><pre>FROM node:18-alpine<br><br>WORKDIR /usr/src/app<br><br># Copy package files first for better caching<br>COPY package.json yarn.lock ./<br><br># Install dependencies<br>RUN yarn install --frozen-lockfile<br><br># Copy the rest of the files<br>COPY . .<br><br># Expose the Vite dev server port<br>EXPOSE 5173<br><br># Make entrypoint executable<br>RUN chmod +x ./entrypoint.sh<br><br>ENTRYPOINT [&quot;sh&quot;, &quot;./entrypoint.sh&quot;]</pre><p><strong>docker-compose.yml config</strong></p><pre>version: &quot;3.8&quot;<br><br>services:<br>  frontend:<br>    image: &lt;dockerhub-username&gt;/todo-front-dockerize-ec2:latest<br>    container_name: todo-frontend<br>    ports:<br>      - &quot;5173:5173&quot;<br>    environment:<br>      VITE_BASE_URL: ${VITE_BASE_URL}<br>    restart: always</pre><p>entrypoint.sh config</p><pre>#!/bin/bash<br><br>yarn dev --host</pre><p>So far, we’ve managed to Dockerize an Express application locally, and we can run it on any Docker-enabled computer.</p><p>Now, we can publish the Docker image to the Dockerhub. For that, we need to have an account on Docker Hub and make a repository. Let’s create a repository first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*geHasgJ6JokjK5CD1kBdyg.png" /><figcaption>Creating Repository in Dockerhub</figcaption></figure><p>When creating the repository, set its privacy to <strong>public</strong>. Because you would be able to create a <strong>private </strong>repository at most one. Now, we need to create an access token to link with the GitHub repository, so the Docker Hub can pull the built image from GitHub through <strong>GitHub Actions</strong>.<br>To create the access token, visit <strong>Account Settings &gt; Personal access token. </strong>Then, try to create the token from this interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-c6QAn8mbCTBvTmSb6Xvlw.png" /><figcaption>Generating access token in Docker hub</figcaption></figure><p><strong>Note</strong>: You must keep the permission <strong>‘Read, Write, Delete’. </strong>After generating the access token, you need to keep it somewhere so that you can use it in the GitHub Actions setup; otherwise, you might lose it. Now, let’s get back to the GitHub repository and connect with Docker Hub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8u7pZK0PEGmLNlyjIF_Q7Q.png" /><figcaption>Setup token in GitHub repos</figcaption></figure><p>After navigating to the Settings, you have to put the Docker Hub <strong>access token</strong> and <strong>username</strong>.</p><p>Now, we have to create a workflow, so whenever the developer pushes new changes, the image will be built on GitHub Linux VM through this pipeline and then pushed to the Docker Hub Repository. Later on, we’ll create another workflow for an EC2 instance. And in that workflow, the EC2 instance will pull that image from the Docker Hub and will use that built version image as a container in the AWS EC2 instance.</p><p><strong>Workflow Instance<br></strong>To create the workflow, we can simply create it from the<strong> actions </strong>tab by choosing from the given options. But we’ll create it manually because we’ll have to update the workflow statement based on our configuration. Now, let’s create a directory and a file in the project first.<br><strong>.github/workflows/docker-build.yml</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*qC7U23lXeN7CAYwfiB9dfA.png" /><figcaption>Workflow configuration for Docker Hub</figcaption></figure><p><strong>docker-build.yml config</strong></p><pre>name: Publish Docker Image<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout code<br>      uses: actions/checkout@v4<br><br>    - name: Login to docker hub<br>      run: echo &quot;${{secrets.DOCKERHUB_YOKEN}}&quot; | docker login -u &quot;${{secrets.DOCKERHUB_USERNAME}}&quot; --password-stdin<br><br>    - name: Build Docker Image<br>      run: docker build . --file Dockerfile --tag ${{secrets.DOCKERHUB_USERNAME}}/todo-back-dockerize-ec2:latest<br><br>    - name: Push Docker Image<br>      run: docker push ${{secrets.DOCKERHUB_USERNAME}}/todo-back-dockerize-ec2:latest</pre><p>Now, if we push the changes to the repository, we’ll be able to see that a workflow will be built mentioning your commit message. Sample image given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQHPRG8_Q7GYtJZ0llfutg.png" /><figcaption>Successful workflow after built</figcaption></figure><p>If everything is good so far, we’ll be able to see a tag in that specific repository on Docker Hub that we’ve created for the backend server. Sample image given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcilCllCBpEq3Oco6jGtVA.png" /></figure><p>So far, we’ve completed half of the work. That means we push the changes, and GitHub Actions builds the image in the Linux VM setup maintained by GitHub. After completing building, it gets pushed to the Docker Hub. Now, our next goal is to pull that image from the AWS EC2 instance by writing another workflow.</p><p>We’re in a stage where we have to deal with cloud components such as VPC and EC2 instances. If I show you the full process of creating a VPC, it would take a lot of time, and it could shift away from the main topic of the writing.</p><p>I want to attach a link where you’ll get the process of creating an AWS VPC, rather than showing it here.</p><blockquote><a href="https://flat-account-317.notion.site/Creating-an-AWS-VPC-30758bd50feb8065a3bceb57449fdbaa">Click here to see how to create an AWS VPC</a></blockquote><p>Now, we want to create an EC2 instance in that VPC. After creating the EC2 instance, we’ll install Docker. So it can run the application with a Dockerfile and Docker Compose configuration. Let’s create an EC2 instance.</p><blockquote><a href="https://flat-account-317.notion.site/Creating-an-AWS-EC2-Instance-30858bd50feb80a0b94bc92dc7d2d0b4">Click here to see how to create an AWS EC2 instance</a></blockquote><p>After creating the EC2 instance, we can simply install Docker on the server. Later, we’ll integrate the GitHub Actions Runner. Let’s just follow the DigitalOcean guidelines for installing Docker in an Ubuntu server. Follow Step 1 only. The link is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*RcFNk_7uJW6c7PtJnFstmA.png" /></figure><blockquote><a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04">Click here to see the guideline of installing Docker in Ubuntu</a></blockquote><p>After the installation of Docker, you can simply check the version and the status of Docker by running it like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*cEW_lpaGhBNFtwgpjbz77w.png" /></figure><p>Now, we need to link our backend repository to the AWS EC2 instance. For that, we need to create an Actions Runner. To create Actions Runner, go to <strong>Your Repository &gt; Settings. </strong>Then create a runner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TqOsQRd5inGp-BUTIGjjEA.png" /><figcaption>GitHub Action Runner</figcaption></figure><p>Make sure Runner Image is <strong>Linux </strong>and execute all the commands one by one. If you execute the command, you’ll see the title in the terminal like this.<br><strong>Note: </strong>When you run the last command from the screenshot, you need to add a label like this, because we have to pull the image from Docker Hub to EC2 instances in two servers.</p><pre>./config.sh --url https://github.com/Protik111/todo-back-dockerize-ec2 --token AJYTDFEO7BJJZS2WVSQNG2LJRNGBO --labels server-</pre><p>At the end of the command, there is a label. So when you run the command in EC2 server, make sure it has the label according to your server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nEKf3FE0sztfE6Cxv0DIgg.png" /></figure><p>Now, we’ll have to install and start <strong>svc </strong>to keep the server up and running, so whenever any changes are pushed to the GitHub reposiotry it will get the update.</p><pre>sudo ./svc.sh install<br><br>sudo ./svc.sh start</pre><p>In the EC2 instance, we’re in the <strong>actions-runner </strong>directory. We have three things on the server. One is giving permission as a user. Another two things are creating the <strong>docker-compose.yml</strong> and <strong>.env</strong> file manually. So, we’ll go one step back by using ‘<strong>cd ..</strong>’</p><p><strong>Allowing permission access:</strong></p><pre># Find the runner user (usually the user you&#39;re logged in as, or &#39;ubuntu&#39;)<br>whoami<br><br># Add your user to the docker group<br>sudo usermod -aG docker $USER<br><br># Or if the runner is running as a different user (check with &#39;ps aux | grep Runner&#39;)<br>sudo usermod -aG docker ubuntu<br><br># Verify the user was added<br>groups $USER<br><br># logout<br>exit</pre><p>Connect the server again and re-run the <strong>svc</strong></p><pre># IMPORTANT: You need to restart the runner for this to take effect<br>cd ~/actions-runner<br>sudo ./svc.sh stop<br>sudo ./svc.sh start</pre><p>We can create the file and update the file by using:</p><pre># create the file<br>sudo touch docker-compose.yml<br><br># edit the file<br>sudo nano docker-compose.yml<br><br># create the file<br>sudo touch .env<br><br># edit the file<br>sudo nano .env<br></pre><p>We’ll exactly paste and save as we have the configuration in our project. We’re done with our EC2 instance setup for the backend. As we’ll be doing load balancing between two servers with the same Express.js application, we need to create another EC2 instance in the same VPC in a similar process. The frontend server with the EC2 instance will have the same process. You should have done it by yourself. We’ll not show them here.</p><p>Now, in our project, we have to write another GitHub workflow that will pull the built image from the Docker Hub to an EC2 instance. Let’s create a file in this directory <strong>.github/workflows/aws-ec2-deploy.yml</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*dlBbxh_iUXr8-a8mz4_8yA.png" /></figure><p><strong>aws-ec2-deploy.yml config</strong></p><pre>name: Deploy Backend to EC2<br><br>on:<br>  workflow_run:<br>    workflows: [&#39;Publish Docker Image&#39;]<br>    types: [completed]<br><br>jobs:<br>  deploy-server-1:<br>    runs-on: [self-hosted, server-1]<br>    steps:<br>      - name: Check disk space<br>        run: df -h<br>      <br>      - name: Clean up Docker system<br>        run: |<br>          docker image prune -f<br>          docker images | grep todo-back-dockerize-ec2 | awk &#39;{print $3}&#39; | xargs -r docker rmi -f || true<br>          docker builder prune -f<br>      <br>      - name: Pull latest image<br>        run: docker pull ${{ secrets.DOCKERHUB_USERNAME }}/todo-back-dockerize-ec2:latest<br>        timeout-minutes: 5<br>      <br>      - name: Stop and restart containers<br>        run: |<br>          docker compose down || true<br>          docker compose up -d<br>      <br>      - name: Wait for services<br>        run: sleep 15<br>      <br>      - name: Health check<br>        run: |<br>          docker compose ps<br>          curl -f http://localhost:5000/health || echo &quot;Warning: Health check failed&quot;<br>      <br>      - name: Show app logs<br>        run: docker compose logs app --tail=30<br><br>  deploy-server-2:<br>    runs-on: [self-hosted, server-2]<br>    needs: deploy-server-1  # Deploy to server-2 only after server-1 is healthy<br>    steps:<br>      - name: Check disk space<br>        run: df -h<br>      <br>      - name: Clean up Docker system<br>        run: |<br>          docker image prune -f<br>          docker images | grep todo-back-dockerize-ec2 | awk &#39;{print $3}&#39; | xargs -r docker rmi -f || true<br>          docker builder prune -f<br>      <br>      - name: Pull latest image<br>        run: docker pull ${{ secrets.DOCKERHUB_USERNAME }}/todo-back-dockerize-ec2:latest<br>        timeout-minutes: 5<br>      <br>      - name: Stop and restart containers<br>        run: |<br>          docker compose down || true<br>          docker compose up -d<br>      <br>      - name: Wait for services<br>        run: sleep 15<br>      <br>      - name: Health check<br>        run: |<br>          docker compose ps<br>          curl -f http://localhost:5000/health || echo &quot;Warning: Health check failed&quot;<br>      <br>      - name: Show app logs<br>        run: docker compose logs app --tail=30</pre><p>We need to notice in some lines of the configuration: <br>1) <strong>workflows: [‘Publish Docker Image’]: </strong>publishing the Docker image will be the first job, then this AWS workflow will begin.<br>2) <strong>runs-on: [self-hosted, server-1]: <br>3) runs-on: [self-hosted, server-2]:</strong></p><p>If we write the configuration and push the changes successfully, we will see the action built successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Dy9KVNKhFbIns5r2h994A.png" /><figcaption>Successful Runner</figcaption></figure><p>Before accessing the live site, you need to edit inbound rules for every EC2 instance depending on your project&#39;s port number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjf8-y-rmO0p4k8K5FGMgQ.png" /><figcaption>Edit inbound rules on EC2</figcaption></figure><p>Now we’re done. If we check whether it succeeds or not by using the public IPV4 address and hit the health route from the browser (excluding HTTPS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ESTMU5er9rC5c2uJSHHOg.png" /><figcaption>Live site after deploying</figcaption></figure><p>I’me sharing the Frontend config as well. So, you can deploy in a similar way, but this time the server is one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*UcQE8GrLKXx81eOqj-doVQ.png" /><figcaption>Frontend config</figcaption></figure><p><strong>docker-build.yml config</strong></p><pre>name: Publish Frontend Docker Image<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout code<br>      uses: actions/checkout@v4<br><br>    - name: Login to docker hub<br>      run: echo &quot;${{secrets.DOCKERHUB_TOKEN}}&quot; | docker login -u &quot;${{secrets.DOCKERHUB_USERNAME}}&quot; --password-stdin<br>    <br>    - name: Build Docker Image<br>      run: docker build . --file Dockerfile --tag ${{secrets.DOCKERHUB_USERNAME}}/todo-front-dockerize-ec2:latest<br><br>    - name: Push Docker Image<br>      run: docker push ${{secrets.DOCKERHUB_USERNAME}}/todo-front-dockerize-ec2:latest</pre><p><strong>aws-deploy-frontend.yml config</strong></p><pre>name: Deploy Frontend to EC2<br><br>on:<br>  workflow_run:<br>    workflows: [&#39;Publish Frontend Docker Image&#39;]<br>    types: [completed]<br><br>jobs:<br>  deploy-frontend:<br>    runs-on: [self-hosted, frontend]<br>    steps:<br>      - name: Check disk space<br>        run: df -h<br>      <br>      - name: Stop and remove containers<br>        run: docker compose down || true<br>      <br>      - name: Clean up Docker system<br>        run: |<br>          docker image prune -f<br>          docker images | grep todo-front-dockerize-ec2 | awk &#39;{print $3}&#39; | xargs -r docker rmi -f || true<br>          docker builder prune -f<br>      <br>      - name: Pull latest image<br>        run: docker pull ${{ secrets.DOCKERHUB_USERNAME }}/todo-front-dockerize-ec2:latest<br>        timeout-minutes: 5<br>      <br>      - name: Start services<br>        run: docker compose up -d<br>      <br>      - name: Wait for services<br>        run: sleep 10<br>      <br>      - name: Check container status<br>        run: docker compose ps<br>      <br>      - name: Show frontend logs<br>        run: docker compose logs frontend --tail=30</pre><p>After creating the EC2 instance for the frontend and setting it up as like a backend server, and creating the <strong>docker-compose.yml</strong>, <strong>.env files. </strong>Add these configuraion above and push the code. The workflows will push the image to Docker Hub and pull it into the EC2 instance as well.</p><p><strong>Note: For the frontend, you should set your baseURL from the NGINX EC2 server because we’re using two servers and map into the NGINX server, which will be created now.</strong></p><p>As with backend and frontend EC2 instances, we have to create another EC2 instance for the NGINX server. But this time we don’t need the Docker installation. We’ll just install NGINX manually and configure the NGINX file. In the NGNIX EC2 server, execute these commands one by one.</p><pre># Install Nginx<br>sudo apt update<br>sudo apt install nginx -y<br><br># Start &amp; enable<br>sudo systemctl start nginx<br>sudo systemctl enable nginx<br><br># Go to config directory<br>cd /etc/nginx/conf.d<br><br># Create backend config<br>sudo nano backend.conf<br></pre><p><strong>Backend load balancer config</strong></p><pre>upstream backend_servers {<br>    server &lt;BACKEND_EC2_1_PRIVATE_IP&gt;:5000;<br>    server &lt;BACKEND_EC2_2_PRIVATE_IP&gt;:5000;<br>}<br><br>server {<br>    listen 80;<br><br>    location /api/ {<br>        proxy_pass http://backend_servers;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    }<br>}</pre><p><strong>Test &amp; reload Nginx</strong></p><pre>sudo nginx -t<br>sudo systemctl reload nginx</pre><p>After updating the NGINX configuration file and updating the frontend port from the <strong>.env</strong> file by providing the NGINX EC2 server’s public IP address, we will see the live site. And this site will use NGINX as a load balancer by following the round robin algorithm (by default).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoyKNngnIKJ2q_PosNHNKg.png" /></figure><p><strong>Reference</strong></p><p><a href="https://github.com/Protik111/todo-back-dockerize-ec2">Backend repository</a><br><a href="https://github.com/Protik111/todo-front-dockerize-ec2">Frontend Repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afaf910bb106" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/deploying-a-full-stack-app-on-aws-ec2-with-nginx-load-balancer-frontend-backend-on-separate-afaf910bb106">Deploying a Full-Stack App on AWS EC2 with Nginx Load Balancer (Frontend &amp; Backend on Separate…</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Asynchronous Behavior (Part 1) - Callbacks in Depth]]></title>
            <link>https://blog.devgenius.io/javascript-asynchronous-behavior-part-1-callbacks-in-depth-ca33fb8dcd04?source=rss-7abc0899f0fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca33fb8dcd04</guid>
            <dc:creator><![CDATA[Rafiur Rahman Protik]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 09:29:08 GMT</pubDate>
            <atom:updated>2024-09-13T15:26:31.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNQxvYNBhmp_6kAG-md4mA.png" /><figcaption>Image Source: [<a href="https://rb.gy/l1cn4k">https://rb.gy/l1cn4k</a>]</figcaption></figure><p>If you’ve been working with JavaScript for a while, chances are you’ve dived into its ecosystem without fully grasping the concept of asynchronous behavior and callbacks. Many beginners code for long periods without truly understanding the underlying mechanics of callbacks and how they function.</p><p>In this article, we’ll explore callbacks from a fresh perspective, breaking down what they really are and how they work. Along the way, we’ll touch on related concepts such as first-class functions, higher-order functions, the execution cycle of a callback, and more.</p><h4>What is a Callback?</h4><p>A callback function is a function passed into another function as an <strong>argument</strong>, which is then <strong>invoked inside the outer function</strong> to complete some kind of <strong>action</strong>.</p><p>Let’s see an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TtXX1_J_zHAZ_VSwffcYw.png" /></figure><h4>Exaplanation:</h4><ul><li>greetUser is a function that accepts a callback function as its parameter.</li><li>Inside greetUser, the callback is called with a value (userName).</li><li>sayHello is a simple function that takes a name and logs a greeting.</li><li>When greetUser(sayHello) is called, greetUser executes sayHello with userName as the argument, resulting in the greeting being printed to the console.</li></ul><p>This example illustrates a basic callback function, a concept that you’ll encounter frequently in JavaScript. If you’ve worked with JavaScript before, understanding the flow of callback functions should be straightforward.</p><p>Now in the following sections, we’ll explore key concepts related to callbacks, such as <strong>first-class functions</strong> and <strong>higher-order functions</strong>. Later, we’ll use these concepts to create a custom filter method that leverages callbacks.</p><h4>First-Class Function:</h4><p>To understand first-class functions, it’s important to recognize that in JavaScript, functions can be treated like variables.</p><p>Why is this possible?</p><p>This is due to JavaScript’s support for functional programming, a key feature of functional programming languages. Just as you can work with numbers or strings as variables, you can also handle functions in the same way. This ability to treat functions as first-class citizens is a fundamental aspect of functional programming.</p><pre>// Define a function<br>function add(a, b) {<br>  return a + b;<br>}<br><br>// Assign the function to a variable<br>const sum = add;<br><br>// Use the variable to call the function<br>console.log(sum(2, 3)); // Output: 5</pre><p>In this example, the add function is defined to add two numbers. We then assign this function to a variable named sum. Instead of calling add directly, we use the variable sum to call the function and get the result.</p><p>This shows that functions in JavaScript can be treated like regular values — stored in variables and used later.</p><h4>Higher Order Function:</h4><p>A higher-order function is a function that either takes other functions as arguments or returns a function as its result.</p><p>That means, A higher-order function can simply return a function without taking any functions as arguments. The key characteristic is that it either operates on functions (by taking them as arguments) or produces new functions (by returning them).</p><blockquote><strong><em>Now, you might be wondering about the difference between callbacks and higher-order functions</em>.</strong></blockquote><p>Actually, the concepts of <strong>callbacks</strong> and <strong>higher-order functions</strong> are related but serve different purposes…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BtCG4LuabGqQPwF0PQjgA.png" /><figcaption>Difference between callback and higher order function</figcaption></figure><h4>Key Points:</h4><ul><li><strong>Callbacks:</strong> Define actions to occur after a task, commonly used in asynchronous operations.</li><li><strong>Higher-Order Functions:</strong> Create reusable code by accepting or returning functions.</li></ul><p>Let’s deep dive into the callback functions by creating a custom method as like <strong>filter </strong>higher order function</p><p>When we use the filter method in JavaScript, we often pass an arrow function as an argument, which acts as a callback to determine which elements to include in the result. This method takes a function as an argument and uses it to filter the array, while we simply consume the result without delving into how it works under the hood.</p><p>To understand this concept more deeply, we can explore the <strong>producer</strong> and <strong>consumer </strong>roles by implementing a custom filter method in an imperative programming style (a style where you explicitly describe <em>how</em> a program should operate, step by step.).</p><p><strong>Problem: </strong>Find the only even numbers from an array of numbers.</p><p><strong>Solution (with only filter method):</strong></p><pre>const numbers = [1, 2, 3, 4, 5];<br>const evenNumbers = numbers.filter(function(number) {<br>  return number % 2 === 0; // Consumer: Filtering condition<br>});<br><br>console.log(evenNumbers); // Output: [2, 4]</pre><p><strong>Solution (with custom filter method):</strong></p><pre>// Custom filter function<br>Array.prototype.myFilter = function (callback) {<br>  const result = []; // Array to store the filtered results<br><br>  // Go through each item in the array<br>  for (let i = 0; i &lt; this.length; i++) {<br>    // Check if the item meets the condition defined in the callback<br>    if (callback(this[i], i, this)) {<br>      // If it does, add it to the result array<br>      result.push(this[i]);<br>    }<br>  }<br><br>  // Return the array of filtered items<br>  return result;<br>};<br><br>// usage<br>const numbers = [1, 2, 3, 4, 5];<br>const evenNumbers = numbers.myFilter(function (number) {<br>  // Define the condition to filter items (even numbers)<br>  return number % 2 === 0;<br>});<br><br>console.log(evenNumbers); // Output: [2, 4]</pre><p><strong>Explanation of custom filter method:</strong></p><ul><li>Array.prototype.myFilter defines a new method for all arrays. This means any array you create will have access to myFilter just like the built-in filter method.</li><li>function(callback) { ... } is the custom filter method. It accepts a single argument: callback, which is a function that will be used to test each element of the array.</li><li>result is an empty array that will store elements that pass the condition defined by the callback function.</li><li>For each element, the callback function is called with three arguments:</li><li>this[i]: The current element of the array.</li><li>i: The index of the current element.</li><li>this: The entire array.</li><li>The callback function should return true or false. If it returns true, the element meets the condition and should be included in the result.</li><li>If the callback returns true, the element (this[i]) is added to the result array.</li><li>After the loop completes, return the result array.</li></ul><p>In summary, the custom myFilter method replicates the functionality of the built-in filter method by applying a callback function to each element of an array and returning a new array with only those elements that meet the condition defined in the callback.</p><h4>Types of Callback Functions:</h4><p>There are essentially two types of callback functions: synchronous and asynchronous. When using higher-order methods like filter, map, or find, and passing a function to them, that’s an example of a synchronous callback function. We&#39;ve already created a custom method for this.</p><p>On the other hand, asynchronous callbacks work differently. For instance, with setTimeout, the function you pass is registered on the event loop side rather than the call stack, which is a key concept in asynchronous JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkgr5GE0iWFttO89OAG8FQ.png" /></figure><p>I want to conclude it now by mentioning that callbacks are essential for handling asynchronous tasks in JavaScript. Even though JavaScript is a single-threaded, synchronous language, callbacks act as a bridge between the call stack and the event loop, ensuring that asynchronous functions are executed at the right time without blocking the main thread.</p><p>In my next blog, I’ll dive deeper into how the call stack and event loop work together to run JavaScript code. With this understanding, you’ll have a clearer picture of how asynchronous programming operates in JavaScript. Don’t miss out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca33fb8dcd04" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/javascript-asynchronous-behavior-part-1-callbacks-in-depth-ca33fb8dcd04">JavaScript Asynchronous Behavior (Part 1) - Callbacks in Depth</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Optimization and Get Child State without Re-Rendering the Child Component Using useRef…]]></title>
            <link>https://medium.com/@rafiurrahmanprotik/performance-optimization-and-get-child-state-without-re-rendering-the-child-component-using-useref-d649ab7db960?source=rss-7abc0899f0fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/d649ab7db960</guid>
            <category><![CDATA[rerender]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Rafiur Rahman Protik]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 19:42:36 GMT</pubDate>
            <atom:updated>2023-11-29T14:33:35.346Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance Optimization and Get Child State without Re-Rendering the Child Component Using useRef, UseImperativeHandle, and Forwarding Refs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3IJaEsj63N8A8fKV.png" /><figcaption>Image Source [<a href="https://rb.gy/eijcxw">https://rb.gy/eijcxw</a>]</figcaption></figure><p>The term <strong>‘Render</strong>’ refers to displaying the React UI elements. React efficiently renders and updates the components based on parameters such as state changes, props changes, etc.</p><h3><strong>Let’s see why components re-render and why it is crucial in some context.</strong></h3><p>When we talk about “re-rendering,” we are specifically referring to the act of updating the DOM (Document Object Model) with new content based on changes in the React components. React components can have an internal state and receive data through props. When the state or props of a component change, React will trigger a re-render of that component. <strong>We can say React components can re-render in several ways such as state changes, props changes, context changes, parent component re-renders, hooks(useState, useEffect), etc.</strong></p><p>Re-rendering is a fundamental aspect of React that allows for dynamic and responsive user interfaces, it can potentially impact performance if not managed carefully.</p><h4>Visual Representation of Component Re-Rendering:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*fVZ5LK7T235P2yRV.gif" /><figcaption>Component Re-Rendering[Source: <a href="https://media.geeksforgeeks.org/wp-content/uploads/20231031094545/Peek-2023-10-31-09-44.gif">https://media.geeksforgeeks.org/wp-content/uploads/20231031094545/Peek-2023-10-31-09-44.gif</a>]</figcaption></figure><h4>Example of a Component Re-Rendering:</h4><pre>// ParentComponent.js<br>import React, { useState } from &#39;react&#39;;<br>import ChildComponent from &#39;./ChildComponent&#39;;<br><br>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br><br>  const handleClick = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  // Problematic: This function is created on each render<br>  const computeValue = () =&gt; {<br>    console.log(&#39;Computing new value&#39;);<br>    return count * 2;<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;p&gt;Computed Value: {computeValue()}&lt;/p&gt;<br>      &lt;ChildComponent onClick={handleClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// ChildComponent.js<br>import React from &#39;react&#39;;<br><br>function ChildComponent({ onClick }) {<br>  console.log(&#39;ChildComponent is re-rendering&#39;);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Child component content&lt;/p&gt;<br>      &lt;button onClick={onClick}&gt;Increment from Child&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ChildComponent;</pre><p>In this example, every time the ParentComponent re-renders (e.g., when the button is clicked), a new computeValue the function is created. This causes unnecessary re-renders of the ChildComponent, even though its rendering logic doesn&#39;t depend on the computeValue function. This is a very basic example of component re-rendering. We can solve this by memoizing the value of computeValue to prevent the re-render of the component.</p><p>In this article, Instead of using like useMemo , useCallback , we’ll optimize the components with some functions and hooks like useImperativeHandle , forwardRef , useRef . We’ll build a simple multi-step form with these hooks and functions.</p><h4>Let’s Jump on It:</h4><p>We know that a multi-step form could have some steps that we can build with some components. Let’s see how we can write the logic(state, validation, API call) in a MultiStepForm.js and can call other components that could be like FirstStep.js , SecondStep.js , ThirdStep.js etc.</p><h4>MultiStepForm.js</h4><pre>import { useState, useRef } from &#39;react&#39;;<br>import { Steps, Button, Spin } from &#39;antd&#39;;<br>import FirstStep from &#39;./FirstStep&#39;;  // Import the FirstStep component<br>import SecondStep from &#39;./SecondStep&#39;;  // Import the SecondStep component<br>import ThirdStep from &#39;./ThirdStep&#39;;  // Import the ThirdStep component<br><br>const date = new Date();<br><br>const MultiStepForm = () =&gt; {<br>  const [current, setCurrent] = useState(0);  // Track the current step<br>  const [isSubmitting, setIsSubmitting] = useState(false);  // Track form submission status<br><br>  const [phone, setPhone] = useState(&#39;&#39;);<br>  const [date, setDate] = useState(date.toLocaleString());<br>  const [time, setTime] = useState(&#39;12:30 PM&#39;);<br>  const [authorizedInUS, setAuthorizedInUS] = useState(true);<br>  const [launchCareer, setLaunchCareer] = useState(true);<br><br>  //reference for interecting with child component<br>  const childRef = useRef();<br><br>  // Define the steps of the form<br>  const steps = [<br>    {<br>      title: &#39;Contact&#39;,<br>      content: &lt;FirstStep<br>        ref={childRef}<br>        phone={phone}<br>        setPhone={setPhone}<br>      &gt;&lt;/FirstStep&gt;,<br>    },<br>    {<br>      title: &#39;Select Date&#39;,<br>      content: &lt;SecondStep<br>        ref={childRef}<br>        date={date}<br>        setDate={setDate}<br>        time={time}<br>        setTime={setTime}<br>      &gt;&lt;/SecondStep&gt;,<br>    },<br>    {<br>      title: &#39;Submit&#39;,<br>      content: &lt;ThirdStep<br>        ref={childRef}<br>        launchCareer={launchCareer}<br>        setLaunchCareer={setLaunchCareer}<br>        authorizedInUS={authorizedInUS}<br>        setAuthorizedInUS={setAuthorizedInUS}<br>      &gt;&lt;/ThirdStep&gt;<br>    }<br>  ];<br><br>  const items = steps.map((item) =&gt; ({<br>    key: item.title,<br>    title: item.title,<br>  }));<br><br>  // Function to go to the previous step<br>  const prev = () =&gt; {<br>    setCurrent(current - 1);<br>  };<br><br>  // Function to go to the next step<br>  const next = () =&gt; {<br>    childRef.current.validateFields();  // Example: Validate fields in the child component<br>    setCurrent(current + 1);<br>  };<br><br>  // Function to handle form submission<br>  const handleSubmit = () =&gt; {<br>    setIsSubmitting(true);<br>    // Perform form submission logic<br>    // ...<br>    setIsSubmitting(false);<br>  };<br><br>  return (<br>    &lt;div className=&quot;form&quot;&gt;<br>      &lt;Steps current={current} items={items} /&gt;<br><br>      {/* Display the content of the current step */}<br>      &lt;div className=&quot;steps-content&quot;&gt;{steps[current].content}&lt;/div&gt;<br><br>      {/* Display navigation buttons based on the current step */}<br>      &lt;div className=&quot;steps-action&quot;&gt;<br>        {current &gt; 0 &amp;&amp;<br>          (&lt;Button<br>            variant=&quot;gradient&quot; gradient={{ from: &#39;indigo&#39;, to: &#39;cyan&#39; }}<br>            onClick={() =&gt; prev()}<br>          &gt;&amp;larr; Previous<br>          &lt;/Button&gt;<br>          )}<br><br>        {current &lt; steps.length - 1 &amp;&amp; current === 1 &amp;&amp; (<br>          &lt;Button className=&#39;next_btn&#39; variant=&quot;gradient&quot; gradient={{ from: &#39;teal&#39;, to: &#39;blue&#39;, deg: 60 }} onClick={() =&gt; next()}&gt;<br>            Next &amp;rarr;<br>          &lt;/Button&gt;<br>        )}<br><br>        {current === steps.length - 1 &amp;&amp; (<br>          &lt;Button disabled={isSubmitting} className=&#39;next_btn&#39; color=&quot;violet&quot; onClick={() =&gt; handleSubmit()}&gt;<br>            {isSubmitting &amp;&amp; &lt;Spin /&gt;} Submit<br>          &lt;/Button&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MultiStepForm;</pre><p>Let’s break down the code and its functionality:</p><h4>Description of the Code:</h4><p>In this above example, Firstly, it imports necessary elements from the ‘react’ and ‘antd’ libraries. Additionally, it imports child components (FirstStep, SecondStep, and ThirdStep) from separate files, assuming they are implemented there. it also has some states like (phone, date, etc.) Date object.</p><p>The useRef hook is utilized to create a reference (childRef) for interacting with child components.</p><p>The steps array is defined to represent different steps of the multi-step form. Each step includes a title and the JSX of the corresponding child component (content)</p><p>Several functions are defined to facilitate form navigation:</p><ul><li>The prev function allows users to go back to the previous step by decrementing the current step.</li><li>The next function is designed for moving forward. It first validates fields in the child component validateFields and then increments the current step.</li></ul><blockquote>NB : It’ll be discussed what <strong><em>childRef.current.validateFields() </em></strong>does in the next function eventually. And also all the states are in individualt state, It can be in a single objects and that’s a good practice. For now we can move forward by ignoring this part.</blockquote><h4>Let’s Jump on a Child Component(SecondStep.js):</h4><pre>import React, { forwardRef, useImperativeHandle, useState } from &#39;react&#39;;<br>import { Select } from &#39;antd&#39;;<br>import { AsYouType, parsePhoneNumber } from &#39;libphonenumber-js&#39;;<br>import PhoneInput from &#39;react-phone-input-2&#39;;<br>const { Option } = Select;<br><br>// Define the FirstStep component using forwardRef to forward a ref to the parent component<br>const FirstStep = forwardRef((props, ref) =&gt; {<br>  let {<br>    setPhone,  <br>    phone,    <br>  } = props;<br><br>  const [errors, setErrors] = useState(null);<br><br>  // Function for validating the form inputs<br>  const formValidator = ({ phone }) =&gt; {<br>    let error = {};<br><br>    // Check if the phone number is provided<br>    if (!phone) {<br>      error.phone = &quot;Enter your phone number&quot;;<br>    } else {<br>      try {<br>        // Parse and validate the phone number using libphonenumber-js<br>        const phoneNumber = parsePhoneNumber(phone, &#39;US&#39;);<br>        if (!phoneNumber.isValid()) {<br>          error.phone = &quot;Invalid phone number&quot;;<br>        }<br>      } catch (error) {<br>        return (error.phone = &quot;Invalid phone number&quot;);<br>      }<br>    }<br><br>    // Return the error object and a flag indicating whether there are errors<br>    return {<br>      error,<br>      isError: Object.keys(error).length === 0,<br>    };<br>  };<br><br>  // Use useImperativeHandle to expose a validate method to the parent component<br>  useImperativeHandle(ref, () =&gt; ({<br>    validate() {<br>      // Call the formValidator function to validate the phone number<br>      const validate = formValidator({ phone });<br><br>      // Update the state with validation errors if any<br>      if (!validate.isError) {<br>        return setErrors(validate.error);<br>      } else {<br>        // If no errors, reset the errors state and return true<br>        setErrors(null);<br>        return true;<br>      }<br>    },<br>  }));<br><br>  return (<br>    &lt;&gt;<br>      {/* Render the UI for the first step of the form */}<br>      &lt;div className=&#39;single_input_date&#39;&gt;<br>        &lt;div&gt;<br>          &lt;div className=&quot;zone&quot;&gt;&lt;/div&gt;<br>          &lt;div style={{ padding: 0 }}&gt;<br>            {/* Label for the phone input */}<br>            &lt;label htmlFor=&quot;phone&quot; className=&quot;required&quot;&gt;<br>              US or Canada Phone &lt;span&gt;*&lt;/span&gt;<br>            &lt;/label&gt;<br>            {/* PhoneInput component for entering the phone number */}<br>            &lt;PhoneInput<br>              country={&#39;us&#39;}<br>              onlyCountries={[&quot;us&quot;, &quot;ca&quot;]}<br>              value={phone}<br>              onChange={(phone) =&gt; setPhone(phone)}<br>              countryCodeEditable={false}<br>              inputProps={{<br>                autoFocus: true,<br>              }}<br>            /&gt;<br>            {/* Display validation error if present */}<br>            {errors &amp;&amp; errors.phone &amp;&amp; (<br>              &lt;span className=&quot;error_text&quot;&gt;{errors.phone}&lt;/span&gt;<br>            )}<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>});<br><br>// Export the FirstStep component<br>export default FirstStep;</pre><p>This FirstStep component is part of a multi-step form. It focuses on collecting and validating the user&#39;s phone number for the first step. Before moving forward we need to understand what forwardRef and useImperativeHandle do?</p><h4>forwardRef:</h4><p>The function forwardRef is used to forward a ref to the parent component. This allows the parent to interact with the methods or properties of this component.</p><h4>useImperativeHandle:</h4><p>The useImperativeHandle hook in React is used to expose specific functions or methods from a child component to its parent component. It allows a child component to provide a clean and controlled interface for the parent to interact with, typically for imperative operations or actions. This hooks exposes a validate method to the parent component. This method can be invoked by the parent to trigger form validation. Remember the <strong><em>childRef.current.validateFields() </em></strong>methods in the next function of the<strong><em> </em></strong>MultiStepForm.js file.</p><p>The useImperativeHandle hook is designed to avoid unnecessary re-renders by allowing you to specify which values or functions you want to expose to the parent component. When you use useImperativeHandle, you are essentially telling React to memoize certain values or functions (validate() in FirstStep component) and only update them when necessary. This helps prevent unnecessary re-renders of the child component.</p><p>In my opinion, this is a good option to avoid unnecessary re-renders by allowing you to specify which values or functions you want to expose to the parent component. It is not limited to exposing just methods, it can also be used to expose state variables or any other values that you want the parent component to have access to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d649ab7db960" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crud Operation with Array and Object in JavaScript.]]></title>
            <link>https://towardsdev.com/crud-operation-with-array-and-object-in-javascript-56af95aff3b2?source=rss-7abc0899f0fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/56af95aff3b2</guid>
            <category><![CDATA[methods]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Rafiur Rahman Protik]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 06:54:31 GMT</pubDate>
            <atom:updated>2022-02-09T07:23:10.767Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*llIOfKIBEEvan_5DKt5HYA.png" /><figcaption>Arrays and Objects in JavaScript.</figcaption></figure><p>In this article I’m going to show you how to perform crud operation with just array and object in JavaScript. And We’ll see a little bit comparison of time complexity between array and object.</p><p>Many of us may’ve done some projects with crud operation with backend server and API. But today we’ll see a different approach how we can perform basic crud(create, read, update, delete) operation to manipulate data in local memory. First of all we’ll see example with array and then object.</p><h3>Array</h3><p>We all know array is a special variable that can hold more than one value. For the example purpose we’ll take a instructors array below.</p><pre>const instructors = [<br>   {<br>     id: &#39;ee9efd79-92bb-4d9f-a4dc-d340e63739b7&#39;,<br>     name: &#39;Ben Awad&#39;,<br>     email: &#39;benawad@gmail.com&#39;,<br>   },<br>   {<br>     id: &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;,<br>     name: &#39;Hussein Nasser&#39;,<br>     email: &#39;hussein@gmail.com&#39;,<br>   }<br>];</pre><p>In the above example, we just took a array of objects with two objects. Now we’ll do crud operation.</p><h4>Create</h4><pre>//unique id generator<br>function uuid() {<br>      return &#39;xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx&#39;.replace(/[xy]/g<br>    ,(c) =&gt; {<br>      const r = (Math.random() * 16) | 0;<br>      const v = c == &#39;x&#39; ? r : (r &amp; 0x3) | 0x8;<br>      return v.toString(16);<br>})};</pre><pre>//new instructor<br>const newIns = {<br>      id: uuid(),<br>      name: &#39;Mosh Hamdani&#39;,<br>      email: &#39;mosh@gmail.com&#39;<br>}<br>//adding new intructor<br>instructors.push(newIns);</pre><p>For creating a new element to instructors array, first of all we created a unique id generator function that is basically taken from stackoverflow. Then we took newIns object that’ll be added to the array. Finally we added a new element to the array with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">push()</a> method. We can also add a element to the beginning of the array with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift">unshift()</a>.</p><h4>Time Complexity:</h4><p><strong>push() — O(1)</strong> [explanation: It’ll calculate total length of the array and then will add the pushed element in (length+1) index]</p><p><strong>unshift() — O(n)</strong>[explanation: As it has to add element in the beginning so it will iterate every element and replace the value in next index]</p><blockquote>NB : If you practice on yourself along with reading this article and see the output it’ll be more effective.</blockquote><h4>Update</h4><pre>//update a element<br>const id = &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;;<br>const index = instructors.findIndex((item) =&gt; item.id === id);</pre><pre>const updatedData = {<br>      name: &quot;Hussein Backend&quot;,<br>      email: &quot;husseinback@gmail.com&quot;<br>   }<br>instructors[index] = {<br>      ...instructors[index],<br>      ...updatedData<br>   };</pre><p>For updating an element in the array we searched by an id with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex">findIndex()</a> method then changed the specific element with the index. We used <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread(…)</a> operator to the specific index because updating an element without spread operator will not copy rest of the property.</p><h4>Time Complexity:</h4><p><strong>findIndex() — O(n)</strong> [explanation: It’ll iterate every element of the array to find the index]</p><h4>Delete</h4><pre>//delete a element<br>const id = &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;;</pre><pre>const index = instructors.findIndex((item) =&gt; item.id === id);</pre><pre>instructors.splice(index, 1);</pre><p>For deleting an element from the array we simply used <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">splice()</a> method and passed the index of the element and total number of element to be removed. We can also use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter()</a> method to remove an element.</p><h4>Time Complexity:</h4><p><strong>findIndex() — O(n)</strong> [explanation: It’ll iterate every element of the array to find the index and then delete]</p><h4>Traverse(Get)</h4><p>For getting all the element from the array we can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach()</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map()</a> method. But these all methods are declarative. If you want to get in a imperative way you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">for</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for of</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for in</a> loop.</p><h4>Time Complexity:</h4><p><strong>forEach(), map() — O(n)</strong> [explanation: It’ll iterate every element of the array]</p><h3>Objects</h3><p>Objects are variables too. But objects can contain many values. And the values are stored with (key:value) pair. We’ll simply use the above instructors arrays as a object.</p><pre>const instructors = {<br>   &quot;ee9efd79-92bb-4d9f-a4dc-d340e63739b7&quot;: {<br>      id: &#39;ee9efd79-92bb-4d9f-a4dc-d340e63739b7&#39;,<br>      name: &#39;Ben Awad&#39;,<br>      email: &#39;benawad@gmail.com&#39;,<br>   },<br>   &quot;49350b1b-b450-418f-a840-c7aa53617a7f&quot;: {<br>      id: &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;,<br>      name: &#39;Hussein Nasser&#39;,<br>      email: &#39;hussein@gmail.com&#39;,<br>   }<br>}</pre><p>In the above code we simply used the instructors array as a object but to make key value pair we used id as a key and id, name, email as value. Now we’ll see how easily we can perform crud operation with object.</p><h4>Create</h4><pre>//creating a new object<br>const newIns = {<br>       id: uuid(),<br>       name: &#39;Brad Traversy&#39;,<br>       email: &#39;brad@gmail.com&#39;<br>   }<br>instructors[newIns.id] = newIns;</pre><p>For creating an property in the object we created a object newIns and in the id field we called uuid() function to generate new unique id. To push in the object we simply used bracket notation and then pushed the new object.</p><p><strong>Hints:</strong> instructors[newIns.id] === instructors[generated id];</p><h4>Time Complexity:</h4><p><strong>O(1)</strong> [explanation: It’ll not iterate every element of the array and it’ll just add to the instructor object]</p><h4>Update</h4><pre>//update<br>const id = &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;;<br>const updatedData = {<br>      name: &quot;Hussein Backend&quot;,<br>      email: &quot;husseinback@gmail.com&quot;<br>   }<br>instructors[id]= {<br>      ...instructors[id],<br>      ...updatedData<br>   }</pre><p>For updating an property in the object we accessed the id property with bracket notation with the specific id. And we used <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread(…)</a> operator to the specific id because updating an property without spread operator will not copy rest of the property.</p><h4>Time Complexity:</h4><p><strong>O(1)</strong> [explanation: It’ll not iterate every element of the object to find the property.]</p><h4>Delete</h4><pre>//delete<br>const id = &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;;<br>delete instructors[id];</pre><p>Surprised!!😲 We can delete an property with just <a href="https://www.w3schools.com/howto/howto_js_remove_property_object.asp">delete</a> operator. On the contrary in array we had to find index then splice. So with object we get let complexity. But arrays has different use cases. We just wanted to see how things work.</p><h4>Time Complexity:</h4><p><strong>O(1)</strong> [explanation: It’ll not iterate every element of the object to find the property and it’ll just remove the property with delete operator.]</p><h4>Traverse(Get)</h4><pre>//get by id<br>const id = &#39;49350b1b-b450-418f-a840-c7aa53617a7f&#39;;<br>console.log(instructors[id]);</pre><pre>//traverse<br>for (let i in instructors){<br>      console.log(instructors[i]);<br>   }</pre><p>To get specific property we can access with bracket notation by passing an id. But to get all the property we can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for in</a> loop.</p><h4>Time Complexity:</h4><p><strong>Specific Id — O(1)</strong> [explanation: It’ll not iterate every element of the object to find the property.]</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><strong>for…in</strong></a><strong> — O(n) </strong>[explantion:<strong> </strong>It’ll iterate every element of the object to find the property.]</p><p>Thank you everyone to read this article. In my writing there could be some silly mistakes, I request all of you to pardon my mistakes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56af95aff3b2" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/crud-operation-with-array-and-object-in-javascript-56af95aff3b2">Crud Operation with Array and Object in JavaScript.</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express.js Project Structure and Middleware Concept for Beginners.]]></title>
            <link>https://medium.com/@rafiurrahmanprotik/express-js-project-structure-and-middleware-concept-for-beginners-ff7bb0baea35?source=rss-7abc0899f0fa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff7bb0baea35</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[folder-structure]]></category>
            <dc:creator><![CDATA[Rafiur Rahman Protik]]></dc:creator>
            <pubDate>Fri, 10 Dec 2021 05:19:50 GMT</pubDate>
            <atom:updated>2023-12-07T04:51:58.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Resz01SPSBJ8weWM0HafQ.png" /><figcaption>Express.js Project Structure [Source: <a href="https://www.spec-india.com/">https://www.spec-india.com/</a> and <a href="https://afteracademy.com/">https://afteracademy.com/</a>]</figcaption></figure><p>Express.js is one of the most popular backend frameworks with built-in JavaScript runtime Nodejs. In any framework project structuring plays a significant role in developing an application. Today, We’ll see a project structuring in Express.js.</p><p>Most beginners find it very difficult to organize and manage their code when writing in Express.js framework. Here I’ll share an approach to writing a manageable, organized, and scalable code for a <a href="https://en.wikipedia.org/wiki/Monolithic_application#:~:text=In%20software%20engineering%2C%20a%20monolithic,independent%20from%20other%20computing%20applications.">monolithic application</a> in a beginner-friendly way.</p><p>As you are reading this article as a beginner or an intermediate you might have experienced some concepts of middleware. But to go further we must get some insights into what is middleware and also the built-in middleware provided by the <a href="https://github.com/orgs/expressjs/people">Express.js team</a>.</p><h3>Middleware</h3><p>To define the middleware, It’s just a function that has access to the request object (req), the response object (res), and the next function of an application’s request-response cycle. Now you may be confused with the definition and what is actually the request-response cycle, request object, and response object. Now we’ll see some key points that will clear the confusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMhE9T_tuC0pUoZyWKWSnQ.png" /><figcaption>Client and Server Communication [Source: <a href="https://bytesofgigabytes.com/">https://bytesofgigabytes.com/</a>]</figcaption></figure><p>Look at the above picture, It’s a communication between client and server with HTTP <a href="https://en.wikipedia.org/wiki/Communication_protocol#:~:text=A%20communication%20protocol%20is%20a,and%20possible%20error%20recovery%20methods.">protocol</a>. We won’t go deep inside of <a href="https://en.wikipedia.org/wiki/Request%E2%80%93response">request-response</a> cycle. Our main concern is to understand the middleware concept. Now to understand the request-response cycle consider a user from the browser types a URL on the search bar and requests for his/her desired results that is called a request and when getting the request from the user, the server sends it back a possible result to the user is called response. This is the basic concept of the request-response cycle.</p><p>By Understanding the request-response cycle, a middleware’s job is to change/modify the user’s request, that is the responsibility of a middleware. It’s a controller function that can control the user’s request and response. Below here, these are some tasks that are done by the middleware.</p><ul><li>Execute any code.</li><li>Each middleware performs a specific task.</li><li>End the request-response cycle at any time.</li><li>Make changes to the request and the response objects.</li><li>Call the next middleware in the stack.</li></ul><pre>//Middleware Signature</pre><pre>const express = require(&#39;express&#39;);<br>const app = express();</pre><pre>app.get(&#39;/&#39;, function(req, res, next){<br>     next();<br>});</pre><pre>app.listen(3000);</pre><p>When writing a middleware we’ve to consider three parameters. (req, res) as usual and a next function. It’s a callback function. It is called when another middleware is written right after. If we don’t call the next function then the server will stuck and it won’t run. We can return a response from the middleware but usually, for returning the response we use another controller function. Now you may confused about a controller function and middleware. These two both are functions and they have the same signature, the main difference is that we return a response from the controller function but not from the middleware in most of the cases. In some edge cases, we can return a response from the middleware instead of invoking the next function. But It is used in rare cases.</p><h4>Where To Use Middleware</h4><p>Middleware could be used in two ways.</p><ol><li>Globally.</li><li>Locally.</li></ol><p>When writing middleware it is written either globally so every route of the application will have the middleware or locally which means the middleware is used in specific routes.</p><h4>Global Middleware</h4><pre>//Global Middleware<br>app.use(simpleLogger);</pre><pre>const simpleLogger = (req, res, next) =&gt; {<br>     console.log(`${req.url} - ${new Date().toLocalString()}`);<br>     next();<br>};</pre><p>In the above example, we used a global middleware. One thing is to note that every global middleware is used in app.use() method. And when we involk it we don’t have to put parenthesis () manually because express library will do it for us.</p><h4>Local Middleware</h4><pre>//Local Middleware</pre><pre>//first middleware<br>const simpleLogger = (req, res, next) =&gt; {<br>     console.log(`${req.url} - ${new Date().toLocalString()}`);<br>     next();<br>};</pre><pre>//second middleware<br>const secondMiddleware = (req, res, next) =&gt; {<br>     console.log(&quot;This is the second middleware&quot;);<br>     next();<br>};</pre><pre>//passing two middlwares<br>app.get(&#39;/date&#39;, simpleLogger, secondMiddleware, (req, res) =&gt; {<br>     res.json({<br>          message: &quot;Success&quot;<br>     });<br>});</pre><p>In the above example, we used a local middleware. We simply used the middleware inside the specific routes. For more, the Express.js team also provided us with some <a href="https://expressjs.com/en/resources/middleware.html">built-in middleware</a> that is essential for building any kind of application easily in a short time.</p><h3>Project Scaffolding</h3><p>To develop an application we should choose an ideal architecture so the code can be manageable, and scalable. And when working with a team all the members can work smoothly. We’ll go through a design principle that is a layered architecture. It is a monolithic architecture for developing monolithic applications. We can choose a distributed structure or microservice architecture when the users of the application will be very high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/1*gb1KMPHBLCQWK8vQgc3HGA.png" /><figcaption>Project Structure in VisualStudioCode</figcaption></figure><p>In the above picture, this is the folder structure of an express project. It’s a monolithic architecture which means it is composed all in one piece. The components of the project are interconnected and interdependent rather than loosely coupled. We defined some folders for specific tasks. Every folder will perform its task. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*Y-z4Q5-hlpw--CEKDASOsw.png" /><figcaption>app Folder</figcaption></figure><p>In the app folder, we created four files and their job is specific for the application. In app.js file we simply imported an express module that returns a function express and we created an app object by calling that express() function. We exported the application file but did not create a server in the app.js file for two reasons one is for testing purposes and another one is for protocol purposes (websocket). In the long run, we could use WebSocket. So we didn’t run the application in the app.js file but in the server.js file.</p><p><strong>app.js file :</strong></p><pre>//importing dotenv package <br>require(&#39;dotenv&#39;).config(&#39;../.env&#39;);</pre><pre>const express = require(&#39;express&#39;);</pre><pre>//error handler from route file<br>const { notFoundHandler, errorHandler } = require(&#39;./error&#39;)<br></pre><pre>const app = express();<br></pre><pre>//using middleware from middleware file<br>app.use(require(&#39;./middleware&#39;));</pre><pre>//using route file<br>app.use(require(&#39;./routes&#39;));</pre><pre>//using error handler from error file<br>app.use(notFoundHandler);</pre><pre>app.use(errorHandler);<br></pre><pre>//exporting app<br>module.exports = app;</pre><p>You already may be familiar with dotenv. It’s a package for securing the application’s data. We used dotenv package and some middleware related to the application folder. Now look at server.js file in the root folder.</p><p><strong>server.js file :</strong></p><pre>require(&#39;dotenv&#39;).config()</pre><pre>//http modules<br>const http = require(&#39;http&#39;);</pre><pre>//importing application from app file <br>const app = require(&#39;./app/app&#39;);<br></pre><pre>//creating server<br>const server = http.createServer(app);<br></pre><pre>const PORT = process.env.PORT || 8000;<br></pre><pre>//listening to port<br>server.listen(PORT, () =&gt; {</pre><pre>console.log(`Listening to ${PORT}`);</pre><pre>})</pre><p>By looking at the file what did you understand? We just required the app file in a common js style and created the server by http modules. That’s the job of the server.js file. We specified their responsibility by individual file so the whole application can be manageable and maintainable. We created a middleware file, a routes file, and an error file inside the app folder for handling errors and for routing applications. There is some built-in middleware like morgan (for logger), <a href="https://www.npmjs.com/package/cors">cors</a>, express.json(), etc in the middleware file.</p><p><strong>middleware.js file</strong></p><pre>const express = require(&#39;express&#39;);</pre><pre>const morgan = require(&#39;morgan&#39;);</pre><pre>const cors = require(&#39;cors&#39;);<br></pre><pre>const middleware = [morgan(&#39;dev&#39;), cors(), express.json()];</pre><pre>module.exports = middleware;</pre><p>And routes, error files hold the routing and default error handler.<strong> [</strong><a href="https://github.com/Protik111/Express.js-project-structure"><strong>Go to the github repository link</strong></a>].</p><p>Another thing to write down is that sometimes we used _req or _res instead of just req, and res because of deployment purposes. When the project is ready for deployment many cloud providers like DigitalOcean throws an error when an unused object is written like req, res. So in every unused object, it should be written with a _(underscore). <a href="https://github.com/Protik111/Express.js-project-structure/blob/main/app/error.js"><strong>[See code]</strong></a></p><p>We also put a health route in our routes file. It’s also for deployment purposes because cloud providers test our application with a ‘/health’ route. To Solve the problem we should return 200 status code if we hit ‘/health’ route. <a href="https://github.com/Protik111/Express.js-project-structure/blob/main/app/routes.js"><strong>[See code]</strong></a></p><p>For other configurations in the project like database connection, custom middleware, controller, model, error handler, test etc I can write another story if you want. But It’s a basic overview of structuring an Express.js project.</p><p><a href="https://github.com/Protik111/Express.js-project-structure"><strong>Visit The Github Repository Link</strong></a><strong> </strong>[Note: Github ignored the empty folder. It’ll be added when I finish my all configuration.]</p><p>In my writing there could be some silly mistakes, I request all of you to pardon my mistakes. Thank You!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff7bb0baea35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>