<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Piyush Garg]]></title><description><![CDATA[22 years old application and web developer. Certified in C, C++, And Java. Completed IT Trainings in Web Development, Javascript, MERN and web Designs, Android.]]></description><link>https://blog.piyushgarg.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 10 Apr 2026 09:07:49 GMT</lastBuildDate><atom:link href="https://blog.piyushgarg.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[FullStack Twitter Clone]]></title><description><![CDATA[Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullSt...]]></description><link>https://blog.piyushgarg.dev/twitter-clone</link><guid isPermaLink="true">https://blog.piyushgarg.dev/twitter-clone</guid><category><![CDATA[fullstack]]></category><category><![CDATA[MERN Stack]]></category><category><![CDATA[AWS]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Wed, 03 May 2023 12:24:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1683116565613/a2840d08-daf1-425f-9305-3db6c5aafad4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullStack Twitter Clone using the latest technologies.</p>
<p>Link to Course: <a target="_blank" href="https://learn.piyushgarg.dev/learn/twitter-clone?COUPON=EARLY_BIRD">https://learn.piyushgarg.dev/learn/twitter-clone?COUPON=EARLY_BIRD</a></p>
<h1 id="heading-overview"><strong>Overview</strong></h1>
<p>In this tutorial, we will create a FullStack Twitter Clone that allows users to create and post tweets, follow other users, and like, and view their own profiles and the profiles of other users.</p>
<h1 id="heading-tech-stack">Tech Stack</h1>
<ul>
<li><p><strong>Node.js</strong> for our backend code would run the graphql server inside the node.js environment.</p>
</li>
<li><p><strong>GraphQL</strong> for our API provides a flexible and efficient way to define and query our data model.</p>
</li>
<li><p><strong>Prisma ORM</strong> for our database ORM, which provides a type-safe and easy-to-use interface for interacting with our PostgreSQL database.</p>
</li>
<li><p><strong>PostgreSQL</strong> is our database, which is a powerful and reliable relational database system.</p>
</li>
<li><p><strong>Supabase</strong> for hosting and managing cloud Postgresql db.</p>
</li>
<li><p><strong>Redis</strong> for query caching on the server side and increasing query speeds</p>
</li>
<li><p><strong>Google OAuth</strong> for Sign in with Google</p>
</li>
<li><p><strong>JSON WEB TOKENS</strong> for authentication</p>
</li>
<li><p><strong>Next.js</strong> for our front end is a popular framework for building React applications with server-side rendering and optimized performance.</p>
</li>
<li><p><strong>TailwindCSS</strong> for styling and reusable components.</p>
</li>
<li><p><strong>Codegen</strong> for typesafe graphql queries and mutations.</p>
</li>
<li><p><strong>Graphql-Request</strong> as API client for client-server communication</p>
</li>
<li><p><strong>React-Query</strong> for client-side data caching and query caching</p>
</li>
<li><p><strong>Typescript</strong> to maintain code quality and write type-safe code.</p>
</li>
<li><p><strong>Amazon Web Services</strong> for storage and deployments.</p>
</li>
</ul>
<h1 id="heading-prerequisites"><strong>Prerequisites</strong></h1>
<p>To follow along with this tutorial, you will need the following:</p>
<ul>
<li><p>Basic programming knowledge</p>
</li>
<li><p>Min 6 months of experience with Node.js and Express</p>
</li>
<li><p>Beginner-level experience with React and NextJS</p>
</li>
<li><p>Overview of Graphql (Optional)</p>
</li>
</ul>
<h1 id="heading-learning-outcomes">Learning Outcomes</h1>
<p>After this course, learners would have a strong hands-on over several latest technologies, tools and programming practices such as:</p>
<ul>
<li><p>How to use Graphql with Express</p>
</li>
<li><p>How to use PrismaORM with Node and PostgreSQL</p>
</li>
<li><p>How relational DBs work and how to make relations in SQL database</p>
</li>
<li><p>Complex Joins and Lookups in SQL using Prisma ORM</p>
</li>
<li><p>Client Query Caching with React Query</p>
</li>
<li><p>On-Demand Query Invalidation</p>
</li>
<li><p>Server Side Data Fetching and Rendering with Next.js SSR</p>
</li>
<li><p>How to Implement OAuth from Scratch</p>
</li>
<li><p>Creating Custom Hook Wrappers around React Query</p>
</li>
<li><p>Redis Caching to increase query speeds</p>
</li>
<li><p>Configuring and Setting up Custom S3 Bucket Policy on AWS</p>
</li>
<li><p>Uploading Media to AWS S3 using Pre-Signed URLs</p>
</li>
<li><p>Working in Typesafe code check with Typescript and Codegen</p>
</li>
</ul>
<p>Link to Course: <a target="_blank" href="https://learn.piyushgarg.dev/learn/twitter-clone?COUPON=EARLY_BIRD">https://learn.piyushgarg.dev/learn/twitter-clone?COUPON=EARLY_BIRD</a></p>
]]></content:encoded></item><item><title><![CDATA[Tic Tac Toe Game in Javascript]]></title><description><![CDATA[Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript.
https://youtu.be/lKe57l8sttw
 
Code
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE...]]></description><link>https://blog.piyushgarg.dev/tic-tac-toe-game-in-javascript</link><guid isPermaLink="true">https://blog.piyushgarg.dev/tic-tac-toe-game-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Mon, 26 Dec 2022 14:34:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672064875309/7eedebef-c344-4971-978b-8543b04853e0.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/lKe57l8sttw">https://youtu.be/lKe57l8sttw</a></div>
<p> </p>
<h1 id="heading-code">Code</h1>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Tic Tac Toe<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
      <span class="hljs-selector-tag">body</span> {
        <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Segoe UI"</span>, Tahoma, Geneva, Verdana, sans-serif;
      }
      <span class="hljs-selector-class">.row</span> {
        <span class="hljs-attribute">display</span>: flex;
      }
      <span class="hljs-selector-class">.col</span> {
        <span class="hljs-attribute">height</span>: <span class="hljs-number">65px</span>;
        <span class="hljs-attribute">width</span>: <span class="hljs-number">65px</span>;
        <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid black;
        <span class="hljs-attribute">display</span>: flex;
        <span class="hljs-attribute">justify-content</span>: center;
        <span class="hljs-attribute">align-items</span>: center;
        <span class="hljs-attribute">font-size</span>: <span class="hljs-number">30px</span>;
        <span class="hljs-attribute">cursor</span>: pointer;
      }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"grid"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"2"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"3"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"4"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"5"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"row"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"6"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"7"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick(this)"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"8"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"col"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> currentPlayer = <span class="hljs-string">"X"</span>;
<span class="hljs-keyword">let</span> arr = <span class="hljs-built_in">Array</span>(<span class="hljs-number">9</span>).fill(<span class="hljs-literal">null</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkWinner</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (
    (arr[<span class="hljs-number">0</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">0</span>] == arr[<span class="hljs-number">1</span>] &amp;&amp; arr[<span class="hljs-number">1</span>] == arr[<span class="hljs-number">2</span>]) ||
    (arr[<span class="hljs-number">3</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">3</span>] == arr[<span class="hljs-number">4</span>] &amp;&amp; arr[<span class="hljs-number">4</span>] == arr[<span class="hljs-number">5</span>]) ||
    (arr[<span class="hljs-number">6</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">6</span>] == arr[<span class="hljs-number">7</span>] &amp;&amp; arr[<span class="hljs-number">7</span>] == arr[<span class="hljs-number">8</span>]) ||
    (arr[<span class="hljs-number">0</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">0</span>] == arr[<span class="hljs-number">3</span>] &amp;&amp; arr[<span class="hljs-number">3</span>] == arr[<span class="hljs-number">6</span>]) ||
    (arr[<span class="hljs-number">1</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">1</span>] == arr[<span class="hljs-number">4</span>] &amp;&amp; arr[<span class="hljs-number">4</span>] == arr[<span class="hljs-number">7</span>]) ||
    (arr[<span class="hljs-number">2</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">2</span>] == arr[<span class="hljs-number">5</span>] &amp;&amp; arr[<span class="hljs-number">5</span>] == arr[<span class="hljs-number">8</span>]) ||
    (arr[<span class="hljs-number">0</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">0</span>] == arr[<span class="hljs-number">4</span>] &amp;&amp; arr[<span class="hljs-number">4</span>] == arr[<span class="hljs-number">8</span>]) ||
    (arr[<span class="hljs-number">2</span>] !== <span class="hljs-literal">null</span> &amp;&amp; arr[<span class="hljs-number">2</span>] == arr[<span class="hljs-number">4</span>] &amp;&amp; arr[<span class="hljs-number">4</span>] == arr[<span class="hljs-number">6</span>])
  ) {
    <span class="hljs-built_in">document</span>.write(<span class="hljs-string">`Winner is <span class="hljs-subst">${currentPlayer}</span>`</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">if</span> (!arr.some(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> e === <span class="hljs-literal">null</span>)) {
    <span class="hljs-built_in">document</span>.write(<span class="hljs-string">`Draw!!`</span>);
    <span class="hljs-keyword">return</span>;
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params">el</span>) </span>{
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">Number</span>(el.id);
  <span class="hljs-keyword">if</span> (arr[id] !== <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span>;
  arr[id] = currentPlayer;
  el.innerText = currentPlayer;
  checkWinner();
  currentPlayer = currentPlayer === <span class="hljs-string">"X"</span> ? <span class="hljs-string">"O"</span> : <span class="hljs-string">"X"</span>;
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Deploying Node.js functions to AWS Lambda | Serverless]]></title><description><![CDATA[Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless.
So, let's get started.
Step 1. Create an AWS Account ☁️
In order to deploy functions to AWS Lambda, you should have a...]]></description><link>https://blog.piyushgarg.dev/deploying-nodejs-functions-to-aws-lambda-or-serverless</link><guid isPermaLink="true">https://blog.piyushgarg.dev/deploying-nodejs-functions-to-aws-lambda-or-serverless</guid><category><![CDATA[AWS]]></category><category><![CDATA[aws lambda]]></category><category><![CDATA[serverless]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sat, 21 May 2022 09:33:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1653123292617/VSBQmL5wk.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless.</p>
<p>So, let's get started.</p>
<h2 id="heading-step-1-create-an-aws-account">Step 1. Create an AWS Account ☁️</h2>
<p>In order to deploy functions to AWS Lambda, you should have an active AWS account. Creating an AWS account is really easy and straightforward. Head over to <a target="_blank" href="https://portal.aws.amazon.com/billing/signup?refid=em_127222&amp;redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start/email">Signup AWS</a> and create your free account.</p>
<p>Now, Once you have set up your AWS account, let's head over to the next step.</p>
<h2 id="heading-step-2-installations-and-setup">Step 2. Installations and Setup 🚀</h2>
<h4 id="heading-1-nodejs">1. Node.js</h4>
<p>You must have Node.js installed on your machine. If you don't have node.js installed you can do so simply by visiting <a target="_blank" href="https://nodejs.org/en/">https://nodejs.org/en/</a>.</p>
<h4 id="heading-2-aws-cli-tools">2. AWS CLI Tools</h4>
<p>Once you have installed node.js, you now need to install AWS CLI tools on your machine.
Installing AWS CLI is really easy. Below are the steps to install the same.</p>
<p>Simply copy-paste the following command on your terminal.</p>
<h5 id="heading-linux"><strong>Linux</strong></h5>
<pre><code class="lang-bash">curl <span class="hljs-string">"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip"</span> -o <span class="hljs-string">"awscliv2.zip"</span>
</code></pre>
<pre><code class="lang-bash">unzip awscliv2.zip
</code></pre>
<pre><code class="lang-bash">sudo ./aws/install
</code></pre>
<h5 id="heading-mac-os"><strong>MAC OS</strong></h5>
<pre><code class="lang-bash">curl <span class="hljs-string">"https://awscli.amazonaws.com/AWSCLIV2.pkg"</span> -o <span class="hljs-string">"AWSCLIV2.pkg"</span>
</code></pre>
<pre><code class="lang-bash">sudo installer -pkg AWSCLIV2.pkg -target /
</code></pre>
<h5 id="heading-windows"><strong>Windows</strong></h5>
<pre><code class="lang-bash">msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
</code></pre>
<p>Instructions Link: <a target="_blank" href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a></p>
<h4 id="heading-3-serverless-cli">3. Serverless CLI</h4>
<pre><code class="lang-bash">npm install -g serverless
</code></pre>
<p>Serverless Installation Instructions: <a target="_blank" href="https://www.serverless.com/framework/docs/getting-started">https://www.serverless.com/framework/docs/getting-started</a></p>
<p>Great, now that you have everything set up, Let's configure AWS credentials on our local machine.</p>
<h2 id="heading-step-3-setting-up-aws-credentials">Step 3: Setting up AWS Credentials</h2>
<p>In this step, we are going to set up AWS credentials with our AWS CLI so that our AWS CLI can communicate to our AWS account.</p>
<p>To set up AWS Account credentials, sign in to your  AWS Console and follow along with me.</p>
<ul>
<li>Click on your account name in the top right corner.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653124738703/zsLhvIvJ1.png" alt="Screenshot 2022-05-21 at 2.48.24 PM.png" /></p>
<ul>
<li>Click the "Security credentials" option.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653124848462/Nq5IN1lnC.png" alt="Screenshot 2022-05-21 at 2.50.03 PM.png" /></p>
<ul>
<li>Expand the "Access Keys" Tab.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653124905134/E95xOi9Am.png" alt="Screenshot 2022-05-21 at 2.51.24 PM.png" /></p>
<ul>
<li>Click the "Create Access Key" button.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653124968861/cnocBWicN.png" alt="Screenshot 2022-05-21 at 2.52.18 PM.png" /></p>
<ul>
<li>Copy Your Access ID and Secret.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125003203/QaNMaA_6j.png" alt="Screenshot 2022-05-21 at 2.52.57 PM.png" /></p>
<p>Now, open your terminal and run the following command</p>
<pre><code class="lang-bash">aws configure
</code></pre>
<p>Paste your Access ID and Secret here and complete the setup</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653124083126/SUpG2C8Wx.png" alt="Piyush Macbook Terminal" /></p>
<p>Great, now we are ready to code.</p>
<h2 id="heading-step-4-lets-code">Step 4: Let's Code 🧑🏻‍💻</h2>
<p>In this step, we are going to code our function and deploy it to amazon web services. Open your favourite IDE or text editor (VS code in my case) and follow me along.</p>
<p>First of all, create a new folder and open this folder in your fav text editor. I am going to name my folder <code>my-functions</code>. You can name it whatever you like.</p>
<p>Now open the terminal at the folder and run the following command:</p>
<pre><code class="lang-bash">serverless create --template aws-nodejs
</code></pre>
<p>The above command would generate some boiler plate code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653124145465/KbzP-xBzS.png" alt="Screenshot 2022-05-21 at 2.35.21 PM.png" /></p>
<p>Open the handler.js file and this is the file where are going to write our function. Feel free to remove the existing code in this file and start with a clean file.</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports.handlerFunction = <span class="hljs-keyword">async</span> (event, context) =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I am inside aws lambda function"</span>);
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">statusCode</span>: <span class="hljs-number">200</span>,
    <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Alright, It is working!"</span> }),
  };
};
</code></pre>
<p>Great, now open serverless.yml file and feel free to clear all the content from here as well.
Paste the following code in serverless.yml file.</p>
<pre><code class="lang-yaml"><span class="hljs-attr">service:</span> <span class="hljs-string">my-functions</span>
<span class="hljs-attr">frameworkVersion:</span> <span class="hljs-string">"3"</span>

<span class="hljs-attr">provider:</span>
  <span class="hljs-attr">name:</span> <span class="hljs-string">aws</span>
  <span class="hljs-attr">runtime:</span> <span class="hljs-string">nodejs12.x</span>

<span class="hljs-attr">functions:</span>
  <span class="hljs-attr">myFunction:</span>
    <span class="hljs-attr">handler:</span> <span class="hljs-string">handler.handlerFunction</span>
    <span class="hljs-attr">events:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-attr">http:</span>
          <span class="hljs-attr">path:</span> <span class="hljs-string">/api/say-hello</span>
          <span class="hljs-attr">method:</span> <span class="hljs-string">GET</span>
          <span class="hljs-attr">cors:</span> <span class="hljs-literal">true</span>
</code></pre>
<p>Great, now we are ready to deploy our function to AWS console.</p>
<h2 id="heading-step-5-deployment">Step 5. Deployment</h2>
<p>To deploy your functions to AWS console, simply open your console and paste the following command on the console.</p>
<pre><code class="lang-bash">serverless deploy
</code></pre>
<p>This will take a while and deploy your functions using the serverless.yml file to your aws console.</p>
<h2 id="heading-testing-our-implementation">Testing our Implementation</h2>
<p>Navigate to your AWS console and search for AWS Lambda
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125074556/5R8A72uj8.png" alt="Screenshot 2022-05-21 at 2.53.57 PM.png" /></p>
<p>Here I can see that my function is successfully deployed
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125099896/x3HTbdAQc.png" alt="Screenshot 2022-05-21 at 2.54.42 PM.png" /></p>
<p>This is the code that we wrote locally and deployed using serverless
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125537015/7mYe8jR_a.png" alt="Screenshot 2022-05-21 at 3.02.05 PM.png" /></p>
<p>Click on the API Gateway icon
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125253837/LHYp58CV3.png" alt="Screenshot 2022-05-21 at 2.56.25 PM.png" /></p>
<p>Here is the public endpoint URL to invoke our lambda function
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125278261/VGvjdpzin.png" alt="Screenshot 2022-05-21 at 2.56.41 PM.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1653125489885/AYkPzBCHG.png" alt="Screenshot 2022-05-21 at 3.01.24 PM.png" /></p>
]]></content:encoded></item><item><title><![CDATA[Uploading images to firebase storage with node.js]]></title><description><![CDATA[Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding.
So, let's get started.
Step...]]></description><link>https://blog.piyushgarg.dev/uploading-images-to-firebase-storage-with-nodejs</link><guid isPermaLink="true">https://blog.piyushgarg.dev/uploading-images-to-firebase-storage-with-nodejs</guid><category><![CDATA[Firebase]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Thu, 27 May 2021 09:07:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622106397168/35ZpSARSW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding.</p>
<p>So, let's get started.</p>
<h3 id="step-1-setting-up-a-free-firebase-account">Step 1: Setting up a free Firebase account.</h3>
<p>In this step, we would create a project on the firebase console. Navigate to  <a target="_blank" href="https://firebase.google.com/">https://firebase.google.com/</a> and log in with your Google account. It's absolutely free and no credit card required.
After logging in, create a project in firebase, and enter any project name of your choice, once done click on submit and wait for the project to finish building up.
Now, you would see a dashboard something like this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622102412585/HlIJ2uIG1.png" alt="Firebase | Piyush Garg" /></p>
<p>Great, now click on the setting icons and navigate to <code>project settings</code> as shown in the following image.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622102575866/swRJudCdt.png" alt="Firebase | Piyush Garg" /></p>
<p>In project settings, navigate to the <code>service accounts</code> tab to download our credentials.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622102706880/kl40tXPOV.png" alt="Firebase | Piyush Garg" /></p>
<p>In <code>service accounts</code>, click on the <code>Generate new private key</code> button to generate your key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622102831257/-8aFM6-U6.png" alt="Firebase | Piyush Garg" /></p>
<p>Now, your credentials.json would be downloaded to your machine. Copy this file to your project folder where we are now going to build the project.</p>
<h3 id="lets-code">Let's Code</h3>
<p>Great, as you have successfully set up your firebase account, now let's write some code. 
Firstly, init your project by running the following command:
<code>npm init -y</code>
Great, now install the following dependencies.</p>
<ul>
<li>firebase-admin</li>
<li>uuid<h4 id="command">Command:</h4>
<code>npm install firebase-admin uuid</code></li>
</ul>
<p>Great, now fire up your favorite code editor. (vs-code) and code along with me.</p>
<h4 id="requiring-the-dependencies">Requiring the dependencies.</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> firebaseAdmin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'firebase-admin'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">v4</span>: uuidv4 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'uuid'</span>);
</code></pre>
<h4 id="importing-our-creditionsjson-file-the-one-we-downloaded-from-firebase-dashboard">Importing our creditions.json file, the one we downloaded from firebase dashboard</h4>
<pre><code class="lang-js"><span class="hljs-comment">// change the path of json file</span>
<span class="hljs-keyword">const</span> serviceAccount = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./hashnode-dev-c6f91-firebase-adminsdk-20fsu-2d218c1c69.json'</span>);
</code></pre>
<h4 id="initializeapp">initializeApp</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> admin = firebaseAdmin.initializeApp({
    <span class="hljs-attr">credential</span>: firebaseAdmin.credential.cert(serviceAccount),
});
</code></pre>
<h4 id="create-a-storage-refrence">Create a storage refrence</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storageRef = admin.storage().bucket(<span class="hljs-string">`gs://hashnode-dev-c6f91.appspot.com`</span>);
</code></pre>
<p>.bucket() function accepts the bucket name as a parameter. To get your bucket name, open the firebase dashboard, navigate to the Storage tab, and then click on <code>Get started</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622103467820/fyljT00j3.png" alt="Firebase" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622103502267/k8aZmunvf.png" alt="Firebase" /></p>
<p>After clicking on <code>Get started</code>, firebase will ask you cloud storage location, you can go with default storage.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622103615760/ku2r-cdws.png" alt="Firebase" /></p>
<p>Now, copy the bucket name of your storage.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622103776129/2ArR-y86D.png" alt="Firebase" /></p>
<p>and then create a firebase storage refrence. (As we did earlier)</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> storageRef = admin.storage().bucket(<span class="hljs-string">`gs://hashnode-dev-c6f91.appspot.com`</span>);
</code></pre>
<h4 id="upload-files">Upload files</h4>
<p>Now, create a simple function <code>uploadFile</code> that accepts <code>filePath</code> and <code>fileName</code> as params, and uploads the file to the firebase storage.</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uploadFile</span>(<span class="hljs-params">path, filename</span>) </span>{
    <span class="hljs-keyword">return</span> storageRef.upload(path, {
        <span class="hljs-attr">public</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">destination</span>: <span class="hljs-string">`/uploads/hashnode/<span class="hljs-subst">${filename}</span>`</span>,
        <span class="hljs-attr">metadata</span>: {
            <span class="hljs-attr">firebaseStorageDownloadTokens</span>: uuidv4(),
        }
    });
}
</code></pre>
<p>Great, now let's test our function.</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span>() =&gt; {
    <span class="hljs-keyword">await</span> uploadFile(<span class="hljs-string">'./mypic.png'</span>, <span class="hljs-string">"my-image.png"</span>);
})();
</code></pre>
<p>Let's start the server: <code>node index.js</code>.</p>
<p>As you can see, my image file is successfully uploaded 🚀.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622104136067/456XUGw4y.gif" alt="Firebase-Storage" /></p>
<h3 id="creating-public-and-downloadable-urls-of-the-uploaded-files">Creating public and downloadable URLs of the uploaded files.</h3>
<p>So far, we have successfully uploaded the file to firebase storage, but we don't have a public URL that is shareable and downloadable. So, let's add some code and implement this.</p>
<h4 id="edit-rules-in-firebase-dashboard">Edit rules in firebase dashboard.</h4>
<p>In order to share the public URL, we need to change some rules in the Firebase dashboard.
In the Storage tab, navigate to the Rules tab and change the default rule to the rule pasted below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622104689400/-26ra8P9Y.png" alt="Firebase-Storage" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622104772372/oMMHnhmb1.png" alt="Firebase-Storage" /></p>
<pre><code class="lang-json">rules_version = '<span class="hljs-number">2</span>';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if <span class="hljs-literal">true</span>;
    }
  }
}
</code></pre>
<p>Great, Now inside the <code>uploadFile</code> function, Add the below code that is responsible for generating a public URL.</p>
<p>Updated <code>uploadFile</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uploadFile</span>(<span class="hljs-params">path, filename</span>) </span>{

    <span class="hljs-comment">// Upload the File</span>
    <span class="hljs-keyword">const</span> storage = <span class="hljs-keyword">await</span> storageRef.upload(path, {
        <span class="hljs-attr">public</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">destination</span>: <span class="hljs-string">`/uploads/hashnode/<span class="hljs-subst">${filename}</span>`</span>,
        <span class="hljs-attr">metadata</span>: {
            <span class="hljs-attr">firebaseStorageDownloadTokens</span>: uuidv4(),
        }
    });


    <span class="hljs-keyword">return</span> storage[<span class="hljs-number">0</span>].metadata.mediaLink;
}
</code></pre>
<p>Let's test our implementation</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span>() =&gt; {
    <span class="hljs-keyword">const</span> url = <span class="hljs-keyword">await</span> uploadFile(<span class="hljs-string">'./mypic.png'</span>, <span class="hljs-string">"my-image.png"</span>);
    <span class="hljs-built_in">console</span>.log(url);
})();
</code></pre>
<p>Run the server: <code>node index.js</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622104975686/wfL39N910.png" alt="Firebase-Storage" /></p>
<p>As you can see, I got my link to  <a target="_blank" href="https://storage.googleapis.com/download/storage/v1/b/hashnode-dev-c6f91.appspot.com/o/%2Fuploads%2Fhashnode%2Fmy-image.png?generation=1622105906245678&amp;alt=media">download the file</a>.</p>
<h3 id="complete-code">Complete Code</h3>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>
<span class="hljs-keyword">const</span> firebaseAdmin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'firebase-admin'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">v4</span>: uuidv4 } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'uuid'</span>);

<span class="hljs-keyword">const</span> serviceAccount = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./hashnode-dev-c6f91-firebase-adminsdk-20fsu-2d218c1c69.json'</span>);

<span class="hljs-keyword">const</span> admin = firebaseAdmin.initializeApp({
    <span class="hljs-attr">credential</span>: firebaseAdmin.credential.cert(serviceAccount),
});

<span class="hljs-keyword">const</span> storageRef = admin.storage().bucket(<span class="hljs-string">`gs://hashnode-dev-c6f91.appspot.com`</span>);

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">uploadFile</span>(<span class="hljs-params">path, filename</span>) </span>{

    <span class="hljs-comment">// Upload the File</span>
    <span class="hljs-keyword">const</span> storage = <span class="hljs-keyword">await</span> storageRef.upload(path, {
        <span class="hljs-attr">public</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">destination</span>: <span class="hljs-string">`/uploads/hashnode/<span class="hljs-subst">${filename}</span>`</span>,
        <span class="hljs-attr">metadata</span>: {
            <span class="hljs-attr">firebaseStorageDownloadTokens</span>: uuidv4(),
        }
    });


    <span class="hljs-keyword">return</span> storage[<span class="hljs-number">0</span>].metadata.mediaLink;
}

(<span class="hljs-keyword">async</span>() =&gt; {
    <span class="hljs-keyword">const</span> url = <span class="hljs-keyword">await</span> uploadFile(<span class="hljs-string">'./mypic.png'</span>, <span class="hljs-string">"my-image.png"</span>);
    <span class="hljs-built_in">console</span>.log(url);
})();
</code></pre>
<p>Thank you for reading. Happy Learning 🚀.</p>
]]></content:encoded></item><item><title><![CDATA[How I built a real-time collaborative IDE with video chat]]></title><description><![CDATA[Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write mark...]]></description><link>https://blog.piyushgarg.dev/how-i-built-a-real-time-collaborative-ide-with-video-chat</link><guid isPermaLink="true">https://blog.piyushgarg.dev/how-i-built-a-real-time-collaborative-ide-with-video-chat</guid><category><![CDATA[WebRTC]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Mon, 24 May 2021 10:51:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621853428061/Dtjww7bQN.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write markdowns on the given text area, people would see a real-time markdown preview of your content. Now, I made this only for my understanding of webRTC and SFU stuff. Nothing serious. But somehow I felt to share this project with you all.</p>
<h3 id="producer-side">Producer side</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621852163712/5PGrf5cHt.png" alt="Producer Screen | Piyush Garg" /></p>
<h3 id="consumer-side">Consumer side</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621852244843/2nZcy3OUZ.png" alt="Consumer screen | Piyush Garg" /></p>
<p>and it's all real-time. </p>
<h3 id="tech-stack">Tech stack</h3>
<ul>
<li>Backend: Node.js &amp; Express</li>
<li>Front-End: React.js</li>
<li>Video Confrence: WebRTC</li>
<li>Real-Time code sharing: Socket.io</li>
</ul>
<h3 id="important">Important</h3>
<p>Now, I am deciding to implement more features such as chatting, IDE with compiling options, and way more. For that I need collaborators, and If you feel like you can collaborate with me, please drop your details in the comments section.</p>
<p>Also, it's really difficult to explain and show the code of the whole project, but I would be sharing the GitHub URL of the backend code. 
Also, I would be sharing the front-end code only with my subscribers. So, If you haven't subscribed yet, please do so.</p>
<p>I would try to publish a series about this application and step by step guide so that you can also build this application. Meanwhile, you all can read the webRTC series that I have published:  <a target="_blank" href="https://piyushgarg.hashnode.dev/series/webrtc">webRTC Series by Piyush Garg</a>.</p>
<p>Code link for the project:  <a target="_blank" href="https://github.com/piyushgarg195/webrtc-collab">webRtc Collab Project</a> </p>
<h3 id="installation">Installation</h3>
<p>Open a terminal at the project's root dir and run the following commands:</p>
<ul>
<li><code>npm install</code></li>
<li><code>npm run build</code></li>
<li><code>IP=&lt;YOUR IP ADDRESS&gt; npm start</code></li>
</ul>
<p>and then open <code>http://localhost:8000/</code>.</p>
<p>Firstly, create a room with a name let's say 'a', and then again open ``http://localhost:8000/``` in some other browser or incognito tab. Now just type your room name 'a' in the join section and click join room. That's it. Try to type something on the text area where you created the room and check the result on the consumer side.</p>
<p>Happy learning 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Image processing in node.js]]></title><description><![CDATA[Hey there, In this article, we would be working on, that how you can perform various tasks such as crop, rotate, applying filters and etc. on an image.
This article would be really short and sweet, as sharp (the library we are using) is powerful and ...]]></description><link>https://blog.piyushgarg.dev/image-processing-in-nodejs</link><guid isPermaLink="true">https://blog.piyushgarg.dev/image-processing-in-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[images]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sun, 23 May 2021 13:05:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621775110650/FV8LqhPgM.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, In this article, we would be working on, that how you can perform various tasks such as crop, rotate, applying filters and etc. on an image.</p>
<p>This article would be really short and sweet, as sharp (the library we are using) is powerful and great. It does all the things under the hood, so we need to worry.</p>
<h3 id="setup">Setup</h3>
<p>Firstly, we would set up our project by installing one dependency i.e sharp. Sharp is a great library for image processing. So, install the sharp by running <code>npm install sharp</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sharp = <span class="hljs-built_in">require</span>(<span class="hljs-string">'sharp'</span>);
</code></pre>
<p>Great, now let's code.</p>
<h3 id="converting-images">Converting images</h3>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">convertImg</span>(<span class="hljs-params">img</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> sharp(img)
          .toFile(<span class="hljs-string">'output.png'</span>)
}   

convertImg(<span class="hljs-string">'/images/input.jpeg'</span>)
</code></pre>
<h3 id="resizing-quality-of-images">Resizing quality of images</h3>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">resizeBy</span>(<span class="hljs-params">img, { height, width }</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> sharp(img)
            .resize({ height, width })
            .toFile(<span class="hljs-string">'output.png'</span>)
}
</code></pre>
<h3 id="rotating-images">Rotating images</h3>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rotateImage</span>(<span class="hljs-params">img</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> sharp(img)
                .rotate()
                .resize(<span class="hljs-literal">null</span>, <span class="hljs-number">200</span>)
                .toFile(<span class="hljs-string">'output.png'</span>)
}
</code></pre>
<h3 id="and-you-can-even-do-tons-and-tons-more-manipulation-with-sharp">and you can even do tons &amp; tons more manipulation with sharp.</h3>
]]></content:encoded></item><item><title><![CDATA[Build Instagram bot with node.js]]></title><description><![CDATA[Hey reader, In this article, we would be building an Instagram bot that is capable of doing various things such as automatic uploading, commenting, accepting follow requests, and much more.
Note: The best part of this article is at the last, so, plea...]]></description><link>https://blog.piyushgarg.dev/build-instagram-bot-with-nodejs</link><guid isPermaLink="true">https://blog.piyushgarg.dev/build-instagram-bot-with-nodejs</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[instagram]]></category><category><![CDATA[Express]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sat, 22 May 2021 09:03:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621674301309/nlfhgmNG4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey reader, In this article, we would be building an Instagram bot that is capable of doing various things such as automatic uploading, commenting, accepting follow requests, and much more.</p>
<p>Note: The best part of this article is at the last, so, please read this article till the end. 🙂</p>
<p>Building an Instagram bot with node.js is really easy. All you need is an Instagram account and node.js installed on your machine.</p>
<p>So, let's get started.</p>
<h3 id="setup-project">Setup project</h3>
<p>Firstly, create an empty project and run <code>npm init -y</code> command to create <code>package.json</code> file. After that install <code>instagram-web-api</code> package to get started. 
<code>npm install instagram-web-api</code></p>
<p>Great, now open your fav editor and code along with me.</p>
<h3 id="login-to-instagram">Login to instagram</h3>
<p>In this step, we would create an Instagram client and authenticate via username and password.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Instagram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'instagram-web-api'</span>);

<span class="hljs-keyword">let</span> username = <span class="hljs-string">'&lt;YOUR_USERNAME&gt;'</span>;
<span class="hljs-keyword">let</span> password = <span class="hljs-string">'&lt;YOUR_PASSWORD&gt;'</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> Instagram({ username, password });

(<span class="hljs-keyword">async</span>() =&gt; {
    <span class="hljs-keyword">await</span> client.login();
    <span class="hljs-keyword">const</span> profile = <span class="hljs-keyword">await</span> client.getProfile();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'profile'</span>);
})()
</code></pre>
<p>Now, Let's play around with the API</p>
<h3 id="upload-photos-to-your-instagram-account">Upload photos to your Instagram account</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> uploadPhoto = <span class="hljs-keyword">async</span> (photoUrl) =&gt; {
    <span class="hljs-keyword">const</span> { media } = <span class="hljs-keyword">await</span> client.uploadPhoto({ <span class="hljs-attr">photo</span>: photoUrl });
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Pic uploaded!!`</span>);
}

uploadPhoto(<span class="hljs-string">'https://example.com/cat.png'</span>)
</code></pre>
<h3 id="change-your-display-picture">Change your display picture</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> changeMyDp = <span class="hljs-keyword">async</span> (photoPath) =&gt; {
    <span class="hljs-keyword">await</span> client.changeProfilePhoto({ <span class="hljs-attr">photo</span>: photoPath });
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'DP changed!!'</span>);
}
</code></pre>
<h3 id="update-instagram-profile">Update Instagram profile</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> updateProfile = <span class="hljs-keyword">async</span> (data) =&gt; {
    <span class="hljs-keyword">await</span> client.updateProfile(data);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Profile updated'</span>)
}

updateProfile({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Piyush'</span>, <span class="hljs-attr">username</span>: <span class="hljs-string">'piyushgargdev'</span>, <span class="hljs-attr">bio</span>: <span class="hljs-string">'piyushgarg.hashnode.dev'</span> });
</code></pre>
<p>Okay, I hope that now you are pretty much familiar with API, now let's build a bot that runs at a specific time and likes, comments on the posts based on hashtags.</p>
<h3 id="instagram-bot">Instagram BOT</h3>
<p>To get started, go and install <code>node-cron</code>. This enables us to schedule tasks on a specific time.
<code>npm install node-cron</code>.</p>
<p>Now, I am going to firstly build a function that fetches posts by hashtags, then I would loop over posts and like them.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> likePostsByHashTag = <span class="hljs-keyword">async</span> (hashtag) =&gt; {
    <span class="hljs-keyword">const</span> LIMIT = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">const</span> feed = <span class="hljs-keyword">await</span> client.getMediaFeedByHashtag({ hashtag });
    <span class="hljs-keyword">const</span> posts = feed.edge_hashtag_to_media.edges;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; LIMIT; i++) {
        <span class="hljs-keyword">const</span> mediaId = posts[i].node.id

        <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-keyword">await</span> client.like({ <span class="hljs-attr">mediaId</span>:  mediaId}); <span class="hljs-comment">// let each like has a gap of 4 seconds</span>
        }, <span class="hljs-number">4000</span>);

    }
}
</code></pre>
<p>Cool, now let's work with <code>node-cron</code> and schedule our posts in such a way that one post is uploaded every day at 12:00am.</p>
<h4 id="import-node-cron">Import node-cron</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cron = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node-cron'</span>);
</code></pre>
<h4 id="create-post-array-that-you-want-to-schedule">Create post array that you want to schedule</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> posts = [
    <span class="hljs-string">'https://expample.com/pic1.png'</span>,
    <span class="hljs-string">'https://expample.com/pic2.png'</span>,
    <span class="hljs-string">'https://expample.com/pic3.png'</span>,
    <span class="hljs-string">'https://expample.com/pic4.png'</span>,
    <span class="hljs-string">'https://expample.com/pic5.png'</span>,
]
</code></pre>
<h4 id="define-current-variable-to-keep-track-of-current-post">Define current variable to keep track of current post.</h4>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> current = <span class="hljs-number">0</span>;
</code></pre>
<h4 id="define-a-function-that-uploads-the-photo-to-instagram">Define a function that uploads the photo to Instagram</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> uploadPhoto = <span class="hljs-keyword">async</span> (photoUrl, caption) =&gt; {
    <span class="hljs-keyword">const</span> { media } = <span class="hljs-keyword">await</span> client.uploadPhoto({ <span class="hljs-attr">photo</span>: photoUrl, caption });
    current++;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Pic uploaded!!`</span>);
}
</code></pre>
<h4 id="finally-lets-schedule-them-with-node-cron">Finally, let's schedule them with node-cron</h4>
<pre><code class="lang-js"><span class="hljs-comment">// 0 0 0 * * ? - means everyday at 12:00am </span>
<span class="hljs-comment">// Read more about these expression at https://www.npmjs.com/package/node-cron</span>

cron.schedule(<span class="hljs-string">'0 0 0 * * ?'</span>, <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">await</span> uploadPhoto(posts[current], <span class="hljs-string">'Great! Its posted automatically!'</span>);
});
</code></pre>
<p>Done 🙂</p>
]]></content:encoded></item><item><title><![CDATA[Building one to many video conference application]]></title><description><![CDATA[Hey there, in this article we would be building a one-to-many video-conferencing application. We would be using SFU architecture to implement this.
To read more about webRTC architectures, visit  Different WebRTC Architectures 
Note: This article is ...]]></description><link>https://blog.piyushgarg.dev/building-one-to-many-video-conference-application</link><guid isPermaLink="true">https://blog.piyushgarg.dev/building-one-to-many-video-conference-application</guid><category><![CDATA[WebRTC]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Fri, 21 May 2021 12:37:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621600544933/rzfKAL211.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, in this article we would be building a one-to-many video-conferencing application. We would be using SFU architecture to implement this.</p>
<p>To read more about webRTC architectures, visit  <a target="_blank" href="https://www.callstats.io/blog/webrtc-architectures-explained-in-5-minutes-or-less">Different WebRTC Architectures</a> </p>
<p>Note: This article is a part of the  <a target="_blank" href="https://piyushgarg.hashnode.dev/series/webrtc">WebRTC Series</a>, if you haven't read previous articles, please read them before this one.</p>
<p>Let's begin</p>
<h2 id="setting-up-the-server">Setting up the server</h2>
<p>Firstly, set up a basic express server.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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

app.use(express.json());
app.use(express.static(<span class="hljs-string">'./public'</span>))

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server started!!'</span>))
</code></pre>
<p>Install wrtc by running
<code>npm install wrtc</code> and import the library.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> wrtc = <span class="hljs-built_in">require</span>(<span class="hljs-string">'wrtc'</span>);
</code></pre>
<p>Now, start by creating a <code>/broadcast</code> route for the broadcaster.</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/broadcast'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> { sdp } = req.body;
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> wrtc.RTCPeerConnection();
    peer.ontrack = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> handleTrackEvent(e, peer);
    <span class="hljs-keyword">const</span> desc = <span class="hljs-keyword">new</span> wrtc.RTCSessionDescription(sdp)
    <span class="hljs-keyword">await</span> peer.setRemoteDescription(desc);
    <span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> peer.createAnswer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(answer);
    res.json({
        <span class="hljs-attr">sdp</span>: peer.localDescription
    })
});
</code></pre>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleTrackEvent</span>(<span class="hljs-params">e, peer</span>) </span>{
    <span class="hljs-built_in">console</span>.log(e.streams[<span class="hljs-number">0</span>])
    senderStream = e.streams[<span class="hljs-number">0</span>]; <span class="hljs-comment">// create a global variable senderStream</span>
}
</code></pre>
<p>This is the route where we would first create an offer on the client-side and then create a peer-to-peer connection with our server (just like we used to do with other clients in previous tutorials).</p>
<p>and now, let's create a route for consumers where we would make a peer-to-peer connection with our clients and share the senderStream with them.</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/consumer'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> { sdp } = req.body;
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> wrtc.RTCPeerConnection();
    <span class="hljs-keyword">const</span> desc = <span class="hljs-keyword">new</span> wrtc.RTCSessionDescription(sdp)
    <span class="hljs-keyword">await</span> peer.setRemoteDescription(desc);
    senderStream.getTracks().forEach(<span class="hljs-function"><span class="hljs-params">track</span> =&gt;</span> peer.addTrack(track, senderStream));
    <span class="hljs-keyword">const</span> ans = <span class="hljs-keyword">await</span> peer.createAnswer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(ans);
    res.json({
        <span class="hljs-attr">sdp</span>: peer.localDescription
    })
});
</code></pre>
<p>Great. Now create two files in your public folder:</p>
<ol>
<li><code>broadcast.html</code> - For the broadcaster</li>
<li><code>consumer.html</code> - For the consumer</li>
</ol>
<h3 id="broadcast">Broadcast</h3>
<p>Inside your <code>broadcast.html</code> you need to implement the following steps in sequence</p>
<ol>
<li>Get the user's media stream and set it to the video tag's srcObject.</li>
<li>Create a peer object for the broadcaster.</li>
<li>Create a local offer and send the offer to the <code>/broadcast</code> route.</li>
<li>Finally add your media stream to the peer (backend server).</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({ <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span> });
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'my-video'</span>).srcObject = stream;
    <span class="hljs-keyword">const</span> peer = createPeer();
    stream.getTracks().forEach(<span class="hljs-function"><span class="hljs-params">track</span> =&gt;</span> peer.addTrack(track, stream));
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPeer</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection();
    peer.onnegotiationneeded = <span class="hljs-function">() =&gt;</span> handleonnegotiationneeded(peer);
    <span class="hljs-keyword">return</span> peer;
}

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{RTCPeerConnection}</span> <span class="hljs-variable">peer</span></span>
*/</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleonnegotiationneeded</span>(<span class="hljs-params">peer</span>) </span>{
    <span class="hljs-keyword">const</span> offer = <span class="hljs-keyword">await</span> peer.createOffer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(offer);
    <span class="hljs-keyword">const</span> payload = {
        <span class="hljs-attr">sdp</span>: peer.localDescription
    }
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span>(<span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/broadcast'</span>, { 
        <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
        },
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(payload),
    })).json();

    peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(response.sdp));
}

init();
</code></pre>
<p>Great!</p>
<h2 id="consume">Consume</h2>
<p>Inside <code>consume.html</code> you have to do pretty much the same things, the only difference is that instead of sending streams, you have to listen on incoming streams.</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> peer = createPeer();
    peer.addTransceiver(<span class="hljs-string">'video'</span>, { <span class="hljs-attr">direction</span>: <span class="hljs-string">'recvonly'</span> })
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPeer</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection();
    peer.ontrack = handleTrack;
    peer.onnegotiationneeded = <span class="hljs-function">() =&gt;</span> handleonnegotiationneeded(peer);
    <span class="hljs-keyword">return</span> peer;
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleTrack</span>(<span class="hljs-params">ev</span>) </span>{
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'remote'</span>).srcObject = ev.streams[<span class="hljs-number">0</span>];
}

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{RTCPeerConnection}</span> <span class="hljs-variable">peer</span></span>
*/</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleonnegotiationneeded</span>(<span class="hljs-params">peer</span>) </span>{
    <span class="hljs-keyword">const</span> offer = <span class="hljs-keyword">await</span> peer.createOffer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(offer);
    <span class="hljs-keyword">const</span> payload = {
        <span class="hljs-attr">sdp</span>: peer.localDescription
    }
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span>(<span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/consumer'</span>, { 
        <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
        },
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(payload),
    })).json();

    peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(response.sdp));
}

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, init);
</code></pre>
<p>And that's it. It was that easy. Now start your server and open <code>http://localhost:9000/broadcast.html</code> and broadcast yourself. Then open several other tabs at <code>http://localhost:9000/consume.html</code> and you would be seeing the broadcaster's video.</p>
<p>Complete code:
<strong><em> Server.js </em></strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> wrtc = <span class="hljs-built_in">require</span>(<span class="hljs-string">'wrtc'</span>);
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-keyword">let</span> senderStream;;

app.use(express.json());
app.use(express.static(<span class="hljs-string">'./public'</span>))

app.post(<span class="hljs-string">'/broadcast'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> { sdp } = req.body;
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> wrtc.RTCPeerConnection();
    peer.ontrack = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> handleTrackEvent(e, peer);
    <span class="hljs-keyword">const</span> desc = <span class="hljs-keyword">new</span> wrtc.RTCSessionDescription(sdp)
    <span class="hljs-keyword">await</span> peer.setRemoteDescription(desc);
    <span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> peer.createAnswer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(answer);
    res.json({
        <span class="hljs-attr">sdp</span>: peer.localDescription
    })
});

app.post(<span class="hljs-string">'/consumer'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
    <span class="hljs-keyword">const</span> { sdp } = req.body;
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> wrtc.RTCPeerConnection();
    <span class="hljs-keyword">const</span> desc = <span class="hljs-keyword">new</span> wrtc.RTCSessionDescription(sdp)
    <span class="hljs-keyword">await</span> peer.setRemoteDescription(desc);
    senderStream.getTracks().forEach(<span class="hljs-function"><span class="hljs-params">track</span> =&gt;</span> peer.addTrack(track, senderStream));
    <span class="hljs-keyword">const</span> ans = <span class="hljs-keyword">await</span> peer.createAnswer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(ans);
    res.json({
        <span class="hljs-attr">sdp</span>: peer.localDescription
    })
});

<span class="hljs-comment">/**
 * 
 * @param {RTCTrackEvent} e 
 * @param {RTCPeerConnection} peer 
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleTrackEvent</span>(<span class="hljs-params">e, peer</span>) </span>{
    <span class="hljs-built_in">console</span>.log(e.streams[<span class="hljs-number">0</span>])
    senderStream = e.streams[<span class="hljs-number">0</span>];
}

app.listen(<span class="hljs-number">9000</span>)
</code></pre>
<p><strong><em> broadcast.html </em></strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"my-video"</span> <span class="hljs-attr">autoplay</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({ <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span> });
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'my-video'</span>).srcObject = stream;
    <span class="hljs-keyword">const</span> peer = createPeer();
    stream.getTracks().forEach(<span class="hljs-function"><span class="hljs-params">track</span> =&gt;</span> peer.addTrack(track, stream));
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPeer</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection();
    peer.onnegotiationneeded = <span class="hljs-function">() =&gt;</span> handleonnegotiationneeded(peer);
    <span class="hljs-keyword">return</span> peer;
}

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{RTCPeerConnection}</span> <span class="hljs-variable">peer</span></span>
*/</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleonnegotiationneeded</span>(<span class="hljs-params">peer</span>) </span>{
    <span class="hljs-keyword">const</span> offer = <span class="hljs-keyword">await</span> peer.createOffer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(offer);
    <span class="hljs-keyword">const</span> payload = {
        <span class="hljs-attr">sdp</span>: peer.localDescription
    }
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span>(<span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/broadcast'</span>, { 
        <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
        },
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(payload),
    })).json();

    peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(response.sdp));
}

init();

    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong><em> consume.html </em></strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"remote"</span> <span class="hljs-attr">autoplay</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> peer = createPeer();
    peer.addTransceiver(<span class="hljs-string">'video'</span>, { <span class="hljs-attr">direction</span>: <span class="hljs-string">'recvonly'</span> })
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPeer</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection();
    peer.ontrack = handleTrack;
    peer.onnegotiationneeded = <span class="hljs-function">() =&gt;</span> handleonnegotiationneeded(peer);
    <span class="hljs-keyword">return</span> peer;
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleTrack</span>(<span class="hljs-params">ev</span>) </span>{
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'remote'</span>).srcObject = ev.streams[<span class="hljs-number">0</span>];
}

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@param <span class="hljs-type">{RTCPeerConnection}</span> <span class="hljs-variable">peer</span></span>
*/</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleonnegotiationneeded</span>(<span class="hljs-params">peer</span>) </span>{
    <span class="hljs-keyword">const</span> offer = <span class="hljs-keyword">await</span> peer.createOffer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(offer);
    <span class="hljs-keyword">const</span> payload = {
        <span class="hljs-attr">sdp</span>: peer.localDescription
    }
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span>(<span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/consumer'</span>, { 
        <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
        <span class="hljs-attr">headers</span>: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
        },
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(payload),
    })).json();

    peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(response.sdp));
}

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, init);

    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How to build a file transfer application with node and webRTC]]></title><description><![CDATA[Hello there, In this article, we would be building a file transfer application using webRTC and node.js. This app would let users transfer heavy files to each other without the need for a server. 
Note, in order to proceed with the tutorial, I would ...]]></description><link>https://blog.piyushgarg.dev/how-to-build-a-file-transfer-application-with-node-and-webrtc</link><guid isPermaLink="true">https://blog.piyushgarg.dev/how-to-build-a-file-transfer-application-with-node-and-webrtc</guid><category><![CDATA[Node.js]]></category><category><![CDATA[WebRTC]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[Express]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Thu, 20 May 2021 10:40:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621507179444/ZVpTr_-MR.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello there, In this article, we would be building a file transfer application using webRTC and node.js. This app would let users transfer heavy files to each other without the need for a server. </p>
<p>Note, in order to proceed with the tutorial, I would highly recommend you to please read my previous tutorial on webRTC  <a target="_blank" href="https://piyushgarg.hashnode.dev/build-video-chat-application-with-webrtc">Build a video chat app with webRTC</a>.</p>
<p>Alright, let's begin.</p>
<h2 id="heading-setting-up-the-server-for-signaling">Setting up the server for signaling.</h2>
<p>In this very step, we are going to set up a simple signaling server using node and socket.io. I won't be explaining the signaling process as I have already that in <a target="_blank" href="https://piyushgarg.hashnode.dev/build-video-chat-application-with-webrtc">Build a video chat app with webRTC</a> article. If you haven't read that, please go and read.</p>
<pre><code class="lang-js"><span class="hljs-comment">// signaling server</span>

<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">Server</span>: SocketIO } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);

<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> server = http.createServer(app);
<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> SocketIO(server, { <span class="hljs-attr">cors</span>: <span class="hljs-literal">true</span> });

<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

app.use(express.static(<span class="hljs-string">'./public'</span>));

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {

    socket.emit(<span class="hljs-string">'me'</span>, socket.id);

    socket.on(<span class="hljs-string">'make:offer'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> { offer, to } = data;
        socket.to(to).emit(<span class="hljs-string">'incomming:offer'</span>, { offer, <span class="hljs-attr">from</span>: socket.id });
    });

    socket.on(<span class="hljs-string">'make:answer'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> { answer, to } = data;
        socket.to(to).emit(<span class="hljs-string">'incomming:answer'</span>, { answer, <span class="hljs-attr">from</span>: socket.id });
    });
});

server.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`🚀 Server started at PORT<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>Very basic, no rocket science. I hope that the above code is clear to you.</p>
<h3 id="heading-great-now-lets-move-further-to-our-front-end-part">Great, now let's move further to our front-end part.</h3>
<p>Let's start with a basic boiler plate code</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"my-id"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"connect"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"id"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>SEND<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"file-transfer"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>SEND<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/socket.io/socket.io.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Pretty simple.</p>
<p>Now let's define some global variables.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'file-transfer'</span>);
<span class="hljs-keyword">const</span> connectForm = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'connect'</span>);

<span class="hljs-keyword">const</span> socket = io();
<span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection();
<span class="hljs-keyword">let</span> dataChannel;
</code></pre>
<p>Alright, good going 🚀</p>
<p>Now let's add some event listeners to our form and socket.</p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'me'</span>, <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'my-id'</span>).innerText = id); <span class="hljs-comment">// to get our own socket id.</span>

form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-keyword">async</span> (ev) =&gt; {
    ev.preventDefault();
});

connectForm.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-keyword">async</span> (ev) =&gt; {
    ev.preventDefault();
});
</code></pre>
<h3 id="heading-alright-now-lets-focus-on-our-connection-process">Alright, now let's focus on our connection process.</h3>
<p>So, what we would be doing is, when a user submits the connection form, we are going to init the signaling process and connect both the peers.</p>
<pre><code class="lang-js">connectForm.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-keyword">async</span> (ev) =&gt; {
    ev.preventDefault();
    <span class="hljs-keyword">const</span> remoteId = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'id'</span>).value;

    <span class="hljs-keyword">const</span> offer = <span class="hljs-keyword">await</span> peer.createOffer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));

    <span class="hljs-comment">// This dataChanel we are going to use to send data</span>
    dataChannel = peer.createDataChannel(<span class="hljs-string">'file-transfer'</span>);
    socket.emit(<span class="hljs-string">'make:offer'</span>, { offer, <span class="hljs-attr">to</span>: remoteId });
});
</code></pre>
<p>and now, create an event listener for the incoming offer</p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'incomming:offer'</span>, <span class="hljs-keyword">async</span> data =&gt; {
    <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(data.offer));
    <span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> peer.createAnswer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(answer));
    socket.emit(<span class="hljs-string">'make:answer'</span>, { answer, <span class="hljs-attr">to</span>: data.from })

    <span class="hljs-comment">// Init the remote datachannel as soon as the first peer creates a data channel</span>
    peer.addEventListener(<span class="hljs-string">'datachannel'</span>, <span class="hljs-function"><span class="hljs-params">ev</span> =&gt;</span> {
        dataChannel = ev.channel
        dataChannel.send(<span class="hljs-string">'Hello Peer'</span>);
    });
})
</code></pre>
<p>and finally, the incoming answer</p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'incomming:answer'</span>, <span class="hljs-keyword">async</span> data =&gt; {
    <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(data.answer));
})
</code></pre>
<h3 id="heading-now-lets-complete-our-file-transfer-form-listener-where-are-actually-going-to-transfer-the-files">Now let's complete our file transfer form listener where are actually going to transfer the files.</h3>
<pre><code class="lang-js">form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-keyword">async</span> (ev) =&gt; {
    ev.preventDefault();

    <span class="hljs-comment">// Get the file from input field.</span>
    <span class="hljs-keyword">const</span> file = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'file'</span>).files[<span class="hljs-number">0</span>];
    <span class="hljs-comment">// convert the file to buffer</span>
    <span class="hljs-keyword">const</span> fileBuffer = <span class="hljs-keyword">await</span> file.arrayBuffer();

    <span class="hljs-comment">// finally, send it to the peer data channel</span>
    dataChannel.send(fileBuffer);
});
</code></pre>
<p>Great, so on the receiver side, listen for this file and download the file to the client.</p>
<pre><code class="lang-js">connectForm.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-keyword">async</span> (ev) =&gt; {
    ev.preventDefault();
    <span class="hljs-keyword">const</span> remoteId = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'id'</span>).value;

    <span class="hljs-keyword">const</span> offer = <span class="hljs-keyword">await</span> peer.createOffer();
    <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));

    <span class="hljs-comment">// This dataChanel we are going to use to send data</span>
    dataChannel = peer.createDataChannel(<span class="hljs-string">'file-transfer'</span>);
    socket.emit(<span class="hljs-string">'make:offer'</span>, { offer, <span class="hljs-attr">to</span>: id });

    <span class="hljs-comment">// Adding a message listener</span>
    dataChannel.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function"><span class="hljs-params">ev</span> =&gt;</span> {

        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> ev.data == <span class="hljs-string">'object'</span>) {
            <span class="hljs-keyword">const</span> a = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'a'</span>);
            <span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> Blob([ev.data]);
            <span class="hljs-keyword">const</span> obj = URL.createObjectURL(blob);
            a.href = obj;
            a.download = <span class="hljs-string">'rec.png'</span>;
            a.click()
        }     
    });
});
</code></pre>
<p>And that's it, the file would get downloaded to the client's machine.</p>
]]></content:encoded></item><item><title><![CDATA[Build a screen share application like zoom and google meet]]></title><description><![CDATA[Hello there, In this article, I would be showing you how you can make a web application that allows you to share your screen with other people.
Now, very important note, in order to create this application you need to understand WebRTC and this tutor...]]></description><link>https://blog.piyushgarg.dev/build-a-screen-share-application-like-zoom-and-google-meet</link><guid isPermaLink="true">https://blog.piyushgarg.dev/build-a-screen-share-application-like-zoom-and-google-meet</guid><category><![CDATA[Node.js]]></category><category><![CDATA[WebRTC]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[Express]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Wed, 19 May 2021 11:43:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621424567433/1vDVBh5mE.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello there, In this article, I would be showing you how you can make a web application that allows you to share your screen with other people.</p>
<p>Now, very important note, in order to create this application you need to understand WebRTC and this tutorial is an extended to my previous article in which I had thought about how to build a video call application using webRTC. If you have already read that article you are ready to go. If not, please go and read that first. </p>
<p> Link: <a target="_blank" href="https://piyushgarg.hashnode.dev/build-video-chat-application-with-webrtc">Build video call application with webRTC</a> </p>
<p>Let's begin</p>
<p>Okay, trust me, this is going to be a very short and easy tutorial. You need to add few lines to our video call application that we build here-&gt; <a target="_blank" href="https://piyushgarg.hashnode.dev/build-video-chat-application-with-webrtc">Build video call application with webRTC</a> </p>
<p>Just add the following code and boom! now you are able to share your screen as well, along with video.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getUserMedia = <span class="hljs-keyword">async</span> () =&gt; {

          <span class="hljs-keyword">const</span> userMedia = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
              <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>
          });

          <span class="hljs-comment">// Capture the screen stream</span>
          <span class="hljs-keyword">const</span> screenSteam = <span class="hljs-keyword">await</span> navigator.mediaDevices.getDisplayMedia();

          <span class="hljs-keyword">const</span> videoEle = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'local-video'</span>);
          videoEle.srcObject = userMedia;
          videoEle.play()

          <span class="hljs-comment">// This is our webcam stream</span>
          <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> track <span class="hljs-keyword">of</span> userMedia.getTracks()) {
                  peer.addTrack(track, userMedia)
          }

          <span class="hljs-comment">// Finally add the screen stream to peer</span>
          <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> track <span class="hljs-keyword">of</span> screenSteam.getTracks()){
                  peer.addTrack(track, userMedia)
          }
 }
</code></pre>
<p>Okay, there is a task for you, we made a <code>`peer.ontrack</code> event listener which receives an array of streams. You have to loop over these streams and render multiple video tags dynamically and add the stream to the video's srcObject. Good luck 🙂</p>
<p><strong><em> Hint </em></strong>
In <code>peer.ontrack</code> method, we can get video and audio tracks:</p>
<pre><code class="lang-js">peer.ontrack = <span class="hljs-keyword">async</span>(ev) =&gt; {
    ev.streams[<span class="hljs-number">0</span>].getAudioTracks(); <span class="hljs-comment">// Returns all the audio tracks</span>
    ev.streams[<span class="hljs-number">0</span>].getVideoTracks(); <span class="hljs-comment">// Returns all the audio tracks</span>
}
</code></pre>
<p>Just in case, you want me to make a full tutorial on this, do leave a comment.</p>
<p>Happy learning</p>
]]></content:encoded></item><item><title><![CDATA[Build video chat application with WebRTC]]></title><description><![CDATA[Hey reader, welcome back to my blog, in this article we would be building a real-time video calling application using something known as WebRTC.
Now, what is webRTC? In simple terms, webRTC refers to as web real-time communications. You can use webRT...]]></description><link>https://blog.piyushgarg.dev/build-video-chat-application-with-webrtc</link><guid isPermaLink="true">https://blog.piyushgarg.dev/build-video-chat-application-with-webrtc</guid><category><![CDATA[WebRTC]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Tue, 18 May 2021 10:08:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621513211697/UdC6mSrVo.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey reader, welcome back to my blog, in this article we would be building a real-time video calling application using something known as WebRTC.</p>
<p>Now, what is webRTC? In simple terms, webRTC refers to as <strong>web real-time communications</strong>. You can use webRTC to design video calling, audio calling, and chatting applications on the web.</p>
<p>Do you know what's the best part about WebRTC? The answer is, you don't need any backend to handle the communications. This means that two or more people are having video calls without any server, how? because WebRTC is implemented inside your browser. Isn't interesting? So, let's build our own video call application.</p>
<p>Note: As I have mentioned we don't need any backend, that does not mean that we are not going to have any type of backend. We need a backend at an initial point just to connect them both initially. after that, you can even stop your server but the video call would go on. I hope you got the point.</p>
<h2 id="heading-technologies-we-would-be-using">Technologies we would be using</h2>
<ol>
<li>Node.js &amp; Express</li>
<li>Socket.io</li>
<li>A good browser (Chrome, Firefox)</li>
</ol>
<h2 id="heading-setup">Setup</h2>
<p>Let's begin to set up our project. Create an empty folder naming video-app and initialize package.json by running <code>npm init -y</code>.</p>
<p>Now, let's install express and socket.io by running </p>
<p><code>npm install express socket.io</code></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"video-call"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A simple video calling application"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node index.js"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Piyush Garg"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.17.1"</span>,
    <span class="hljs-attr">"socket.io"</span>: <span class="hljs-string">"^4.1.2"</span>
  }
}
</code></pre>
<p>don't forget to add the <code>start</code> script in package.json.</p>
<p>Good going, now let's create a <code>index.js</code> file on the server and start coding along with me.</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">Server</span>: SocketIO } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

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

<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> SocketIO(server);
<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

app.use(express.static( path.resolve(<span class="hljs-string">'./public'</span>) ));

server.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>let's try to run our server with <code>npm start</code>.</p>
<pre><code class="lang-bash">Server started at PORT:8000
</code></pre>
<p>Cool 😎</p>
<p>Now let's start adding event listeners to our socket.io</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">Server</span>: SocketIO } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

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

<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> SocketIO(server);
<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user connected: <span class="hljs-subst">${socket.id}</span>`</span>);


    socket.on(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user disconnected: <span class="hljs-subst">${socket.id}</span>`</span>);
    });
});


app.use(express.static( path.resolve(<span class="hljs-string">'./public'</span>) ));

server.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>Okay, you are really fast at learning. Now create a folder named public on your server and create a <code>index.html</code> file. This is the file where all our front-end code goes.</p>
<pre><code>node_modules<span class="hljs-operator">/</span>
<span class="hljs-keyword">public</span>
     <span class="hljs-operator">|</span> index.html
index.js
package<span class="hljs-operator">-</span>lock.json
package.json
</code></pre><p><code>index.html</code></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>My Video App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Now, things become a little serious, before moving further I want you to understand some basic terms</p>
<ol>
<li>RTCPeerConnection –  creates and navigates peer-to-peer connections.</li>
<li>RTCSessionDescription – describes one end of a connection (or a potential connection) and how it’s configured.</li>
</ol>
<p>What is a peer? A peer is a node or a user connected to webRTC. </p>
<h2 id="heading-flow-of-webrtc">Flow of WebRTC</h2>
<p>The flow of webRTC is simple, yet confusing. Once you understand this flow, whoa you know webRTC. I don't expect that you would understand this in one go, so please read this topic 2-3 times.</p>
<p>To understand the flow of WebRTC, let's take the real-life situations on how it works.</p>
<p>There are 2 online users named A and B. A wants to call B, so first of all A would <code>create an offer</code> and send it to B via <code>socket.io</code>. B would then accept the offer sent by A and after accepting the offer, B will <code>create an answer</code>  and send back the answer to A via <code>socket.io</code>. This process is called <strong> signaling </strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621325173448/1UhfFmhAH.png" alt="SOCKETIO WEBRTC.png" /></p>
<p>Did you understand that? If not, please read that again slowly. If yes, please read that carefully.</p>
<h4 id="heading-now-lets-code-the-above-situation-to-make-things-more-sensual">Now, let's code the above situation to make things more sensual.</h4>
<p><strong><em> On the server <code>index.js</code> </em></strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// create a users map to keep track of users</span>
<span class="hljs-keyword">const</span> users = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
</code></pre>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'outgoing:call'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
     <span class="hljs-keyword">const</span> { fromOffer, to } = data;
     socket.to(to).emit(<span class="hljs-string">'incomming:call'</span>, { <span class="hljs-attr">from</span>: socket.id, <span class="hljs-attr">offer</span>: fromOffer });
});
</code></pre>
<p>In the above code sample, <code>to</code> refers to the id of B.</p>
<p>So, basically in the above implementation, whenever a client emits an outgoing call event to someone our server would emit the incoming call event for the client who is being called along with the offer. I hope it makes sense to you.</p>
<p>Now, let's code when B accepts the call and sends back the answer to the server.</p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'call:accepted'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
     <span class="hljs-keyword">const</span> { answere, to } = data;
     socket.to(to).emit(<span class="hljs-string">'incomming:answere'</span>, { <span class="hljs-attr">from</span>: socket.id, <span class="hljs-attr">offer</span>: answere })
});
</code></pre>
<p>In this case, <code>to</code> refers to the id of A.</p>
<p>Complete <code>index.js</code> code.</p>
<pre><code class="lang-js">
<span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">Server</span>: SocketIO } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

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

<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> SocketIO(server);
<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

<span class="hljs-comment">// Create a users map to keep track of users</span>
<span class="hljs-keyword">const</span> users = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user connected: <span class="hljs-subst">${socket.id}</span>`</span>);
    users.set(socket.id, socket.id);

    <span class="hljs-comment">// emit that a new user has joined as soon as someone joins</span>
    socket.emit(<span class="hljs-string">'user:joined'</span>, socket.id);

    socket.on(<span class="hljs-string">'outgoing:call'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> { fromOffer, to } = data;

        socket.to(to).emit(<span class="hljs-string">'incomming:call'</span>, { <span class="hljs-attr">from</span>: socket.id, <span class="hljs-attr">offer</span>: fromOffer });
    });

    socket.on(<span class="hljs-string">'call:accepted'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> { answere, to } = data;
        socket.to(to).emit(<span class="hljs-string">'incomming:call'</span>, { <span class="hljs-attr">from</span>: socket.id, <span class="hljs-attr">offer</span>: answere })
    });


    socket.on(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user disconnected: <span class="hljs-subst">${socket.id}</span>`</span>);
        users.delete(socket.id);
    });
});


app.use(express.static( path.resolve(<span class="hljs-string">'./public'</span>) ));

server.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>Good job, lets move further and code our front-end part where we would be creating and accepting these offers.</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- Import socket.io script --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/socket.io/socket.io.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Complete html code</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>My Video App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Your Id: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myId"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Online Users (click to connect)<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"users"</span>&gt;</span>

                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"local-video"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"remote-video"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"status"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-comment">&lt;!-- Import socket.io script --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/socket.io/socket.io.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
            <span class="hljs-keyword">const</span> socket = io();
        </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>also, add the following CSS styles</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-family</span>: Arial, Helvetica, sans-serif;
}

<span class="hljs-selector-tag">button</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid;
    <span class="hljs-attribute">cursor</span>: pointer;
    <span class="hljs-attribute">display</span>: block;
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-id">#local-video</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid green;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">250px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">250px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">right</span>: <span class="hljs-number">20px</span>
}

<span class="hljs-selector-id">#remote-video</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid blue;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">550px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">550px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">right</span>: <span class="hljs-number">300px</span>
}

<span class="hljs-selector-id">#status</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">bottom</span>: <span class="hljs-number">30px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">30px</span>;
}
</code></pre>
<p>Start the server <code>npm start</code> and go to <code>http://localhost:8000</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621327174314/-LWqT-go7.png" alt="Screenshot 2021-05-18 at 2.08.55 PM.png" /></p>
<p>Okay, please don't judge my front end. I know it's horrible. 🥲</p>
<h3 id="heading-displaying-online-users">Displaying online users</h3>
<p>Firstly, create a route on the backend that gets the users from the user Map and sends them as json.</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/users'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> res.json(<span class="hljs-built_in">Array</span>.from(users));
});
</code></pre>
<p>Great, let's fetch users on the front end.</p>
<p><strong><em> index.html </em></strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
            <span class="hljs-keyword">const</span> socket = io();

            <span class="hljs-keyword">const</span> getAndUpdateUsers = <span class="hljs-keyword">async</span> () =&gt; {
                <span class="hljs-keyword">const</span> usersDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'users'</span>);

                <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/users'</span>, { <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span> });
                <span class="hljs-keyword">const</span> jsonResponse = <span class="hljs-keyword">await</span> response.json();

                <span class="hljs-built_in">console</span>.log(jsonResponse)

                jsonResponse.forEach(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> {
                    <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'button'</span>);
                    <span class="hljs-keyword">const</span> textNode = <span class="hljs-built_in">document</span>.createTextNode(user[<span class="hljs-number">0</span>]);

                    btn.setAttribute(<span class="hljs-string">'onclick'</span>, <span class="hljs-string">`createCall('<span class="hljs-subst">${user[<span class="hljs-number">0</span>]}</span>')`</span>);
                    btn.appendChild(textNode);
                    usersDiv.appendChild(btn);
                });
            }


            socket.on(<span class="hljs-string">'user:joined'</span>, <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
                <span class="hljs-keyword">const</span> usersDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'users'</span>);
                <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'button'</span>);
                <span class="hljs-keyword">const</span> textNode = <span class="hljs-built_in">document</span>.createTextNode(id);

                btn.appendChild(textNode);
                btn.setAttribute(<span class="hljs-string">'onclick'</span>, <span class="hljs-string">`createCall('<span class="hljs-subst">${id}</span>')`</span>);
                usersDiv.appendChild(btn);
            })

            <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, getAndUpdateUsers);
        </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621328131170/4Z15y4lkL.png" alt="Screenshot 2021-05-18 at 2.25.19 PM.png" /></p>
<p>As you can see, I have opened <code>http://localhost:8000</code> on three different tabs, and I got 3 buttons.</p>
<p>Now, create a peer object.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection({
    <span class="hljs-attr">iceServers</span>: [
        {
            <span class="hljs-attr">urls</span>: <span class="hljs-string">"stun:stun.stunprotocol.org"</span>
        }
    ]
});
</code></pre>
<p>and define a function <code>createCall</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> createCall = <span class="hljs-keyword">async</span> (to) =&gt; {
         <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
         status.innerText = <span class="hljs-string">`Calling <span class="hljs-subst">${to}</span>`</span>;

         <span class="hljs-keyword">const</span> localOffer = <span class="hljs-keyword">await</span> peer.createOffer();
         <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(localOffer));

         socket.emit(<span class="hljs-string">'outgoing:call'</span>, { <span class="hljs-attr">fromOffer</span>: localOffer, to })
}
</code></pre>
<p>Great, now let's add a listener for <code>incoming: call</code></p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'incomming:call'</span>, <span class="hljs-keyword">async</span> data =&gt; {
         <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, offer } = data;

         <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));

         <span class="hljs-keyword">const</span> answereOffer = <span class="hljs-keyword">await</span> peer.createAnswer();
         <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(answereOffer));

         socket.emit(<span class="hljs-string">'call:accepted'</span>, { <span class="hljs-attr">answere</span>: answereOffer, <span class="hljs-attr">to</span>: <span class="hljs-keyword">from</span> });
})
</code></pre>
<p>and finally, a listener for <code>incoming: answer</code></p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'incomming:answere'</span>, <span class="hljs-keyword">async</span> data =&gt; {
       <span class="hljs-keyword">const</span> { offer } = data;
       <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));
});
</code></pre>
<p>Great, Now finally get the user's video via webcam and share them.</p>
<p>So, firstly get the user's video and display it on screen.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getUserMedia = <span class="hljs-keyword">async</span> () =&gt; {
     <span class="hljs-keyword">const</span> userMedia = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
            <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>,
     });

      <span class="hljs-keyword">const</span> videoEle = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'local-video'</span>);
      videoEle.srcObject = userMedia;
      videoEle.play()
 }
</code></pre>
<p>Refresh the tab, and you would see something like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621329586345/FCzo1pzX7.png" alt="Screenshot 2021-05-18 at 2.47.55 PM.png" /></p>
<p>Okay, now we have to share this so-called media stream with our remote user.
Inside <code>incoming: call</code> listener. I have added code to share the stream.</p>
<pre><code class="lang-js">socket.on(<span class="hljs-string">'incomming:call'</span>, <span class="hljs-keyword">async</span> data =&gt; {
                <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
                status.innerText = <span class="hljs-string">'incomming:call'</span>;

                <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, offer } = data;

                <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));

                <span class="hljs-keyword">const</span> answereOffer = <span class="hljs-keyword">await</span> peer.createAnswer();
                <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(answereOffer));

                socket.emit(<span class="hljs-string">'call:accepted'</span>, { <span class="hljs-attr">answere</span>: answereOffer, <span class="hljs-attr">to</span>: <span class="hljs-keyword">from</span> });
                <span class="hljs-keyword">const</span> mySteam = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
                    <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>,
                });

                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> track <span class="hljs-keyword">of</span> mySteam.getTracks()) {
                    peer.addTrack(track, mySteam);
                }
            })
</code></pre>
<p>and finally, add a listener on incoming streams</p>
<pre><code class="lang-js">peer.ontrack = <span class="hljs-keyword">async</span> ({<span class="hljs-attr">streams</span>: [stream]}) =&gt; {

       <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
       status.innerText = <span class="hljs-string">'Incomming Stream'</span>;

        <span class="hljs-built_in">console</span>.log(stream)

         <span class="hljs-keyword">const</span> video = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'remote-video'</span>);
         video.srcObject = stream;
         video.play();

         <span class="hljs-keyword">const</span> mySteam = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
                  <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>,
         });

         <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> track <span class="hljs-keyword">of</span> mySteam.getTracks()) {
                 peer.addTrack(track, mySteam);
         }

 }
</code></pre>
<p>And you are done. Try to open this app on 2 tabs and call each other.</p>
<p>Note: I have made very minor changes such as disconnecting the user and displaying my own id. I would recommend you implement that of your own. Anyways I have pasted the complete code below.</p>
<p>Happy learning 🚀</p>
<p>Complete Code:</p>
<p>Server: <strong><em> index.js </em></strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">Server</span>: SocketIO } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

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

<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> SocketIO(server);
<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

<span class="hljs-comment">// Create a users map to keep track of users</span>
<span class="hljs-keyword">const</span> users = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user connected: <span class="hljs-subst">${socket.id}</span>`</span>);
    users.set(socket.id, socket.id);

    <span class="hljs-comment">// emit that a new user has joined as soon as someone joins</span>
    socket.broadcast.emit(<span class="hljs-string">'users:joined'</span>, socket.id);
    socket.emit(<span class="hljs-string">'hello'</span>, { <span class="hljs-attr">id</span>: socket.id });

    socket.on(<span class="hljs-string">'outgoing:call'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> { fromOffer, to } = data;

        socket.to(to).emit(<span class="hljs-string">'incomming:call'</span>, { <span class="hljs-attr">from</span>: socket.id, <span class="hljs-attr">offer</span>: fromOffer });
    });

    socket.on(<span class="hljs-string">'call:accepted'</span>, <span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-keyword">const</span> { answere, to } = data;
        socket.to(to).emit(<span class="hljs-string">'incomming:answere'</span>, { <span class="hljs-attr">from</span>: socket.id, <span class="hljs-attr">offer</span>: answere })
    });


    socket.on(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`user disconnected: <span class="hljs-subst">${socket.id}</span>`</span>);
        users.delete(socket.id);
        socket.broadcast.emit(<span class="hljs-string">'user:disconnect'</span>, socket.id);
    });
});


app.use(express.static( path.resolve(<span class="hljs-string">'./public'</span>) ));

app.get(<span class="hljs-string">'/users'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> res.json(<span class="hljs-built_in">Array</span>.from(users));
});

server.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>HTML: <strong><em> index.html </em></strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>My Video App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Your Id: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myId"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Online Users (click to connect)<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"users"</span>&gt;</span>

                <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"local-video"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">video</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"remote-video"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">video</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"status"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-comment">&lt;!-- Import socket.io script --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/socket.io/socket.io.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
            <span class="hljs-keyword">const</span> socket = io();

            <span class="hljs-keyword">const</span> peer = <span class="hljs-keyword">new</span> RTCPeerConnection({
                <span class="hljs-attr">iceServers</span>: [
                    {
                        <span class="hljs-attr">urls</span>: <span class="hljs-string">"stun:stun.stunprotocol.org"</span>
                    }
                ]
            });

            <span class="hljs-keyword">const</span> createCall = <span class="hljs-keyword">async</span> (to) =&gt; {
                <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
                status.innerText = <span class="hljs-string">`Calling <span class="hljs-subst">${to}</span>`</span>;

                <span class="hljs-keyword">const</span> localOffer = <span class="hljs-keyword">await</span> peer.createOffer();
                <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(localOffer));

                socket.emit(<span class="hljs-string">'outgoing:call'</span>, { <span class="hljs-attr">fromOffer</span>: localOffer, to });
            }

            peer.ontrack = <span class="hljs-keyword">async</span> ({<span class="hljs-attr">streams</span>: [stream]}) =&gt; {

                <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
                status.innerText = <span class="hljs-string">'Incomming Stream'</span>;

                <span class="hljs-built_in">console</span>.log(stream)

                <span class="hljs-keyword">const</span> video = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'remote-video'</span>);
                video.srcObject = stream;
                video.play();

                <span class="hljs-keyword">const</span> mySteam = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
                    <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>,
                });

                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> track <span class="hljs-keyword">of</span> mySteam.getTracks()) {
                    peer.addTrack(track, mySteam);
                }

            }

            socket.on(<span class="hljs-string">'users:joined'</span>, <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
                <span class="hljs-keyword">const</span> usersDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'users'</span>);
                <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'button'</span>);
                <span class="hljs-keyword">const</span> textNode = <span class="hljs-built_in">document</span>.createTextNode(id);

                btn.id = id;

                btn.setAttribute(<span class="hljs-string">'onclick'</span>, <span class="hljs-string">`createCall('<span class="hljs-subst">${id}</span>')`</span>);
                btn.appendChild(textNode);
                usersDiv.appendChild(btn);
            });


            socket.on(<span class="hljs-string">'incomming:answere'</span>, <span class="hljs-keyword">async</span> data =&gt; {
                <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
                status.innerText = <span class="hljs-string">'incomming:answere'</span>;

                <span class="hljs-keyword">const</span> { offer } = data;
                <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));
            });

            socket.on(<span class="hljs-string">'user:disconnect'</span>, <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
                <span class="hljs-built_in">document</span>.getElementById(id).remove()
            })

            socket.on(<span class="hljs-string">'incomming:call'</span>, <span class="hljs-keyword">async</span> data =&gt; {
                <span class="hljs-keyword">const</span> status = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'status'</span>);
                status.innerText = <span class="hljs-string">'incomming:call'</span>;

                <span class="hljs-keyword">const</span> { <span class="hljs-keyword">from</span>, offer } = data;

                <span class="hljs-keyword">await</span> peer.setRemoteDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(offer));

                <span class="hljs-keyword">const</span> answereOffer = <span class="hljs-keyword">await</span> peer.createAnswer();
                <span class="hljs-keyword">await</span> peer.setLocalDescription(<span class="hljs-keyword">new</span> RTCSessionDescription(answereOffer));

                socket.emit(<span class="hljs-string">'call:accepted'</span>, { <span class="hljs-attr">answere</span>: answereOffer, <span class="hljs-attr">to</span>: <span class="hljs-keyword">from</span> });
                <span class="hljs-keyword">const</span> mySteam = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
                    <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>,
                });

                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> track <span class="hljs-keyword">of</span> mySteam.getTracks()) {
                    peer.addTrack(track, mySteam);
                }
            })

            <span class="hljs-keyword">const</span> getAndUpdateUsers = <span class="hljs-keyword">async</span> () =&gt; {
                <span class="hljs-keyword">const</span> usersDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'users'</span>);
                usersDiv.innerHTML = <span class="hljs-string">''</span>

                <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/users'</span>, { <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span> });
                <span class="hljs-keyword">const</span> jsonResponse = <span class="hljs-keyword">await</span> response.json();

                <span class="hljs-built_in">console</span>.log(jsonResponse)

                jsonResponse.forEach(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> {
                    <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'button'</span>);
                    <span class="hljs-keyword">const</span> textNode = <span class="hljs-built_in">document</span>.createTextNode(user[<span class="hljs-number">0</span>]);

                    btn.id = user[<span class="hljs-number">0</span>];

                    btn.setAttribute(<span class="hljs-string">'onclick'</span>, <span class="hljs-string">`createCall('<span class="hljs-subst">${user[<span class="hljs-number">0</span>]}</span>')`</span>);
                    btn.appendChild(textNode);
                    usersDiv.appendChild(btn);
                });
            }

            socket.on(<span class="hljs-string">'hello'</span>, <span class="hljs-function">(<span class="hljs-params">{ id }</span>) =&gt;</span> <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myId'</span>).innerText = id)


            <span class="hljs-keyword">const</span> getUserMedia = <span class="hljs-keyword">async</span> () =&gt; {
                <span class="hljs-keyword">const</span> userMedia = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia({
                    <span class="hljs-attr">video</span>: <span class="hljs-literal">true</span>,
                });

                <span class="hljs-keyword">const</span> videoEle = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'local-video'</span>);
                videoEle.srcObject = userMedia;
                videoEle.play()
            }


            <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, getAndUpdateUsers);
            <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, getUserMedia);
        </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>CSS: <strong><em> style.css </em></strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-family</span>: Arial, Helvetica, sans-serif;
}

<span class="hljs-selector-tag">button</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid;
    <span class="hljs-attribute">cursor</span>: pointer;
    <span class="hljs-attribute">display</span>: block;
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-id">#local-video</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid green;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">250px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">250px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">right</span>: <span class="hljs-number">20px</span>
}

<span class="hljs-selector-id">#remote-video</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid blue;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">550px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">550px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">right</span>: <span class="hljs-number">300px</span>
}

<span class="hljs-selector-id">#status</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">bottom</span>: <span class="hljs-number">30px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">30px</span>;
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Queue tasks in node.js & express]]></title><description><![CDATA[Hey there, in this article we would be discussing how you can queue tasks and run them in the background in node.js and express server.
Queuing jobs is a really easy task, we would be installing a couple of dependencies and then write some code. I wo...]]></description><link>https://blog.piyushgarg.dev/queue-tasks-in-nodejs-and-express</link><guid isPermaLink="true">https://blog.piyushgarg.dev/queue-tasks-in-nodejs-and-express</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[full stack]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sat, 15 May 2021 11:31:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621078525006/6mnMF0jAR.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, in this article we would be discussing how you can queue tasks and run them in the background in node.js and express server.</p>
<p>Queuing jobs is a really easy task, we would be installing a couple of dependencies and then write some code. I would highly recommend you to code along for better understanding.</p>
<p>with that being said, let's get started.</p>
<h1 id="step-0-setup">Step 0: Setup</h1>
<p>In this project, we would be using a package known as "bull" which is great for queuing jobs in the background. But in order to run the bull package, we must have Redis installed on our machine.
So, head over to https://redis.io/download and download the stable version of Redis. After successful installation, we are good to go.</p>
<h1 id="step-1-project-setup-and-installing-dependencies">Step 1: Project Setup and installing dependencies</h1>
<p>Now, go ahead and initialize an empty nodejs project with <code>npm init</code>. I would assume that you are already familiar with node.js and express and won't be going deep into the basics. After setting up the project install express and bull library by running <code>npm install express bull</code>.</p>
<h1 id="step-2-basic-express-server">Step 2: Basic express server</h1>
<p>In this step, we would be creating a simple express server up and running.</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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

<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.end(<span class="hljs-string">'Hello from the server'</span>)
})

app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>))
</code></pre>
<p>let's start the server <code>node index.js</code>.</p>
<h1 id="step-3-implementing-queue">Step 3: Implementing Queue</h1>
<p>Now, in this step, we would be implementing the queue feature. 
To understand the implementation queue, let's simulate a fake situation. Please read and understand the following situation carefully.</p>
<blockquote>
<p>A user visits your website and sees a form. He fills up the form and uploads some high-quality photos and clicks on submit. The request is then sent to the backend along with the data and photos he uploaded. Now, on the server, you want to first compress the images and upload the image to let's say amazon s3 bucket and then update the URL of images in the database.</p>
</blockquote>
<p>As you can already guess, the above scenario is a time taking process. If you do all the above-mentioned tasks on the main thread it would highly affect the performance of your server and users have to wait really long. So, to avoid that let's code the above scenario with queues.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> Queue = <span class="hljs-built_in">require</span>(<span class="hljs-string">'bull'</span>); <span class="hljs-comment">// import the bull package</span>

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

<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">8000</span>;

<span class="hljs-comment">// create a middleware that creates queue and add to the request object</span>
app.use(<span class="hljs-function">(<span class="hljs-params">req, res,next</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> imageProcessingQueue = <span class="hljs-keyword">new</span> Queue(<span class="hljs-string">'imageProcessingQueue'</span>); <span class="hljs-comment">// Create a queue object.</span>
    req.queue = imageProcessingQueue; <span class="hljs-comment">// add this queue to req object so its accessible in the request handler.</span>

    next(); <span class="hljs-comment">// important!</span>
});

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.end(<span class="hljs-string">'Hello from the server'</span>)
});

<span class="hljs-comment">// Submit route, where the data is actually submitted.</span>
app.post(<span class="hljs-string">'/submit'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> imageFiles = req.files; <span class="hljs-comment">// Images uploaded by the user.</span>
    <span class="hljs-keyword">const</span> data = insertIntoDatabase(req.body); <span class="hljs-comment">// Rest of the form data has been saved in database;</span>

    <span class="hljs-comment">// Define a queue.process method</span>
    req.queue.process(<span class="hljs-function">(<span class="hljs-params">job, done</span>) =&gt;</span> {
        <span class="hljs-comment">// Write all the logic to compress and upload file here.</span>
        <span class="hljs-comment">// I would be using setTimeout to simulate this thing.</span>

        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Compression and upload done'</span>);
            <span class="hljs-comment">// update the links in database. job.data.id contains the id of the insertedData,</span>
            done(); <span class="hljs-comment">// call the done method when all things are done;</span>
        }, <span class="hljs-number">5000</span>);
    });

    req.queue.add(data); <span class="hljs-comment">// finally add the queue and pass the required info as parameter.</span>

    <span class="hljs-keyword">return</span> res.json({
        <span class="hljs-attr">message</span>: <span class="hljs-string">'successfully queued'</span>,
    });

});

app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>))
</code></pre>
<p>let's start the server <code>node index.js</code></p>
<p>Now, I would fire up my postman and try to send POST requests at /submit route.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621077988333/xkClWOL52.png" alt="Screenshot 2021-05-15 at 4.55.01 PM.png" /></p>
<p>Great! I got a "successfully queued" response. Now let's check our server console.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621078044073/v7TOUW3Mo.png" alt="Screenshot 2021-05-15 at 4.55.20 PM.png" /></p>
<p>As you can see, after 5 seconds, I got a log saying "Compression and upload done" as I set a time out of 5 seconds. </p>
<p>I hope that now you have understood how you can queue tasks in nodejs and express server.</p>
]]></content:encoded></item><item><title><![CDATA[Integrate Razorpay Payment Gateway with node.js and express server]]></title><description><![CDATA[Source: Razorpay
Hello reader, in this article I would provide you step by step guide to integrate the Razorpay payment gateway into your node.js application. Trust me, it’s easy than you think.
So, let’s begin…
Step 0: Initialize Project
First thing...]]></description><link>https://blog.piyushgarg.dev/integrate-razorpay-payment-gateway-with-node-js-and-express-server-924f771af7e0</link><guid isPermaLink="true">https://blog.piyushgarg.dev/integrate-razorpay-payment-gateway-with-node-js-and-express-server-924f771af7e0</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sun, 09 May 2021 07:18:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072207548/p-jI3s4zC.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Source: Razorpay</p>
<p>Hello reader, in this article I would provide you step by step guide to integrate the <strong>Razorpay payment gateway</strong> into your node.js application. Trust me, it’s easy than you think.</p>
<p>So, let’s begin…</p>
<h2 id="step-0-initialize-project"><strong>Step 0: Initialize Project</strong></h2>
<p>First things first, so let's create a simple project folder and start our journey.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072192682/ERSx0j_t2.png" alt /></p>
<p>Here I have created a folder named “razorpay-tutorial”. Now open your terminal in the folder and run the following command to init the node server.</p>
<pre><code>npm <span class="hljs-keyword">init</span> -y
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072195471/zl9bekyqF.png" alt /></p>
<p>This command would create a package.json file in your project.</p>
<h2 id="step-1-install-dependencies"><strong>Step 1: Install dependencies</strong></h2>
<p>In order to integrate razor pay, we need to install the following dependencies.</p>
<ol>
<li><p>express</p>
</li>
<li><p>razorpay</p>
</li>
</ol>
<p>Run the following command to install the above dependencies.</p>
<pre><code><span class="hljs-built_in">npm</span> install express razorpay
</code></pre><h2 id="step-2-create-and-set-up-a-simple-express-server">Step 2: Create and set up a simple express server</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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


app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Express server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>also, create a public folder in your project and serve it via express.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072197789/wExLhH25Y.png" alt /></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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

<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">8000</span>;

app.use(express.static(<span class="hljs-string">'./public'</span>));
app.use(express.json());


app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Express server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<h2 id="step-3-lets-begin-with-razorpay">Step 3: Let's begin with razorpay</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072200069/qC2iRaxJs.png" alt /></p>
<p>To begin with, firstly we have to create an order on our server.</p>
<h3 id="step-31-creating-an-order-on-our-server">Step 3.1: Creating an order on our server</h3>
<pre><code>Note: You need to <span class="hljs-keyword">create</span> an <span class="hljs-keyword">test</span> <span class="hljs-keyword">account</span> <span class="hljs-keyword">on</span> the razorpay. <span class="hljs-keyword">Then</span> <span class="hljs-keyword">in</span> the <span class="hljs-keyword">settings</span> pannel <span class="hljs-keyword">of</span> razorpay, <span class="hljs-keyword">go</span> <span class="hljs-keyword">to</span> API <span class="hljs-keyword">keys</span> <span class="hljs-keyword">and</span> generate keys. Copy the key_id <span class="hljs-keyword">and</span> key_secret.
</code></pre><pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { request, response } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> Razorpay = <span class="hljs-built_in">require</span>(<span class="hljs-string">'razorpay'</span>);

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

<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">8000</span>;

app.use(express.static(<span class="hljs-string">'./public'</span>));
app.use(express.json());

app.post(<span class="hljs-string">'/order'</span>, <span class="hljs-keyword">async</span> (request, response) =&gt; {

    <span class="hljs-keyword">const</span> amount = request.body.amount;

    <span class="hljs-keyword">if</span> (!amount) <span class="hljs-keyword">return</span> response.json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Please provide amount'</span> })

    <span class="hljs-comment">// Create a razorpayInstance</span>
    <span class="hljs-keyword">const</span> razorpayInstance = <span class="hljs-keyword">new</span> Razorpay({ 
        <span class="hljs-attr">key_id</span>: <span class="hljs-string">'&lt;YOUR_KEY_ID_HERE&gt;'</span>,
        <span class="hljs-attr">key_secret</span>: <span class="hljs-string">'&lt;YOUR_SECRET_HERE&gt;'</span>,
     });

     <span class="hljs-keyword">const</span> paymentOptions = {
        <span class="hljs-attr">amount</span>: amount * <span class="hljs-number">100</span>,
        <span class="hljs-attr">currency</span>: <span class="hljs-string">'INR'</span>,
        <span class="hljs-attr">receipt</span>: <span class="hljs-string">'#1'</span>,
     };

     <span class="hljs-keyword">const</span> razorpayOrder = <span class="hljs-keyword">await</span> razorpayInstance.orders.create(paymentOptions);

     <span class="hljs-keyword">return</span> response.json({ 
        <span class="hljs-attr">message</span>: <span class="hljs-string">'success'</span>, 
        <span class="hljs-attr">order</span>: razorpayOrder 
    });

});


app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Express server started at PORT:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>As you can see, we have defined a post route “/order” which is responsible for creating an order and return a JSON response with the created order.</p>
<h3 id="step-32-design-our-front-end">Step 3.2 Design our front-end</h3>
<blockquote>
<p>Navigate to your public folder and add the following code to public/index.html file.</p>
</blockquote>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Razorpay<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"buy-now-btn"</span>&gt;</span>Buy Now<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- Razorpay Script --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://checkout.razorpay.com/v1/checkout.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-comment">// Get the button</span>
        <span class="hljs-keyword">const</span> buyButton = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'buy-now-btn'</span>);

        <span class="hljs-comment">// Add click event listner</span>
        buyButton.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {

        });

    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Now start your server and head to <a target="_blank" href="http://localhost:8000">http://localhost:8000</a></p>
<blockquote>
<p>Run the following command to start the server</p>
</blockquote>
<pre><code>node <span class="hljs-keyword">index</span>.js
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072202308/rve53gQZU.png" alt /></p>
<pre><code class="lang-javascript">buyButton.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-keyword">async</span> (event) =&gt; {

            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'/order'</span>, {
                <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
                <span class="hljs-attr">headers</span>: {
                    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
                },
                <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">amount</span>: <span class="hljs-number">500</span> }) <span class="hljs-comment">// Rs.500</span>
            });

            <span class="hljs-keyword">const</span> responseJson = <span class="hljs-keyword">await</span> response.json();

            <span class="hljs-keyword">const</span> { order } = responseJson;

            <span class="hljs-keyword">const</span> razorPayOptions = {
                <span class="hljs-attr">key</span>: <span class="hljs-string">'&lt;YOUR_KEY_ID_HERE&gt;'</span>,
                <span class="hljs-attr">amount</span>: <span class="hljs-number">500</span>,
                <span class="hljs-attr">currency</span>: <span class="hljs-string">'INR'</span>,
                <span class="hljs-attr">name</span>: <span class="hljs-string">`Buy Shirt`</span>,
                <span class="hljs-attr">description</span>: <span class="hljs-string">`Paying for testing`</span>,
                <span class="hljs-attr">order_id</span>: order.id,
                <span class="hljs-attr">handler</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) </span>{ <span class="hljs-comment">// handler function when payment is successfull</span>
                    <span class="hljs-keyword">const</span> razorpayPaymentId = response[<span class="hljs-string">'razorpay_payment_id'</span>];
                    <span class="hljs-keyword">const</span> razorpayOrderId = response[<span class="hljs-string">'razorpay_order_id'</span>];
                    <span class="hljs-keyword">const</span> razorpaySignature = response[<span class="hljs-string">'razorpay_signature'</span>];

                    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Payment successfull'</span>);
                },
            };

            <span class="hljs-keyword">const</span> razorpayInstance = <span class="hljs-keyword">new</span> Razorpay(razorPayOptions);
            razorpayInstance.open();

        });
</code></pre>
<p>In your button click event listener add the above code and done. You have successfully integrated the Razorpay gateway.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072204349/b5Xmgn3K4.png" alt /></p>
]]></content:encoded></item><item><title><![CDATA[Build a chat application with Express and Socket.io]]></title><description><![CDATA[Hey guys, In this article, we would be building a real chat application. Building a chat application is really easy.
For this application, we would be using Express.js and Socket.io.
I would recommend you to code along with me to better understand th...]]></description><link>https://blog.piyushgarg.dev/build-a-chat-application-with-express-and-socket-io-e8c335d27386</link><guid isPermaLink="true">https://blog.piyushgarg.dev/build-a-chat-application-with-express-and-socket-io-e8c335d27386</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[server]]></category><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sun, 26 Apr 2020 14:45:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072253264/YXyRDrQHj.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey guys, In this article, we would be building a real chat application. Building a chat application is really easy.</p>
<p>For this application, we would be using Express.js and Socket.io.</p>
<p>I would recommend you to code along with me to better understand the code.</p>
<h3 id="so-lets-begin">So, Let’s begin 😉</h3>
<h2 id="step-0-setting-up-the-project">Step 0: Setting up the project</h2>
<h3 id="firstly-lets-create-a-folder-chatapp">Firstly, let's create a folder chatApp</h3>
<p>After then create the following two new folders inside the chatApp folder:</p>
<ol>
<li><p>server</p>
</li>
<li><p>client</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072241953/etb1p84OT.png" alt /></p>
<h2 id="step-11-server">Step 1.1: Server</h2>
<p>Now, head over to the <strong>server folder</strong> and run the following command:</p>
<pre><code>npm <span class="hljs-keyword">init</span>
</code></pre><p>After initializing package.json lets now install some dependencies</p>
<pre><code><span class="hljs-selector-tag">npm</span> <span class="hljs-selector-tag">install</span> <span class="hljs-selector-tag">socket</span><span class="hljs-selector-class">.io</span>
</code></pre><h3 id="great-and-finally-lets-create-our-indexjs-file">Great, and finally let's create our index.js file</h3>
<h3 id="now-lets-have-our-boilerplate-code-to-serverindexjs">Now, let's have our boilerplate code to server/index.js</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> socket = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);

<span class="hljs-keyword">const</span> server = http.createServer();
<span class="hljs-keyword">const</span> io = socket(server);

server.listen(<span class="hljs-number">8080</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server Running`</span>))
</code></pre>
<p>In the above code firstly we required the node’s build-in HTTP module and created a server using <strong>createServer()</strong> method.</p>
<p>Then, we imported our <strong>socket.io</strong> and named it as socket which returns a function.</p>
<p>Finally, we initialised our io by calling the function socket and passed our server as parameter to it.</p>
<h3 id="great-now-we-have-successfully-created-a-server-and-initialized-our-io">Great, now we have successfully created a server and initialized our io.</h3>
<h2 id="step-1-creating-socketio-listeners-on-the-backend">Step 1 Creating socket.io listeners on the backend</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> socket = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);

<span class="hljs-keyword">const</span> server = http.createServer();
<span class="hljs-keyword">const</span> io = socket(server);

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A new user has joined the chat'</span>)

  socket.emit(<span class="hljs-string">'message'</span>, <span class="hljs-string">'You have successfully joined the chat'</span>)

})

server.listen(<span class="hljs-number">8080</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server Running`</span>))
</code></pre>
<p>Whenever there is a new user or a connection joins the chat, the <strong>‘connection’</strong> event is fired by the <strong>socket.io</strong>, to which we are listening with the<strong> .on method</strong>.</p>
<p>so <strong>io.on(‘connection’), </strong>means whenever there is a connection this function will be called. This function has a second argument which is a callback function that has access to a single parameter and that is a socket. The socket contains information about the user who has just joined.</p>
<p>So whenever a new user joins the chat, our server would log <strong>A new user has joined the chat. </strong>Also, we must welcome the user who has just joined by saying, <strong>You have successfully joined the chat.</strong></p>
<p>So, to send a message <strong>only to a particular user who has just joined</strong> we do:</p>
<pre><code><span class="hljs-selector-tag">socket</span><span class="hljs-selector-class">.emit</span>(<span class="hljs-string">'message'</span>, <span class="hljs-string">'**You have successfully joined the chat'</span>);**
</code></pre><p><strong>.emit</strong> method is used to fire up an event where the first parameter is event name and second is the data.</p>
<p>With that being set now let us set up our listeners for the incoming and outgoing chat messages.</p>
<p>So to listen to an event we use the <strong>.on method.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> socket = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);

<span class="hljs-keyword">const</span> server = http.createServer();
<span class="hljs-keyword">const</span> io = socket(server);

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function"><span class="hljs-params">socket</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A new user has joined the chat'</span>)

  socket.emit(<span class="hljs-string">'message'</span>, <span class="hljs-string">'You have successfully joined the chat'</span>)

  socket.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {
    io.emit(<span class="hljs-string">'message'</span>, msg)
  })

})

server.listen(<span class="hljs-number">8080</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server Running`</span>))
</code></pre>
<p>Let me simplify, In the above code, we are listening to an event named as “message” which would be fired up from our frontend later. So whenever a socket ( which is a user ) sends a message we will take that message and send that to everyone. The io means everyone.</p>
<blockquote>
<p><strong>socket.emit</strong> — Only to the user.
<strong>IO </strong>— To all the users connected to our application.</p>
</blockquote>
<h3 id="i-hope-you-got-the-point">I hope you got the point. 🤓</h3>
<p><strong>Now Run your server:</strong></p>
<pre><code>node <span class="hljs-keyword">index</span>.js
</code></pre><p><strong>and keep it running…</strong></p>
<h2 id="good-news-our-backend-is-complete-yes-thats-it">Good News! 🎉Our backend is complete. Yes! That's it.</h2>
<h2 id="step-12-creating-frontend">Step 1.2: Creating FrontEnd</h2>
<h3 id="now-navigate-to-the-client-folder-and-create-indexhtml-and-indexjs-file">Now, navigate to the client folder and create index.html and index.js file.</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072243730/CKT12zI9x.png" alt /></p>
<p>Now, let's design a simple frontend in index.html</p>
<h3 id="copy-the-code-below-into-indexhtml">Copy the code below into index.html</h3>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Chat App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
    <span class="hljs-selector-class">.chat-container</span>{
      <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid;
      <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
      <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
      <span class="hljs-attribute">overflow</span>: scroll;
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"bg-dark text-white p-3 text-center"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Chat App<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container mt-5"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"chat-box"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list-group chat-container"</span>&gt;</span>

    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mt-3"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"chat-form"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"messageBox"</span> <span class="hljs-attr">required</span>/&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-success form-control mt-2"</span>&gt;</span>Send<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Our Design</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072245608/CPLc1UJsi.png" alt /></p>
<h2 id="now-navigate-to-indexjs-file-in-the-client-folder">Now navigate to index.js file in the client folder</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'chat-form'</span>);
<span class="hljs-keyword">const</span> messageBox = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'messageBox'</span>);
<span class="hljs-keyword">const</span> chatBox = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'chat-box'</span>)

<span class="hljs-keyword">const</span> socket = io(<span class="hljs-string">'localhost:8080'</span>);

  socket.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> liTag = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>);
    liTag.classList.add(<span class="hljs-string">'list-group-item'</span>)
    liTag.innerText = msg;

    chatBox.appendChild(liTag)
  })


form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
  e.preventDefault();
  socket.emit(<span class="hljs-string">'message'</span>, messageBox.value)
  messageBox.value = <span class="hljs-string">''</span>
})
</code></pre>
<p>So firstly we initialize our socket variable and pass our servers address.</p>
<p>Then, we listen to the message event fired by our backend which contains the message.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072247445/NC1XeK5yG.png" alt="server/index.js: Rember this?" /><em>server/index.js: Rember this?</em></p>
<p>And finally, we add an event listener to our form and emits the user message to a socket which is being listened by our backend.</p>
<h2 id="now-on-the-vscode-run-the-indexhtml-with-live-server-and-test-the-application">Now, on the vscode, run the index.html with live server and test the application</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072249327/ZYk9HloZ3.png" alt="Ohh! I got a welcome Message" /><em>Ohh! I got a welcome Message</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072251261/q8ZyDuh7v.png" alt="Also, my server says that" /><em>Also, my server says that</em></p>
<h2 id="congrats-you-have-successfully-build-your-own-chatting-server">Congrats! You have successfully build your own chatting server.</h2>
<p><a target="_blank" href="https://medium.com/daily-programmer/authentication-in-nodejs-using-passport-js-48b3c7394a5d"><strong>Authentication in Nodejs using Passport.js</strong>
<em>In this article I would be teaching you authentication in nodejs using express and passport.js</em>medium.com</a>
<a target="_blank" href="https://medium.com/daily-programmer/express-and-mongodb-78cc7266f569"><strong>Express and MongoDB</strong>
<em>In this article, I would be teaching you how to use MongoDB with express.js and perform CRUD operations.</em>medium.com</a>
<a target="_blank" href="https://medium.com/daily-programmer/building-rest-api-with-node-js-4420ff6214b6"><strong>Building REST API with Node.js</strong>
<em>Build your own REST API from scratch</em>medium.com</a>
<a target="_blank" href="https://medium.com/daily-programmer/top-10-visual-studio-code-extensions-2020-fc5761116443"><strong>Top 10 visual studio code extensions 2020</strong>
<em>Best vscode extensions to make your development smooth and powerful.</em>medium.com</a></p>
<h2 id="social-links">Social Links:</h2>
<p>Github: <a target="_blank" href="https://github.com/piyushgarg195">https://github.com/piyushgarg195</a></p>
<p>Linkedin: <a target="_blank" href="https://www.linkedin.com/in/piyushgarg195/">https://www.linkedin.com/in/piyushgarg195/</a></p>
<p>Website: <a target="_blank" href="https://www.piyushgarg.dev/">https://www.piyushgarg.dev/</a></p>
]]></content:encoded></item><item><title><![CDATA[Express and MongoDB]]></title><description><![CDATA[Hey there, In this article, I would be teaching you how to use MongoDB with express.js and perform CRUD operations.
What is MongoDB?
MongoDB is a no-SQL database. It is a general-purpose, document-based, distributed database built for modern applicat...]]></description><link>https://blog.piyushgarg.dev/express-and-mongodb-78cc7266f569</link><guid isPermaLink="true">https://blog.piyushgarg.dev/express-and-mongodb-78cc7266f569</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Sat, 25 Apr 2020 13:19:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072350163/r-Hr4Fz18.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, In this article, I would be teaching you how to use <strong>MongoDB</strong> with express.js and perform CRUD operations.</p>
<h2 id="what-is-mongodb">What is MongoDB?</h2>
<p>MongoDB is a no-SQL database. It is a general-purpose, document-based, distributed database built for modern application developers and for the cloud era.</p>
<h3 id="mongodb-stores-the-data-as-form-of-document-inside-collections">MongoDB stores the data as form of document inside collections.</h3>
<p>For Example: If I have a record of 5 students, So I can say that I have 5 documents inside a collection named as students.</p>
<h3 id="i-hope-you-got-the-point">I hope you got the point. 😄</h3>
<blockquote>
<p>Note: In this tutorial, I will be using MongoDB atlas to avoid the complexities faced while installing MongoDB and it would also be easier for beginners to understand too.
<strong>MongoDB Atlas is a cloud service to use mongoDb.</strong></p>
</blockquote>
<h2 id="lets-begin">Let’s Begin</h2>
<h2 id="step-0-create-an-account-on-mongodb">Step 0: Create an account on MongoDB</h2>
<p>Head over to <a target="_blank" href="https://www.mongodb.com/">https://www.mongodb.com/</a> and create your free account to use MongoDB atlas.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072305584/0bk21t43p.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072308087/rhYpGf4m9.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072310204/NVQsn51SP.png" alt /></p>
<h2 id="after-creating-your-account-choose-free-cluster-and-click-on-create-a-cluster">After creating your account, choose free cluster and click on create a cluster</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072312498/4EbVfkblJ.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072314928/ZlTlic--D.png" alt /></p>
<h2 id="now-wait-for-23-minutes-for-the-cluster-to-get-deployed">Now, wait for 2–3 minutes for the cluster to get deployed.</h2>
<h2 id="congrats-you-have-successfully-deployed-your-cluster-and-now-we-are-ready-to-move-on-to-next-step">Congrats! You have successfully deployed your cluster and now we are ready to move on to next step. 🎉</h2>
<h2 id="step1-configuring-mongodb-atlas">Step1: Configuring MongoDB Atlas</h2>
<p>There are a couple of tweaks here and there which we need to follow to get started with MongoDB Atlas.</p>
<h3 id="creating-a-user-role-to-access-the-database-from-our-application"><strong>Creating a user role to access the database from our application</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072317300/dQf6HLR8zI.png" alt="Navigate to Database Access" /><em>Navigate to Database Access</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072319086/gUkGjayH0g.png" alt="Click add new database user" /><em>Click add new database user</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072321770/4lkjKKcWK.png" alt /></p>
<h3 id="now-we-have-to-whitelist-the-ips-from-where-we-can-access-the-database">Now, We have to whitelist the IP’s from where we can access the database.</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072324699/DwPumdvp4.png" alt="Navigate to Network access and click Add IP Address" /><em>Navigate to Network access and click Add IP Address</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072326898/t5TKic-jd.png" alt="Select Allow Access from anywhere and select confirm" /><em>Select Allow Access from anywhere and select confirm</em></p>
<h2 id="step-2-project-setup">Step 2: Project Setup</h2>
<p>Now, lets set up our project structure and create boilerplate code.</p>
<h3 id="firstly-create-a-folder-lets-name-it-as-myproject">Firstly, create a folder. Let's name it as “myProject”.</h3>
<h3 id="now-fire-up-your-terminal-or-command-prompt-and-run">Now, Fire-up your terminal or command prompt and run:</h3>
<pre><code>npm <span class="hljs-keyword">init</span>
</code></pre><h3 id="great-now-lets-install-dependencies">Great, Now let's install dependencies.</h3>
<p>Run:</p>
<pre><code><span class="hljs-built_in">npm</span> i express mongoose
</code></pre><p><strong>Great Going, Now let's create some files and folders. For the time bear with me and create these folders. I am going to explain the working of each and file step by step.</strong></p>
<p><strong>Our Project Structure:</strong></p>
<pre><code>myProject
|
|- model
     |- <span class="hljs-keyword">user</span>.js
|- <span class="hljs-keyword">index</span>.js
|- package.json
</code></pre><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072328690/xKBUFHfod.png" alt /></p>
<p>In the above project structure, we have created a folder <strong>model, </strong>this is the folder where we are going to keep all our schemas for different collection.</p>
<p>Currently, we have one, the <strong>user.js</strong></p>
<h2 id="step-3-creating-the-boilerplate-code">Step 3: Creating the Boilerplate Code</h2>
<p>Head over to index.js and code along with me.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>);
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<h2 id="step-4-connect-our-node-application-to-mongodb-atlas">Step 4: Connect our node application to MongoDB Atlas</h2>
<p>Connecting application to MongoDB is really simple.</p>
<ol>
<li><strong>Head over to Clusters panel and click connect.</strong></li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072331216/O2UR8VKJI.png" alt /></p>
<p><strong>2. Click on connect your application.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072333318/rQRLRT6rk.png" alt /></p>
<p><strong>3. Copy the connection string</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072335514/lCQmlOBDd.png" alt /></p>
<p>Great Now back to our code …..</p>
<h3 id="follow-the-steps-below-to-connect-to-mongodb-atlas">Follow the steps below to connect to MongoDB Atlas</h3>
<ol>
<li>Import the mongoose package in index.js</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);


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

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>);
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<ol>
<li>Use connect function of mongoose to connect to our application and pass the connection string that we copied earlier.</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072337802/iqKxkYvhU.png" alt="Replace the original password with &lt;password&gt;" /><em>Replace the original password with &lt;password&gt;</em></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

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

mongoose.connect(
  <span class="hljs-string">`mongodb+srv://piyushgarg:hello123@cluster0-2bghc.mongodb.net/test?retryWrites=true&amp;w=majority`</span>
  )
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'MongoDB Connect'</span>))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error Occured <span class="hljs-subst">${err}</span>`</span>))


app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>);
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<p>Additionally, pass the following parameters to the connect function:</p>
<blockquote>
<p>Refer to <a target="_blank" href="https://mongoosejs.com/docs/deprecations.html">https://mongoosejs.com/docs/deprecations.html</a> for more info</p>
</blockquote>
<pre><code>{

<span class="hljs-attr">useNewUrlParser:</span> <span class="hljs-literal">true</span>,

<span class="hljs-attr">useUnifiedTopology:</span> <span class="hljs-literal">true</span>

}
</code></pre><pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

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

mongoose.connect(
  <span class="hljs-string">`mongodb+srv://piyushgarg:hello123@cluster0-2bghc.mongodb.net/test?retryWrites=true&amp;w=majority`</span>,
  {
    <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>
  }
  )
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'MongoDB Connect'</span>))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error Occured <span class="hljs-subst">${err}</span>`</span>))


app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>);
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<h2 id="congrats-try-running-the-server-and-you-would-see-mongodb-connected-on-the-console">Congrats! 🎉… try running the server and you would see MongoDB connected on the console.</h2>
<h2 id="step-4-creating-user-schema">Step 4: Creating user schema</h2>
<p>In this step, we would be working with the <strong>user.js</strong> inside our <strong>models</strong> folder and create a user schema.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

<span class="hljs-keyword">const</span> userSchema = mongoose.Schema({
  <span class="hljs-attr">name</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>,
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
  },
  <span class="hljs-attr">email</span>:{
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>,
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">unique</span>: <span class="hljs-literal">true</span>,
  },
  <span class="hljs-attr">password</span>:{
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>,
    <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>,
  },
  <span class="hljs-attr">age</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-built_in">Number</span>
  }
})

<span class="hljs-keyword">const</span> user = mongoose.model(<span class="hljs-string">'users'</span>, userSchema);

<span class="hljs-built_in">module</span>.exports = user;
</code></pre>
<p>In this file, we, first of all, require the mongoose package and then use the . Schema method to create the schema. In the Schema method, we pass an object specifying our schema of the user with various properties like type, unique and required.</p>
<p>Finally, we create a model using mongoose. model which requires two parameters:</p>
<p>First: The name of the model as a string. [ users ]</p>
<p>Second: The user schema we created above.</p>
<h2 id="hooray-user-schema-ready-now-we-are-ready-to-perform-crud-operations">Hooray! User Schema Ready! Now we are ready to perform CRUD operations</h2>
<h2 id="step-5-api-and-crud-operations">Step 5: API and CRUD operations</h2>
<p>In this step, we would be creating API's to perform crud operation on our DB.</p>
<p>Back to index.js</p>
<h3 id="import-the-userjs-and-start-coding-along-with-me">Import the user.js and start coding along with me.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

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

<span class="hljs-keyword">const</span> User = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./model/user'</span>);

mongoose.connect(
  <span class="hljs-string">`mongodb+srv://piyushgarg:hello123@cluster0-2bghc.mongodb.net/test?retryWrites=true&amp;w=majority`</span>,
  {
    <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">useUnifiedTopology</span>: <span class="hljs-literal">true</span>
  }
  )
  .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'MongoDB Connect'</span>))
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error Occured <span class="hljs-subst">${err}</span>`</span>))


app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>);
})

app.get(<span class="hljs-string">'/users/all'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

  User.find({}, <span class="hljs-function">(<span class="hljs-params">err, users</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err) <span class="hljs-keyword">return</span> res.json(err);
    <span class="hljs-keyword">return</span> res.json(users)
  })

})


app.get(<span class="hljs-string">'/users/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {

  <span class="hljs-keyword">const</span> id = req.params.id;
  User.findById(id, <span class="hljs-function">(<span class="hljs-params">err, user</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span>(err) <span class="hljs-keyword">return</span> res.json(err);

    <span class="hljs-keyword">return</span> res.json(user);
  })
})

app.post(<span class="hljs-string">'/user/new'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> {name, email, password, age} = req.body;
  <span class="hljs-keyword">const</span> myUser = <span class="hljs-keyword">new</span> User();
  myUser.name = name;
  myUser.email = email;
  myUser.password = password; <span class="hljs-comment">// Make sure you hash the passowrd;</span>
  myUser.age = age;

  myUser.save()
    .then(<span class="hljs-function">() =&gt;</span> res.send(<span class="hljs-string">'User inserted into db'</span>))
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> res.send(err))
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<p>There is one error in code and that is we have not implemented the express.json() middleware.</p>
<p>Well, that’s your task.</p>
<h2 id="and-done"><strong>And Done! 😍</strong></h2>
<h2 id="lets-test-our-implementation-in-postman">Let's test our implementation in Postman</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072339920/r0pkkEO2h.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072341953/4aPOTziEg.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072344189/VOzghI2VFZ.png" alt /></p>
<h3 id="in-your-mongodb-atlas-go-to-collections-and-see-your-newly-created-user-document-there">In your MongoDB Atlas go to collections and see your newly created user document there.</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072346131/NmjTVu1jzz.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072348299/GJy50SUWK.png" alt /></p>
<h2 id="great-our-api-is-working-great">Great! 😍 Our API is working great.</h2>
<p><a target="_blank" href="https://medium.com/daily-programmer/authentication-in-nodejs-using-passport-js-48b3c7394a5d"><strong>Authentication in Nodejs using Passport.js</strong>
<em>In this article I would be teaching you authentication in nodejs using express and passport.js</em>medium.com</a>
<a target="_blank" href="https://medium.com/daily-programmer/building-rest-api-with-node-js-4420ff6214b6"><strong>Building REST API with Node.js</strong>
<em>Build your own REST API from scratch</em>medium.com</a>
<a target="_blank" href="https://medium.com/daily-programmer/top-10-visual-studio-code-extensions-2020-fc5761116443"><strong>Top 10 visual studio code extensions 2020</strong>
<em>Best vscode extensions to make your development smooth and powerful.</em>medium.com</a>
<a target="_blank" href="https://medium.com/daily-programmer/authentication-in-nodejs-using-json-web-tokens-jwt-936e6c0118ef"><strong>Authentication in Nodejs using JSON web tokens (JWT)</strong>
<em>Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka…</em>medium.com</a></p>
<h2 id="social-links">Social Links:</h2>
<p>Github: <a target="_blank" href="https://github.com/piyushgarg195">https://github.com/piyushgarg195</a></p>
<p>Linkedin: <a target="_blank" href="https://www.linkedin.com/in/piyushgarg195/">https://www.linkedin.com/in/piyushgarg195/</a></p>
<p>Website: <a target="_blank" href="https://www.piyushgarg.dev/">https://www.piyushgarg.dev/</a></p>
]]></content:encoded></item><item><title><![CDATA[Authentication in Nodejs using Passport.js]]></title><description><![CDATA[Hello once again, In this article I would be teaching you authentication in nodejs using express and passport.js
I know working with passport.js is a little bit tricky and confusing, but trust me I'll make it really simple.
I would highly recommend y...]]></description><link>https://blog.piyushgarg.dev/authentication-in-nodejs-using-passport-js-48b3c7394a5d</link><guid isPermaLink="true">https://blog.piyushgarg.dev/authentication-in-nodejs-using-passport-js-48b3c7394a5d</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Fri, 24 Apr 2020 18:16:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621926579705/kiBS11wV3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello once again, In this article I would be teaching you <strong>authentication in nodejs</strong> using <strong>express and passport.js</strong></p>
<p>I know working with passport.js is a little bit tricky and confusing, but trust me I'll make it really simple.</p>
<p>I would highly recommend you to code along with me to better understand the flow of the code.</p>
<h2 id="note-before-we-begin-i-would-like-you-to-understand-the-term-strategy">Note: Before we begin I would like you to understand the term “Strategy”</h2>
<p>Passport uses what is termed <em>strategies</em> to authenticate requests.</p>
<p>Like authenticating with username and password is a strategy, authenticating with google or Facebook is a strategy.</p>
<p>So the strategy is a way to authenticate a user.</p>
<p>In this tutorial, we would be using the username and password authentication known as a <strong>local strategy</strong> in terms of passport.js</p>
<h2 id="step-0-project-setup-and-installing-dependencies">Step 0: Project setup and Installing dependencies</h2>
<p><strong>First of all, Create a new folder, let’s say “myApplication” and open your terminal or command prompt in that folder.</strong></p>
<p>After opening your terminal or command prompt run the following command to initialize your node application.</p>
<pre><code>npm <span class="hljs-keyword">init</span>
</code></pre><h3 id="after-successfully-creating-your-json-file-now-we-are-ready-to-install-the-following-dependencies">After successfully creating your JSON file, now we are ready to install the following dependencies:</h3>
<ol>
<li><p>express</p>
</li>
<li><p>express-session</p>
</li>
<li><p>passport</p>
</li>
<li><p>passport-local</p>
</li>
</ol>
<h3 id="install-the-above-dependencies-by-typing-following-command">Install the above dependencies by typing following command:</h3>
<pre><code>npm <span class="hljs-keyword">install</span> express express-<span class="hljs-keyword">session</span> passport passport-<span class="hljs-keyword">local</span>
</code></pre><h3 id="now-our-project-is-set-up-and-we-are-ready-to-move-to-the-next-step">Now, Our project is set up and we are ready to move to the next step.</h3>
<h2 id="step-1-creating-a-boilerplate-code">Step 1: Creating a Boilerplate Code</h2>
<h3 id="lets-now-create-indexjs-and-write-the-boilerplate-code-for-the-express-app">Lets now create index.js and write the boilerplate code for the express app.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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


app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span>(req.isAuthenticated()){
    res.send(<span class="hljs-string">`Heyyyy <span class="hljs-subst">${req.user.email}</span>`</span>)
  }<span class="hljs-keyword">else</span>{
    res.send(<span class="hljs-string">'Whooo Areee youuuuuu ???'</span>)
  }
});

app.post(<span class="hljs-string">'/login'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">// ...</span>
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server Started at PORT 9000`</span>))
</code></pre>
<h3 id="so-i-hope-that-you-have-got-an-idea-that-what-we-are-going-to-implement">So, I hope that you have got an idea that what we are going to implement.</h3>
<h3 id="in-the-above-code-we-have-two-routes">In the above code we have two routes:</h3>
<ol>
<li><p><strong>Home Route ‘/’: </strong>This route checks if the req.user is present, which means the user is logged in and sends <strong>heyy and email</strong> if so, else it sends a response saying<strong> Heyy how are you?.</strong></p>
</li>
<li><p><strong>Login Route ‘/login’:</strong> This route is a route that we need to implement later. This route is responsible for logging in the user.</p>
</li>
</ol>
<h3 id="now-in-the-next-step-we-would-be-implementing-some-middleware-functions-which-we-need-to-authenticate-the-user">Now, in the next step, we would be implementing some middleware functions which we need to authenticate the user.</h3>
<h2 id="step-2-implementing-middleware-functions">Step 2: Implementing Middleware functions</h2>
<h3 id="to-authenticate-our-user-using-passport-we-need-to-implement-the-following-middleware-functions">To authenticate our user using passport we need to implement the following middleware functions:</h3>
<ol>
<li><p><strong>express-session() — Maintaining Sessions</strong></p>
</li>
<li><p><strong>passport.initialize() — Initialize Passport.js</strong></p>
</li>
<li><p><strong>passport.session() — Using Passport Sessions</strong></p>
</li>
</ol>
<p>With that being set lets import and implement them.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> passport = <span class="hljs-built_in">require</span>(<span class="hljs-string">'passport'</span>);
<span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>);

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


app.use(session({ <span class="hljs-attr">secret</span>: <span class="hljs-string">'mysecret'</span>, <span class="hljs-attr">resave</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">saveUninitialized</span>: <span class="hljs-literal">true</span> }));
app.use(passport.initialize())
app.use(passport.session())

app.use(express.json())

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span>(req.user) {
    res.send(<span class="hljs-string">`Hey There.... You are <span class="hljs-subst">${req.user.email}</span>`</span>)
  }
  <span class="hljs-keyword">else</span>{
    res.send(<span class="hljs-string">'Hey.. I dont know who are you??? '</span>)
  }
})

app.post(<span class="hljs-string">'/login'</span>, passport.authenticate(<span class="hljs-string">'local'</span>), <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Loggin Sucess'</span>)
})


app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server running at 9000`</span>))
</code></pre>
<h2 id="okay-with-that-being-set-lets-move-to-next-step">Okay, With that being set let's move to next step.</h2>
<h2 id="step-3-code-the-passportjs">Step 3: Code the passport.js</h2>
<p>In this step, we would be coding the logic part of passport.js which is really simple.</p>
<p>Step 1: Create a file named as <strong>passport.js</strong> in your project root directory.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072368664/JYk3B0GVD.png" alt /></p>
<p>Step 2: Import <strong>passport-local</strong> Strategy</p>
<pre><code><span class="hljs-keyword">const</span> LocalStrategy = <span class="hljs-keyword">require</span>(<span class="hljs-string">'passport-local'</span>).Strategy;
</code></pre><p>Finally exporting a helper function that accepts passport as a parameter and configures it as a local strategy for us.</p>
<p>It okay for now if you didn't understand the above line.</p>
<h3 id="so-our-passportjs-would-look-something-like-this">So our passport.js would look something like this:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> LocalStrategy = <span class="hljs-built_in">require</span>(<span class="hljs-string">'passport-local'</span>).Strategy;

<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">passport</span>)</span>{
  passport.use(
    <span class="hljs-keyword">new</span> LocalStrategy({<span class="hljs-attr">usernameField</span>: <span class="hljs-string">'email'</span>, <span class="hljs-attr">passwordField</span>: <span class="hljs-string">'password'</span>}, <span class="hljs-function">(<span class="hljs-params">email, password, done</span>) =&gt;</span> {
      <span class="hljs-comment">// ... do the database stuff with email and passsword and get all the details </span>
      <span class="hljs-comment">// of user. In this case I am hardcoding the user.</span>
      <span class="hljs-keyword">const</span> user = {
        email
      }
      <span class="hljs-keyword">if</span>(user){
      done(<span class="hljs-literal">null</span>, user);
      }
      <span class="hljs-keyword">else</span>{
        done(<span class="hljs-literal">null</span>, <span class="hljs-literal">false</span>, {<span class="hljs-attr">message</span>: <span class="hljs-string">"Incorrect Password"</span>});
    })
  )
}
</code></pre>
<h3 id="let-me-simplify-the-above-code">Let me simplify the above code</h3>
<p>In the above code, we are exporting a function that takes passport as a parameter(line #3), After then it calls the use method on the passport that we get from the parameter and passes a new instance of the strategy we want to use (local strategy in this case, the one we imported on the top).</p>
<p><strong>The LocalStrategy instance which is being passed to passport.js(line #5) takes in two parameters:</strong></p>
<ol>
<li><p><strong>Options:</strong> We are passing an option{usernameField: ‘email’, passwordField: ‘password’}, which means that the user would provide his username with a field named as email and password with field named as password.</p>
</li>
<li><p><strong>callback function:</strong> The second argument is a callback function which has access to 3 parameters:</p>
</li>
<li><p><strong>email:</strong> Email Id of the user</p>
</li>
<li><p><strong>password:</strong> Password of the user</p>
</li>
<li><p><strong>done</strong>: We call the done function after we process our logic with email and password to call next middleware.</p>
</li>
</ol>
<p>If we found the user from database and we match the password we call done function with the first parameter as null and second as user object.</p>
<pre><code>done(<span class="hljs-keyword">null</span>, <span class="hljs-keyword">user</span>);
</code></pre><p>If we could not found the user or the password is wrong we call the done function as:</p>
<pre><code><span class="hljs-selector-tag">done</span>(<span class="hljs-selector-tag">null</span>, <span class="hljs-selector-tag">false</span>, {<span class="hljs-attribute">message</span>: <span class="hljs-string">"Incorrect Password or no user found"</span>}
</code></pre><h2 id="step-4-completing-our-login-route">Step 4: Completing our login route</h2>
<p>Before we complete our login route we need to configure our passport js with the help of function we just created in the previous step.</p>
<p>Back to index.js</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> passport = <span class="hljs-built_in">require</span>(<span class="hljs-string">'passport'</span>);
<span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>);

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

<span class="hljs-comment">// Configure the Passport JS</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'./passport'</span>)(passport);

app.use(session({ <span class="hljs-attr">secret</span>: <span class="hljs-string">'mysecret'</span>, <span class="hljs-attr">resave</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">saveUninitialized</span>: <span class="hljs-literal">true</span> }));
app.use(passport.initialize())
app.use(passport.session())

app.use(express.json())


app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span>(req.isAuthenticated()){
    res.send(<span class="hljs-string">`Heyyyy <span class="hljs-subst">${req.user.email}</span>`</span>)
  }<span class="hljs-keyword">else</span>{
    res.send(<span class="hljs-string">'Whooo Areee youuuuuu ???'</span>)
  }
});

app.post(<span class="hljs-string">'/login'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">// ...</span>
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server Started at PORT 9000`</span>))
</code></pre>
<p>After we configure the passport, lets now complete our login route</p>
<pre><code class="lang-javascript">app.post(<span class="hljs-string">'/login'</span>, passport.authenticate(<span class="hljs-string">'local'</span>), <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Login Success'</span>)
})
</code></pre>
<h3 id="yeah-thats-it-your-login-route-is-ready">Yeah! That's it. Your Login route is ready.</h3>
<p>The passport.authenticate(‘local’) would call the function we exported from passport.js and pass the email and password to the Local Strategy we created.</p>
<p>If everything goes well, passport then called the next middleware that is our req, res function where we send a response saying login success.</p>
<h2 id="last-step-serialize-and-deserialize-the-user">Last Step: Serialize and Deserialize the user</h2>
<p>Don’t panic! Serialising and the deserializing user simply means that every time the user makes a request to the server we need to parse the incoming user and set the user value to the req.user object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> LocalStrategy = <span class="hljs-built_in">require</span>(<span class="hljs-string">'passport-local'</span>).Strategy;

<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">passport</span>)</span>{
  passport.use(
    <span class="hljs-keyword">new</span> LocalStrategy({<span class="hljs-attr">usernameField</span>: <span class="hljs-string">'email'</span>}, <span class="hljs-function">(<span class="hljs-params">email, password, done</span>) =&gt;</span> {
      <span class="hljs-comment">// ... do the database stuff with email and passsword and get all the details </span>
      <span class="hljs-comment">// of user. In this case I am hardcoding the user.</span>
      <span class="hljs-keyword">const</span> user = {
        email
      }
      <span class="hljs-keyword">if</span>(user){
      done(<span class="hljs-literal">null</span>, user);
      }
      <span class="hljs-keyword">else</span>{
        done(<span class="hljs-literal">null</span>, <span class="hljs-literal">false</span>, {<span class="hljs-attr">message</span>: <span class="hljs-string">"Incorrect username"</span>});
      }
    })
  )


  passport.serializeUser(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user, done</span>) </span>{
    done(<span class="hljs-literal">null</span>, user.email);
  });


  passport.deserializeUser(<span class="hljs-function">(<span class="hljs-params">email, done</span>) =&gt;</span> {
    <span class="hljs-comment">// Find user by the email from your db</span>
    <span class="hljs-keyword">const</span> user = {
      email,
      <span class="hljs-attr">name</span>: <span class="hljs-string">'Piyush'</span>, <span class="hljs-comment">// In future, this value would come from your db</span>
    }
    done(<span class="hljs-literal">null</span>, user)

  })
}
</code></pre>
<p>Every time the user makes a request to server firstly the Serialize user gets called which has the user that we created before. (passport.js line number #12).</p>
<p>Then this function further calls the deserialize user in which we set the req.user and pass the control to next middleware.</p>
<h2 id="congrats-you-have-learned-how-to-implement-authentication-using-passportjs">Congrats! You have learned how to implement authentication using Passport.js</h2>
<h2 id="lets-test-our-implementation-in-postman"><strong>Let's test our implementation in Postman</strong></h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072370785/N9KxTm91V.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072372796/cGx_wyYG8.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072374740/YHc8QQuyl.png" alt />
<a target="_blank" href="https://medium.com/@gargpiyush195/authentication-in-nodejs-using-json-web-tokens-jwt-936e6c0118ef"><strong>Authentication in Nodejs using JSON web tokens (JWT)</strong>
<em>Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka…</em>medium.com</a>
<a target="_blank" href="https://medium.com/@gargpiyush195/building-rest-api-with-node-js-4420ff6214b6"><strong>Building REST API with Node.js</strong>
<em>Build your own REST API from scratch</em>medium.com</a>
<a target="_blank" href="https://medium.com/@gargpiyush195/top-10-visual-studio-code-extensions-2020-fc5761116443"><strong>Top 10 visual studio code extensions 2020</strong>
<em>Best vscode extensions to make your development smooth and powerful.</em>medium.com</a></p>
<h2 id="social-links">Social Links:</h2>
<p>Github: <a target="_blank" href="https://github.com/piyushgarg195">https://github.com/piyushgarg195</a></p>
<p>Linkedin: <a target="_blank" href="https://www.linkedin.com/in/piyushgarg195/">https://www.linkedin.com/in/piyushgarg195/</a></p>
<p>Website: <a target="_blank" href="https://www.piyushgarg.dev/">https://www.piyushgarg.dev/</a></p>
]]></content:encoded></item><item><title><![CDATA[Top 5 Libraries for Reactjs]]></title><description><![CDATA[In this article, I would be listing the top 5 libraries for React that can make your life easier.
1. Ant Design

Ant Design is a design system for enterprise-level products. Create an efficient and enjoyable work experience. It offers tons and tons o...]]></description><link>https://blog.piyushgarg.dev/top-5-libraries-for-reactjs-42062f812c75</link><guid isPermaLink="true">https://blog.piyushgarg.dev/top-5-libraries-for-reactjs-42062f812c75</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Thu, 23 Apr 2020 18:51:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072234244/eOmNPPJtV.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I would be listing the top 5 libraries for React that can make your life easier.</p>
<h2 id="1-ant-design">1. Ant Design</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072225022/kWRPjE0_S.png" alt /></p>
<p><a target="_blank" href="https://ant.design/">Ant Design</a> is a design system for enterprise-level products. Create an efficient and enjoyable work experience. It offers tons and tons of components with very powerful features.</p>
<h2 id="2-react-bootstrap">2. React Bootstrap</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072227104/2B4oB1JNU.png" alt /></p>
<p>The <a target="_blank" href="https://react-bootstrap.github.io/">React Bootstrap</a> library is exactly what the name describes: Bootstrap components built with React. Bootstrap is an open-source toolkit for developing with HTML, CSS, and JS. Bootstrap is the world’s most popular front-end component library.</p>
<p>What is great about React Bootstrap is that it replaces the old Bootstrap JavaScript. Each component in this library has been built from scratch as a true React component, without unneeded dependencies like jQuery.</p>
<p>As one of the oldest React libraries, React Bootstrap has evolved and grown alongside React, making it a great choice as your UI foundation.</p>
<p>Source: <a target="_blank" href="https://medium.com/@daaaan">Daan</a></p>
<h2 id="3-react-spinners">3. React Spinners</h2>
<p>There is no space any longer for boring spinners in your applications. <a target="_blank" href="https://www.react-spinners.com/">React spinner</a> is a library that offers a wide variety of fancy spinners. The properties of these spinners can be tweaked so you can fully customize the spinners the way you want.</p>
<p>This is a small library that has about 1k stars on GitHub, but it could give your application a real boost in terms of UX.</p>
<p>Source: <a target="_blank" href="https://medium.com/@daaaan">Daan</a></p>
<h2 id="4-evergreen">4. Evergreen</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072229345/jrbGonwRw.png" alt /></p>
<p><a target="_blank" href="https://evergreen.segment.com/">Evergreen</a> provides a <strong>Design System for the Web. </strong>It provided various pre-build components with great UI. It would be worth checking out.</p>
<h2 id="5-webix">5. Webix</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072231788/xNQqEacEN.png" alt /></p>
<p><a target="_blank" href="https://webix.com/">Webix</a> is yet another and very advance UI library that provides you UI for building complex and heavy web applications on a Large Scale.
<a target="_blank" href="https://medium.com/@gargpiyush195/top-10-visual-studio-code-extensions-2020-fc5761116443"><strong>Top 10 visual studio code extensions 2020</strong>
<em>Best vscode extensions to make your development smooth and powerful.</em>medium.com</a>
<a target="_blank" href="https://medium.com/@gargpiyush195/building-rest-api-with-node-js-4420ff6214b6"><strong>Building REST API with Node.js</strong>
<em>Build your own REST API from scratch</em>medium.com</a>
<a target="_blank" href="https://medium.com/@gargpiyush195/authentication-in-nodejs-using-json-web-tokens-jwt-936e6c0118ef"><strong>Authentication in Nodejs using JSON web tokens (JWT)</strong>
<em>Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka…</em>medium.com</a></p>
<h2 id="social-links">Social Links:</h2>
<p>Github: <a target="_blank" href="https://github.com/piyushgarg195">https://github.com/piyushgarg195</a></p>
<p>Linkedin: <a target="_blank" href="https://www.linkedin.com/in/piyushgarg195/">https://www.linkedin.com/in/piyushgarg195/</a></p>
<p>Website: <a target="_blank" href="https://www.piyushgarg.dev/">https://www.piyushgarg.dev/</a></p>
]]></content:encoded></item><item><title><![CDATA[Authentication in Nodejs using JSON web tokens (JWT)]]></title><description><![CDATA[Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka JSON web tokens
What are JSON web tokens?
JSON web tokens or JWT is a simple long string that contains some data in an encoded way. S...]]></description><link>https://blog.piyushgarg.dev/authentication-in-nodejs-using-json-web-tokens-jwt-936e6c0118ef</link><guid isPermaLink="true">https://blog.piyushgarg.dev/authentication-in-nodejs-using-json-web-tokens-jwt-936e6c0118ef</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Thu, 23 Apr 2020 16:38:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072271917/W0ux7VnL5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there, In this article, we would be learning how to implement authentication in nodejs using express and <strong>JWT aka JSON web tokens</strong></p>
<h2 id="what-are-json-web-tokens">What are JSON web tokens?</h2>
<p>JSON web tokens or JWT is a simple long string that contains some data in an encoded way. Sounds confusing? here is an example</p>
<h3 id="a-sample-jwt-string-may-look-like">A Sample JWT String may look like:</h3>
<pre><code><span class="hljs-attribute">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9</span>.eyJuYW<span class="hljs-number">1</span>lIjoiUGl<span class="hljs-number">5</span>dXNoIEdhcmciLCJlbWFpbCI<span class="hljs-number">6</span>ImluZm<span class="hljs-number">9</span>AcGl<span class="hljs-number">5</span>dXNoZ<span class="hljs-number">2</span>FyZy<span class="hljs-number">5</span>kZXYiLCJpYXQiOjE<span class="hljs-number">1</span>MTYyMzkwMjJ<span class="hljs-number">9</span>.XaQC<span class="hljs-number">6</span>iMAgESX<span class="hljs-number">8</span>b-HT<span class="hljs-number">2</span>AkclCAWDnAmNiHV<span class="hljs-number">7</span>tq<span class="hljs-number">7</span>b<span class="hljs-number">6</span>GWRE
</code></pre><h3 id="now-lets-decode-the-above-jwt-string">Now, Let’s decode the above JWT string</h3>
<blockquote>
<p>You can decode the string by visiting <a target="_blank" href="https://jwt.io/">https://jwt.io/</a> and paste the above string into the debugger present on the mentioned link.</p>
</blockquote>
<pre><code>{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Piyush Garg"</span>,
  <span class="hljs-attr">"email"</span>: <span class="hljs-string">"info@piyushgarg.dev"</span>,
  <span class="hljs-attr">"iat"</span>: <span class="hljs-number">1516239022</span>
}
</code></pre><h3 id="so-i-hope-that-now-you-have-a-simple-idea-that-what-json-web-tokens-are">So, I hope that now you have a simple idea that what JSON web tokens are!</h3>
<h2 id="now-with-that-being-set-lets-create-an-express-application-and-implement-authentication-with-jwt">Now, with that being set let's create an express application and implement authentication with JWT</h2>
<p>I'll be guiding you step by step and I would highly recommend you to code along with me.</p>
<h2 id="step-0-creating-a-boilerplate-code">Step 0: Creating a boilerplate code.</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>)
<span class="hljs-keyword">const</span> app = express();

app.use(express.json())
app.use(cookieParser())

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>)
})

app.get(<span class="hljs-string">'/profile'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Hello'</span>)
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<p>A very basic express starter code. We would be protecting the<strong> ‘/profile’</strong> route so that only logged in users can access that route.</p>
<h2 id="step-1-installing-dependencies">Step 1: Installing Dependencies</h2>
<p>For this project, we would be installing a few dependencies.</p>
<ol>
<li><p>Express</p>
</li>
<li><p>jsonwebtoken</p>
</li>
<li><p>cookie-parser</p>
</li>
</ol>
<h3 id="run-the-following-command-in-your-terminal-or-command-prompt">Run the following command in your terminal or command prompt:</h3>
<pre><code>npm install express jsonwebtoken cookie-<span class="hljs-keyword">parser</span>
</code></pre><h2 id="step-2-creating-middleware-functions-to-deal-with-tokens">Step 2: Creating Middleware functions to deal with tokens</h2>
<p>In this step, we would be creating functions which would be used as middlewares to protect our certain routes.</p>
<h3 id="trust-me-its-really-simple">Trust me it's really simple 😉</h3>
<h2 id="creating-authjs">Creating auth.js</h2>
<h3 id="so-create-a-new-js-file-in-your-project-directory-lets-call-it-as-authjs-in-this-file-we-would-be-creating-functions-that-we-need-to-deal-with-tokens">So, Create a new .js file in your project directory. Lets call it as auth.js. In this file, we would be creating functions that we need to deal with tokens.</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072259725/98fxfSHV-.png" alt /></p>
<h3 id="great-going-now-lets-create-a-couple-of-functions">Great going, Now let's create a couple of functions</h3>
<ol>
<li><p><strong>generateToken()</strong>: This function would take data as a parameter and return the token after generating it.</p>
</li>
<li><p><strong>isLoggedIn()</strong>: This function is responsible for checking if the current user is logged in or not.</p>
</li>
</ol>
<h3 id="yeah-thats-it-lets-codeee">Yeah! That's it. Lets Codeee 🤟🏻</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateToken</span>(<span class="hljs-params">payload</span>) </span>{
  <span class="hljs-keyword">const</span> token = jwt.sign(payload, <span class="hljs-string">'mySecretKey'</span>);
  <span class="hljs-keyword">return</span> token;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLoggedIn</span>(<span class="hljs-params">req, res, next</span>) </span>{

  <span class="hljs-comment">// Check if the user has token in cookies. If not return the request;</span>
  <span class="hljs-keyword">if</span>(!req.cookies.jwt) <span class="hljs-keyword">return</span> res.json({ <span class="hljs-attr">error</span>: <span class="hljs-string">'Please Login'</span> });

  <span class="hljs-keyword">const</span> clientToken = req.cookies.jwt;

 <span class="hljs-keyword">try</span> {
  <span class="hljs-comment">//  Decode the client token by using same secret key that we used to sign the token</span>
    <span class="hljs-keyword">const</span> decoded = jwt.verify(clientToken, <span class="hljs-string">'mySecretKey'</span>);
    req.user = decoded;
     next();
 }
 <span class="hljs-keyword">catch</span>(err){
    <span class="hljs-keyword">return</span> res.json({<span class="hljs-attr">error</span>: <span class="hljs-string">'Invalid Token'</span>})
 }

}

<span class="hljs-built_in">module</span>.exports = {
  generateToken,
  isLoggedIn
}
</code></pre>
<p>In auth.js we have created two functions as mentioned above. Please go through the code and you would understand the flow behind it.</p>
<h3 id="yep-thats-it-now-lets-protect-our-routes">Yep, that's it. Now let's protect our routes</h3>
<p>Back to index.js let's create two routes <strong>signup route</strong> and<strong> login route</strong>.</p>
<p>In this article, I’ll be coding only the signup route.</p>
<p><strong>Your assignment is to create the login route.</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>)
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// Import auth.js that we created earlier</span>
<span class="hljs-keyword">const</span> auth = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./auth'</span>);


app.use(express.json())
app.use(cookieParser())

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Welcome to my API'</span>)
})

app.get(<span class="hljs-string">'/profile'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'Hello'</span>)
})

app.post(<span class="hljs-string">'/signup'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> {name, email, password} = req.body;
  <span class="hljs-comment">// .. code to save user in database</span>

  <span class="hljs-comment">// Now lets generate token and give it to user as a cookie</span>
  <span class="hljs-keyword">const</span> payload = {
    name,
    email
  }
  <span class="hljs-keyword">const</span> token = auth.generateToken(payload);
  res.cookie(<span class="hljs-string">'jwt'</span>, token);
  <span class="hljs-keyword">return</span> res.redirect(<span class="hljs-string">'/profile'</span>)
})

app.listen(<span class="hljs-number">9000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started at PORT 9000'</span>))
</code></pre>
<h2 id="step-3-lets-protect-our-route">Step 3: let's protect our route</h2>
<p>To protect your route, just call the isLoggedIn function as middleware before the route that you want to protect and that's it.</p>
<p>Updated profile route:</p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/profile'</span>, auth.isLoggedIn, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">`Hello <span class="hljs-subst">${req.user.name}</span>`</span>);
})
</code></pre>
<p><strong>req.user</strong> holds the current user which is logged in. Navigate to auth.js line number 18:</p>
<pre><code><span class="hljs-attr">req.user</span> = decoded<span class="hljs-comment">;</span>
</code></pre><p>This is where we set the value of req.user to the current user.</p>
<blockquote>
<p>Value of req.user is exactly the same as we defined the payload while generating the token.</p>
</blockquote>
<h2 id="finally-lets-test-our-implementation-in-postman">Finally: Let's test our implementation in postman</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072261951/JpLx0PZcD.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072263973/GdIXMenNV.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072266095/e_gGzMJg7.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072268035/4Z_Twlpso.png" alt /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072269974/SLGqDhZ2V.png" alt /></p>
<h2 id="congratulations-you-have-now-learned-how-to-do-authentication-in-nodejs-using-jwt">Congratulations! 😍 You have now learned how to do authentication in nodejs using JWT</h2>
<p><a target="_blank" href="https://medium.com/@gargpiyush195/building-rest-api-with-node-js-4420ff6214b6"><strong>Building REST API with Node.js</strong>
<em>Build your own REST API from scratch</em>medium.com</a>
<a target="_blank" href="https://medium.com/@gargpiyush195/top-10-visual-studio-code-extensions-2020-fc5761116443"><strong>Top 10 visual studio code extensions 2020</strong>
<em>Best vscode extensions to make your development smooth and powerful.</em>medium.com</a>
<a target="_blank" href="https://medium.com/@gargpiyush195/how-to-create-a-vs-code-extension-c41314ef5a67"><strong>How to create a VS Code extension</strong>
<em>Hi there, in this article we would be creating an extension for VS Code and publishing it to the vscode marketplace.</em>medium.com</a></p>
<h3 id="social-links">Social Links:</h3>
<p>Github: <a target="_blank" href="https://github.com/piyushgarg195">https://github.com/piyushgarg195</a></p>
<p>Linkedin: <a target="_blank" href="https://www.linkedin.com/in/piyushgarg195/">https://www.linkedin.com/in/piyushgarg195/</a></p>
<p>Website: <a target="_blank" href="https://www.piyushgarg.dev/">https://www.piyushgarg.dev/</a></p>
]]></content:encoded></item><item><title><![CDATA[How to create a VS Code extension]]></title><description><![CDATA[Hi there, in this article we would be creating an extension for VS Code and publishing it to the vscode marketplace.
Excited about that 🥰? Lets Start
What we are going to create?
We would be building an auto-complete extension that auto-completes th...]]></description><link>https://blog.piyushgarg.dev/how-to-create-a-vs-code-extension-c41314ef5a67</link><guid isPermaLink="true">https://blog.piyushgarg.dev/how-to-create-a-vs-code-extension-c41314ef5a67</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Wed, 22 Apr 2020 17:18:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072404831/hWHOI4kGu.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hi there, in this article we would be creating an extension for VS Code and publishing it to the vscode marketplace.</p>
<h2 id="excited-about-that-lets-start">Excited about that 🥰? Lets Start</h2>
<h2 id="what-we-are-going-to-create">What we are going to create?</h2>
<p>We would be building an auto-complete extension that auto-completes the bootstrap snippets in an Html file.</p>
<h3 id="prerequisites">Prerequisites</h3>
<p>You must have node.js installed on your machine.</p>
<h2 id="step-1-install-yo">Step 1. Install Yo! 🤟🏻</h2>
<p>Yes, you read that correctly. We have to install yo to create our vscode extension.</p>
<p>To install yo fire-up your terminal or command prompt.</p>
<blockquote>
<p>Note: Windows users please open your command prompt as an administrator.</p>
</blockquote>
<p>After being set type in the following command:</p>
<h3 id="macos">macOS:</h3>
<pre><code>sudo <span class="hljs-built_in">npm</span> install -g yo
</code></pre><h3 id="windows">Windows:</h3>
<pre><code><span class="hljs-built_in">npm</span> install -g yo
</code></pre><h2 id="yo-you-have-successfully-installed-yo">Yo! you have successfully installed Yo 🎉</h2>
<h2 id="step-2-project-setup">Step 2: Project setup</h2>
<p>Setting up the project is really simple.</p>
<p>All you need to do is:</p>
<ol>
<li><p>Create a new folder. Let us say “<strong>myFirstExtension</strong>”</p>
</li>
<li><p>Open your terminal or command prompt and navigate to the folder we have just created.</p>
</li>
<li><p>Run the following command</p>
</li>
</ol>
<pre><code><span class="hljs-attribute">yo</span> code
</code></pre><h3 id="at-this-step-vscode-extension-generator-would-show-up">At this step, vscode extension generator would show up</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072382868/KxEBhT6-D.png" alt /></p>
<h3 id="from-the-given-options-choose-new-code-snippets-to-create-an-auto-complete-snippets-extension">From the given options choose New Code Snippets to create an auto-complete snippets extension.</h3>
<p>After that being done, you would be prompted with some questions such as the name of the extension, description etc.</p>
<h3 id="also-there-would-be-a-prompt-saying">Also, there would be a prompt saying</h3>
<p>“<em>Enter the language for which the snippets should appear. The id is an identifier and is a single, lower-case name such as ‘PHP’, ‘javascript</em>”</p>
<p>Type in <strong>html</strong> for this as we are creating snippets for HTML</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072385136/pG4gaafql.png" alt /></p>
<h2 id="hora-you-have-successfully-set-up-the-project-and-we-are-now-ready-to-code-our-extension">Hora 🎉 ! You have successfully set up the project and we are now ready to code our extension.</h2>
<h2 id="step-3-code-the-extension">Step 3: Code the extension.</h2>
<p>Now you may close your terminals and command prompts and open the folder we created in the previous step. There you will notice a folder created with the name of your extension. Open this folder inside your favourite code editor. Like vscode in my case.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072386871/jG5e4D6ke.png" alt /></p>
<h3 id="now-head-over-to-snippets-folder-and-open-snippetsjson-file">Now, head over to snippets folder and open snippets.json file.</h3>
<p>At this point, your snippets.json file would we something like this</p>
<pre><code>{}
</code></pre><p>Yep, it’s an empty object and we have to code our snippets inside this object.</p>
<h2 id="lets-code">Lets Code!</h2>
<p>Code along with me:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"start"</span>:{
     <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"!start"</span>,
      <span class="hljs-attr">"body"</span>: [
        <span class="hljs-string">"&lt;html&gt;"</span>,
        <span class="hljs-string">"&lt;/html"</span>
      ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Basic Starter Template"</span>
  }
}
</code></pre>
<pre><code>prefix: what <span class="hljs-keyword">user</span> would <span class="hljs-keyword">type</span> <span class="hljs-keyword">to</span> <span class="hljs-keyword">access</span> the snippet

body: the body <span class="hljs-keyword">of</span> the snippet. <span class="hljs-keyword">In</span> this <span class="hljs-keyword">case</span> <span class="hljs-keyword">Array</span> <span class="hljs-keyword">of</span> HTML tags
</code></pre><h3 id="yes-that-it-we-have-successfully-created-our-first-snippet">Yes that it! We have successfully created our first snippet.</h3>
<p>So whenever users types “!start” in vscode the body of our snippet would be printed there.</p>
<h3 id="you-can-create-multiple-snippets-by-adding-more-objects-to-the-main-object">You can Create multiple snippets by adding more objects to the main object</h3>
<pre><code class="lang-json">{
  <span class="hljs-attr">"start"</span>:{
     <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"!start"</span>,
      <span class="hljs-attr">"body"</span>: [
        <span class="hljs-string">"&lt;html&gt;"</span>,
        <span class="hljs-string">"&lt;/html"</span>
      ],
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Basic Starter Template"</span>
  },
  <span class="hljs-attr">"h1"</span>:{
    <span class="hljs-attr">"prefix"</span>: <span class="hljs-string">"!h1"</span>,
    <span class="hljs-attr">"body"</span>: [
        <span class="hljs-string">"&lt;h1&gt;"</span>,
        <span class="hljs-string">"&lt;/h1"</span>
      ],
     <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Basic html tag"</span>
  }
}
</code></pre>
<h2 id="wola-you-have-created-your-own-very-first-extension">Wola! You have created your own very first extension 🥰</h2>
<p>Just keep adding your snippets and create some great snippets.</p>
<p><strong>Please post your extension links below because I cant wait to see what you have made.</strong></p>
<h3 id="complete-bootstrap-snippets-code">Complete Bootstrap Snippets Code</h3>
<p><a target="_blank" href="https://gist.github.com/piyushgarg195/36fda82a1662e04618a34afbca293830">https://gist.github.com/piyushgarg195/36fda82a1662e04618a34afbca293830</a></p>
<h2 id="step-4-configuring-the-extension">Step 4: Configuring the Extension</h2>
<p>At this point, you have successfully created your vscode extension.</p>
<p>Now open <strong>package.json</strong> file present in your project folder.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"bootstrap-snippets"</span>,
    <span class="hljs-attr">"displayName"</span>: <span class="hljs-string">"bootstrap-snippets"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A simple Bootstrap snippets"</span>,
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.0.1"</span>,
    <span class="hljs-attr">"engines"</span>: {
        <span class="hljs-attr">"vscode"</span>: <span class="hljs-string">"^1.44.0"</span>
    },
    <span class="hljs-attr">"categories"</span>: [
        <span class="hljs-string">"Snippets"</span>
    ],
    <span class="hljs-attr">"contributes"</span>: {
        <span class="hljs-attr">"snippets"</span>: [
            {
                <span class="hljs-attr">"language"</span>: <span class="hljs-string">"html"</span>,
                <span class="hljs-attr">"path"</span>: <span class="hljs-string">"./snippets/snippets.json"</span>
            }
        ]
    }
}
</code></pre>
<p>In this file, we need to make a few changes as listed below:</p>
<h3 id="1-adding-publisher-name-in-packagejson">1. Adding Publisher name in package.json</h3>
<pre><code class="lang-json">{
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"bootstrap-snippets"</span>,
    <span class="hljs-attr">"displayName"</span>: <span class="hljs-string">"bootstrap-snippets"</span>,
    <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A simple Bootstrap snippets"</span>,
    <span class="hljs-attr">"publisher"</span>: <span class="hljs-string">"piyushgarg"</span>,
    <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.0.1"</span>,
    <span class="hljs-attr">"engines"</span>: {
        <span class="hljs-attr">"vscode"</span>: <span class="hljs-string">"^1.44.0"</span>
    },
    <span class="hljs-attr">"categories"</span>: [
        <span class="hljs-string">"Snippets"</span>
    ],
    <span class="hljs-attr">"contributes"</span>: {
        <span class="hljs-attr">"snippets"</span>: [
            {
                <span class="hljs-attr">"language"</span>: <span class="hljs-string">"html"</span>,
                <span class="hljs-attr">"path"</span>: <span class="hljs-string">"./snippets/snippets.json"</span>
            }
        ]
    }
}
</code></pre>
<h2 id="2-updating-readmemd-file">2. Updating Readme.md file</h2>
<p>This file is the documentation of your extension. You need to edit this file before publishing your extension.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072388895/aFA5Yuwje.png" alt /></p>
<h2 id="finally-lets-publish-our-extension">Finally: let's publish our extension</h2>
<p>To publish your extension first you need to download vse tool by writing a command</p>
<h3 id="macos">macOS</h3>
<pre><code>sudo <span class="hljs-built_in">npm</span> install -g vsce
</code></pre><h3 id="windows-open-command-prompt-as-administrator">Windows ( open command prompt as administrator)</h3>
<pre><code><span class="hljs-built_in">npm</span> install -g vsce
</code></pre><h3 id="now-after-installing-vse-navigate-to-your-extension-directory-and-open-that-directory-in-terminal-or-command-prompt-and-type-the-following-command">Now, after installing vse, navigate to your extension directory and open that directory in terminal or command prompt and type the following command</h3>
<pre><code>vsce <span class="hljs-keyword">package</span>
</code></pre><p>After this you would be prompted with a message saying</p>
<p><em>“A ‘repository’ field is missing from the ‘package.json’ manifest file.
Do you want to continue? [y/N]”</em></p>
<h3 id="hit-y-and-press-enter">Hit ‘y’ and press enter.</h3>
<p>This would create &lt;extension_name&gt;.vsix file</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072390790/Jww1Max8D.png" alt /></p>
<h2 id="congratulation-you-are-now-ready-to-publish-it">Congratulation! you are now ready to publish it.</h2>
<ul>
<li><p>Head over to <a target="_blank" href="https://marketplace.visualstudio.com/vscode">**https://marketplace.visualstudio.com/vscode</a> **and create your free account.</p>
</li>
<li><p>After signing select <strong>publish extensions </strong>from the top right corner.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072392808/Gk8pJdlDg.png" alt /></p>
<ul>
<li>Create a publisher<blockquote>
<p><strong>Note: Please make sure that the publisher name in package.json is same as you create a publisher here.</strong></p>
</blockquote>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072394866/YFCKHGoaP.png" alt /></p>
<ul>
<li>Select <strong>+ Create new extension</strong> and select <strong>visual studio</strong> from the dropdown</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072396984/6a6i-488J.png" alt /></p>
<ul>
<li>Upload your .vsix extension</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072399106/Su2bVDx6c.png" alt /></p>
<ul>
<li>Click Continue</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072401251/7Q8R6Bfuk.png" alt /></p>
<h2 id="congrats-your-extension-is-now-published">Congrats! Your extension is now published! 😍</h2>
<h3 id="do-visit">Do visit:</h3>
<p><a target="_blank" href="https://medium.com/@gargpiyush195/top-10-visual-studio-code-extensions-2020-fc5761116443"><strong>Top 10 visual studio code extensions 2020</strong>
<em>Best vscode extensions to make your development smooth and powerful.</em>medium.com</a></p>
]]></content:encoded></item><item><title><![CDATA[Building REST API with Node.js]]></title><description><![CDATA[A few years back, the only way to run a javascript code was in web browsers. But after the birth of Nodejs, we could run javascript code outside of the web browser.
Node.js provides a run time environment to run javascript code. It is built on the ch...]]></description><link>https://blog.piyushgarg.dev/building-rest-api-with-node-js-4420ff6214b6</link><guid isPermaLink="true">https://blog.piyushgarg.dev/building-rest-api-with-node-js-4420ff6214b6</guid><dc:creator><![CDATA[Piyush Garg]]></dc:creator><pubDate>Wed, 22 Apr 2020 09:52:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072362032/SU_ZKUY4N.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A few years back, the only way to run a javascript code was in web browsers. But after the birth of Nodejs, we could run javascript code outside of the web browser.</p>
<p><strong>Node.js</strong> provides a run time environment to run javascript code. It is built on the <a target="_blank" href="https://v8.dev/">chrome’s open-source V8 engine.</a></p>
<p>After being said that let's build a real REST API in Node.js &amp; Express from scratch.</p>
<p>I'll be guiding you step by step with a detailed explanation from installing node to building our restful API.</p>
<h3 id="now-what-is-an-api">Now, What is an API? 🤷🏻‍♂️</h3>
<p>API stands for <strong>A</strong>pplication<strong> P</strong>rogramming <strong>I</strong>nterface. Yes I know it’s too much jargon.</p>
<h3 id="in-simple-terms-api-is-a-service-that-is-used-to-deliver-data-and-the-content-between-the-server-and-the-client"><strong>In simple terms, API is a service that is used to deliver data and the content between the server and the client.</strong></h3>
<h2 id="so-lets-build-our-very-first-api">So let’s build our very first API 😍</h2>
<h2 id="step-1-download-and-install-nodejs">Step 1. Download and Install Node.js</h2>
<p>To download and install node js on your machine, head over to <a target="_blank" href="https://nodejs.org/en/">https://nodejs.org/en/</a> and select your download version.</p>
<p><strong>There are two types of download version:</strong></p>
<ol>
<li><p>LTS — Long Term Support</p>
</li>
<li><p>Current Version</p>
</li>
</ol>
<h3 id="in-this-tutorial-i-would-recommend-you-to-download-the-lts-version-as-its-more-stable">In this tutorial, I would recommend you to download the LTS version as it’s more stable.</h3>
<h3 id="download-link-httpsnodejsorgenhttpsnodejsorgen">Download Link: <a target="_blank" href="https://nodejs.org/en/">https://nodejs.org/en/</a></h3>
<p>To Verify your installation open your terminal (macOS) or Command Prompt (Windows) and type <strong>“<em>node — version”. </em></strong>This will show your current installed version of nodejs on your machine.</p>
<h3 id="congrats-you-have-successfully-installed-nodejs-on-your-machine">Congrats! you have successfully installed nodejs on your machine.</h3>
<h2 id="step-2-setting-up-the-project-folder">Step 2: Setting up the project folder</h2>
<p>After you have successfully installed node on your machine, lets set up our project structure for building API.</p>
<h3 id="step-1-create-a-new-folder-lets-name-it-as-myapi">Step 1: Create a new folder, let's name it as “myApi”</h3>
<h3 id="step-2-open-terminal-or-command-prompt-and-navigate-to-the-recently-created-folder-ie-myapi">Step 2: Open terminal or command prompt and navigate to the recently created folder i.e “myApi”.</h3>
<h2 id="step-3-setting-up-packagejson">Step 3: Setting up package.json</h2>
<p>Every node project has a file named as package.json. This file contains some configs and names about your project. This file also keeps the track of the dependencies and packages used in our project.</p>
<p>To create a package.json, In your terminal or command prompt type</p>
<pre><code>npm <span class="hljs-keyword">init</span>
</code></pre><p>in your project folder and press enter. At this step, npm would ask you some questions like name, description, etc. Keep pressing enter key to accept all at default names.</p>
<h3 id="now-you-have-successfully-created-your-own-packagejson-file">Now you have successfully created your own package.json file.</h3>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"myapi"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>
}
</code></pre>
<blockquote>
<p>Please do verify that package.json is created inside the folder.</p>
</blockquote>
<h3 id="create-an-indexjs-file">Create an index.js file</h3>
<blockquote>
<p>Note: If you had a look on to our <strong>package.json</strong> file, there is a key named as “main” and value is “index.js”, which means that index.js is the entry point of our application. So we need to create an <strong>index.js</strong> file in our<strong> project directory</strong>.</p>
</blockquote>
<p>Our Project Structure:</p>
<pre><code>myApi
|- <span class="hljs-keyword">index</span>.js
|- package.json
</code></pre><h3 id="huraa-our-project-is-now-set-up-and-we-can-finally-move-on-to-code-our-api">Huraa! 🎉 our project is now set up and we can finally move on to code our API.</h3>
<h2 id="step-4-install-dependencies">Step 4: Install dependencies</h2>
<p>Before we get started to code our API we need to install some dependencies in our project.</p>
<p>Installing dependencies is really simple. All you need to type is a command in your terminal or command prompt.</p>
<h3 id="for-this-project-we-need-a-dependency-ie-expressjs">For this project, we need a dependency i.e express.js</h3>
<p>Command:</p>
<pre><code><span class="hljs-built_in">npm</span> install express
</code></pre><blockquote>
<p><a target="_blank" href="https://expressjs.com/">Express</a> is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.</p>
</blockquote>
<p>At this point a <strong>package.lock</strong> and <strong>node_modules</strong> folder would be created in your project directory. <strong>node_modules</strong> folder contains the source code of your all the dependencies that you install (express in our case).</p>
<h2 id="step-5-lets-code">Step 5: Lets Code! 💻</h2>
<p>Open your index.js file and code along with me.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import the Express using require() module</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);

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

<span class="hljs-comment">// Lets create Fake Data for api</span>
<span class="hljs-keyword">const</span> userData = [
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Jhon'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">20</span>
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">23</span>
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Tim'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">34</span>
  },
];

<span class="hljs-comment">// Create Endpoints for API</span>

<span class="hljs-comment">// Endpoint 1</span>
app.get(<span class="hljs-string">'/api'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  res.send(<span class="hljs-string">'Welcome to our API'</span>)
})

<span class="hljs-comment">// Endpoint 2</span>
app.get(<span class="hljs-string">'/api/users'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  res.json(userData);
})

<span class="hljs-comment">// Endpoint 3</span>
app.get(<span class="hljs-string">'/api/user/:id'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  <span class="hljs-keyword">const</span> id = req.params.id;
  <span class="hljs-keyword">const</span> user = userData.find(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id == id);

  <span class="hljs-keyword">if</span> (user) {
    res.json(user)
  }
  <span class="hljs-keyword">else</span> {
    res.send(<span class="hljs-string">'No User Found'</span>)
  }
})

<span class="hljs-comment">// Start the Server</span>
<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">3000</span>;
app.listen(PORT, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started'</span>)
})
</code></pre>
<p>So firstly we will import express in our application using require() function and store it into a variable express.</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-keyword">require</span>(<span class="hljs-string">'express'</span>)
</code></pre><p>Now, the express module that we have just imported returns a function which we can store into a different variable. By convention it is named as an app;</p>
<pre><code><span class="hljs-keyword">const</span> app = express()
</code></pre><p>Great going! Now let's create a fake array of users which we would serve to our clients as an API.</p>
<pre><code><span class="hljs-string">const</span> <span class="hljs-string">userData</span> <span class="hljs-string">=</span> [

{

<span class="hljs-attr">id:</span> <span class="hljs-number">1</span>,

<span class="hljs-attr">name:</span> <span class="hljs-string">'Jhon'</span>,

<span class="hljs-attr">age:</span> <span class="hljs-number">20</span>

},

{

<span class="hljs-attr">id:</span> <span class="hljs-number">2</span>,

<span class="hljs-attr">name:</span> <span class="hljs-string">'Jane'</span>,

<span class="hljs-attr">age:</span> <span class="hljs-number">23</span>

},

{

<span class="hljs-attr">id:</span> <span class="hljs-number">3</span>,

<span class="hljs-attr">name:</span> <span class="hljs-string">'Tim'</span>,

<span class="hljs-attr">age:</span> <span class="hljs-number">34</span>

},

]<span class="hljs-string">;</span>
</code></pre><p>Feel free to add more users or data. 😉</p>
<h3 id="now-we-are-finally-ready-to-create-our-api-endpoints">Now we are finally ready to create our API Endpoints</h3>
<p>An API endpoint is a URL where users can access to our API.</p>
<p>Creating Endpoints (also known as routes) is really simple.</p>
<p>Syntax: <strong>app.&lt;Request_Method&gt;(‘ Endpoint ’, callback function)</strong></p>
<p>Example: Suppose we want an endpoint named as posts that accept GET requests.</p>
<pre><code>app.get(<span class="hljs-string">'/posts'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  <span class="hljs-comment">// ... do stuff !</span>
})
</code></pre><p>The callback function has access to two parameters i.e <strong>Request</strong> and <strong>Response</strong> respectively.</p>
<p>So now you know how to create endpoints lets create some for our API.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Endpoint 1</span>
app.get(<span class="hljs-string">'/api'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  res.send(<span class="hljs-string">'Welcome to our API'</span>)
})

<span class="hljs-comment">// Endpoint 2</span>
app.get(<span class="hljs-string">'/api/users'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  res.json(userData);
})

<span class="hljs-comment">// Endpoint 3</span>
app.get(<span class="hljs-string">'/api/user/:id'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>)</span>{
  <span class="hljs-keyword">const</span> id = req.params.id;
  <span class="hljs-keyword">const</span> user = userData.find(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.id === id);

  <span class="hljs-keyword">if</span> (user) {
    res.json(user)
  }
  <span class="hljs-keyword">else</span> {
    res.send(<span class="hljs-string">'No User Found'</span>)
  }
})
</code></pre>
<p>Now, please pay a little attention to endpoint 3.</p>
<pre><code>app.<span class="hljs-keyword">get</span>(‘/api/<span class="hljs-keyword">user</span>/:id’, <span class="hljs-keyword">function</span>(req, res){
})
</code></pre><p>Here “<strong>: id”</strong> at the end of the endpoint is a parameter.</p>
<p>Suppose user types <a target="_blank" href="http://www.example.com/api/user/1">**www.example.com/api/user/1</a>, **then the value of id would be equal to 1. you got the point!</p>
<p>We can access these parameters by typing req.params.id where req is the request which we received from the first parameter of the call back;</p>
<p>app.get(‘/example’, function(<strong>req</strong>, res){}) ;</p>
<h3 id="sending-response">Sending Response</h3>
<p>To send a response to the client we use the res parameter.</p>
<pre><code><span class="hljs-selector-tag">res</span><span class="hljs-selector-class">.send</span>(“Hey There”);
</code></pre><p><strong>or JSON Response</strong></p>
<pre><code>res.json(<span class="hljs-keyword">object</span>);
</code></pre><p>In the end, we have to start our server by listening to some PORT and trust me this is also really simple.</p>
<p>Just use .listen function that accepts two parameters, PORT number and a callback function (which gets called when our server starts).</p>
<pre><code>app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server Started'</span>);
})
</code></pre><p>In our example, we have used 3000 as our PORT number.</p>
<h2 id="congratulations-now-lets-start-our-application">Congratulations 🎉! Now let's start our application</h2>
<p>To start your server type</p>
<pre><code>node <span class="hljs-keyword">index</span>.js
</code></pre><p>in command prompt or terminal and your server would get started.</p>
<h2 id="lets-test-our-api">Let's test our API</h2>
<p>Navigate to your favourite web browser and visit <strong>localhost:3000/api</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072356124/tcrNURiq3.png" alt /></p>
<h3 id="now-lets-test-the-users-api-endpoint">Now let's test the users API endpoint.</h3>
<p>Visit: <strong>localhost:3000/api/users</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072358333/LJkJBSGRI.png" alt /></p>
<h3 id="last-but-not-the-least-lets-test-our-endpoint-three">Last but not the least, let's test our endpoint three</h3>
<p>Visit: <strong>localhost:3000/api/user/&lt;id&gt;</strong></p>
<blockquote>
<p>Example: l<strong>ocalhost:3000/api/user/2</strong></p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621072360095/fvbuulz3N.png" alt /></p>
<h2 id="congrats-you-have-build-your-very-own-first-api">Congrats! 😍 You have build your very own first API.</h2>
<p>Follow me on social media:</p>
<p>Github: <a target="_blank" href="https://github.com/piyushgarg195">piyushgarg195</a></p>
<p>Linkedin: <a target="_blank" href="https://www.linkedin.com/in/piyushgarg195/">Piyush Garg</a></p>
]]></content:encoded></item></channel></rss>