<?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[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://blog.omprakashpandey.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 18:17:28 GMT</lastBuildDate><atom:link href="https://blog.omprakashpandey.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Docker Networking Guide for Developers]]></title><description><![CDATA[In our Docker journey so far, we’ve built and run containers for everything from Express applications to lightweight BusyBox shells. But one thing we haven’t really explored in detail is this: how do Docker containers actually connect to the internet...]]></description><link>https://blog.omprakashpandey.com/docker-networking-guide-for-developers</link><guid isPermaLink="true">https://blog.omprakashpandey.com/docker-networking-guide-for-developers</guid><category><![CDATA[Docker]]></category><category><![CDATA[dockernetworking]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Tue, 15 Jul 2025 11:11:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752578606519/a55c225c-c761-41f9-ad61-e8ca466377ec.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In our Docker journey so far, we’ve built and run containers for everything from Express applications to lightweight BusyBox shells. But one thing we haven’t really explored in detail is this: <strong>how do Docker containers actually connect to the internet or to each other?</strong></p>
<p>In this blog, we'll break down Docker networking in a developer-friendly way.</p>
<p>Let’s dive in.</p>
<h2 id="heading-does-my-container-have-internet-access">🧪 Does My Container Have Internet Access?</h2>
<p>Let’s find out the answer by actually doing it. We'll run a BusyBox container and try to ping Google:</p>
<pre><code class="lang-bash">docker run --rm -it busybox sh
</code></pre>
<p>Once inside the container:</p>
<pre><code class="lang-bash">ping google.com
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752576013316/f29e7f49-5f8e-4a2a-8ab9-a4a1d52c5ceb.png" alt class="image--center mx-auto" /></p>
<p>Boom! We get a response. That means our container has internet access ✅</p>
<p>This is made possible by Docker's <strong>default bridge network</strong>.</p>
<h2 id="heading-what-is-the-bridge-network">🧠 What is the Bridge Network?</h2>
<p>By default, Docker assigns containers to a <code>bridge</code> network. This creates a <strong>virtual Ethernet interface (veth)</strong> on your host machine, and your container connects through it like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752579272735/3011cd65-02e7-47ce-bd11-53f67fa56219.png" alt class="image--center mx-auto" /></p>
<p>Run this command to view it:</p>
<pre><code class="lang-bash">ifconfig
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752576090299/4ce21bef-a524-414b-8de9-8afc560726dd.png" alt class="image--center mx-auto" /></p>
<p>You’ll see interfaces like <code>eth0</code> or <code>docker0</code> — that’s your container being connected to the host’s network via Docker’s bridge.</p>
<h2 id="heading-docker-networking-types-with-cheat-sheet">⚙️ Docker Networking Types (with Cheat Sheet)</h2>
<p>Docker supports different <strong>network drivers</strong>. Here’s a quick summary:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Driver</td><td>Use Case</td></tr>
</thead>
<tbody>
<tr>
<td><strong>bridge (default)</strong></td><td>Containers on the same host can communicate and external access needs port mapping</td></tr>
<tr>
<td><strong>host</strong></td><td>The container shares the host's networking namespace (No isolation).</td></tr>
<tr>
<td><strong>none</strong></td><td>No network connectivity <em>(Fully isolated)</em>.</td></tr>
<tr>
<td><strong>overlay</strong></td><td>Enable multiple-host networking for swarm services.</td></tr>
<tr>
<td><strong>macvlan</strong></td><td>Assigns a real MAC address to the container <em>(acts like a physical device)</em>.</td></tr>
</tbody>
</table>
</div><h2 id="heading-essential-docker-network-commands">🛠️ Essential Docker Network Commands</h2>
<p>Let’s get hands-on. These are the commands you’ll use often:</p>
<h3 id="heading-list-all-networks">🔍 List all networks</h3>
<pre><code class="lang-bash">docker network ls
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752568432808/b45e7afb-ee72-4de7-ad99-04035db8a38a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-inspect-a-specific-network">🔎 Inspect a specific network</h3>
<pre><code class="lang-bash">docker network inspect &lt;network_name&gt;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752568625950/e127af5a-a6f5-4457-b07a-1996bd649cfb.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-create-a-custom-bridge-network">🧱 Create a custom bridge network</h3>
<pre><code class="lang-bash">docker network create &lt;network_name&gt;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752568761953/82bf4aef-921d-4375-b366-b7487943269c.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-run-a-container-in-a-custom-network">🚀 Run a container in a custom network</h3>
<pre><code class="lang-bash">docker run --network &lt;network_name&gt; --name &lt;container_name&gt; -d &lt;image_name&gt;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752569112826/a7e7263d-8c5d-4574-aea2-c632bb1c8de2.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-connect-an-existing-container-to-a-network">🔗 Connect an existing container to a network</h3>
<pre><code class="lang-bash">docker network connect &lt;network_name&gt; &lt;container_name&gt;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752570341054/97177d11-d0d6-4974-8436-1da1140d4368.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-disconnect-a-container-from-a-network">🧼 Disconnect a container from a network</h3>
<pre><code class="lang-bash">docker network disconnect &lt;network_name&gt; &lt;container_name&gt;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752570201035/a1c26b71-24f7-4034-b608-62109b6ac902.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-remove-a-network">🗑️ Remove a network</h3>
<pre><code class="lang-bash">docker network rm &lt;network_name&gt;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752570439736/24d40bf3-1416-4011-b955-1f5ceb2c567d.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-container-to-container-communication">🤝 Container-to-Container Communication</h2>
<p>Let’s try it out!</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create custom bridge network</span>
docker network create my-bridge-network
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752574005059/306c63b7-4fcc-4c75-8e29-15f7e31e7858.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash"><span class="hljs-comment"># Start container 1 using nginx</span>
docker run -d --name container1 --network my-bridge-network nginx
</code></pre>
<p>Then check if container 1 is up and running:</p>
<pre><code class="lang-bash">docker ps
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752574144780/720ae565-37bf-461c-9140-dc7fe496edf5.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash"><span class="hljs-comment"># Start container 2 using alpine (lightweight Linux)</span>
docker run -d --name container2 --network my-bridge-network alpine sleep 3600
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752574266956/21934c88-00bb-4ea2-b992-dcce242e27a0.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-bash"><span class="hljs-comment"># From container2, ping container1 using container name</span>
docker <span class="hljs-built_in">exec</span> -it container2 ping container1
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752574413960/3ca59713-016c-4e8f-b7d5-7f5b2bd71791.png" alt class="image--center mx-auto" /></p>
<p>If you're using Docker's default bridge, container names won’t resolve—only IPs work. But in custom bridge networks, Docker gives you automatic DNS resolution. 🎉</p>
<h2 id="heading-host-networking-example">🖥️ Host Networking Example</h2>
<pre><code class="lang-bash">docker run -d --network host nginx
</code></pre>
<p>This container now shares your host machine’s IP address. It’s faster and leaner, but there’s no isolation — use with caution!</p>
<h2 id="heading-macvlan-networking-assigning-real-mac-ip">🔐 MacVLAN Networking (Assigning Real MAC + IP)</h2>
<p>Want your container to appear like a physical device on the network?</p>
<pre><code class="lang-bash">docker network create -d macvlan I am running a few minutes late; my previous meeting is running over.
  --subnet=192.168.1.0/24 \
  --gateway=192.168.1.1 \
  -o parent=eth0 \
  my-macvlan
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752575373603/1936a7a1-36d5-418c-96bf-3be8912aea88.png" alt class="image--center mx-auto" /></p>
<p>This sets up a network where containers have their own MAC address and can appear directly on your LAN. Great for advanced setups or legacy systems that require MAC-level identity.</p>
<h2 id="heading-dont-memorize-understand">📚 Don't Memorize, Understand</h2>
<p>Remember, it's not about memorizing every Docker command. It's about understanding the <strong>structure</strong> of commands:</p>
<pre><code class="lang-javascript">docker network &lt;action&gt; [options]
</code></pre>
<p>For example:</p>
<ul>
<li><p><code>docker network ls</code></p>
</li>
<li><p><code>docker network create &lt;nework_name&gt;</code></p>
</li>
<li><p><code>docker network inspect &lt;network_name&gt;</code></p>
</li>
<li><p><code>docker network connect &lt;nework_name&gt; &lt;container_name&gt;</code></p>
</li>
</ul>
<p>They're all intuitive once you get the hang of it.</p>
<h2 id="heading-summary">📝 Summary</h2>
<p>Docker networking isn’t as scary as it looks. Just remember:</p>
<ul>
<li><p><strong>Bridge</strong> is the default.</p>
</li>
<li><p><strong>Custom bridge</strong> gives DNS resolution.</p>
</li>
<li><p><strong>Host</strong> removes isolation (be careful).</p>
</li>
<li><p><strong>None</strong> means no network.</p>
</li>
<li><p><strong>Macvlan</strong> makes your container feel like a physical device.</p>
</li>
</ul>
<p>And most of all: <strong>don’t overthink it</strong>. For 95% of developer use cases, custom bridge networks with simple port mappings are more than enough.</p>
<p>If you found this helpful, please share it with your fellow developers.</p>
<p>Thanks for reading! 🙌</p>
<p>Happy learning! 🐳</p>
]]></content:encoded></item><item><title><![CDATA[How to Dockerize Your React App – With Multi-Stage Build]]></title><description><![CDATA[Welcome back, devs! 👋
If you’ve followed our Docker journey so far — from Intro to Docker to running your first container to Dockerizing a Node.js backend — you're ready for something more real-world.
In this blog, we will Dockerize React frontend a...]]></description><link>https://blog.omprakashpandey.com/how-to-dockerize-your-react-app-with-multi-stage-build</link><guid isPermaLink="true">https://blog.omprakashpandey.com/how-to-dockerize-your-react-app-with-multi-stage-build</guid><category><![CDATA[Docker]]></category><category><![CDATA[docker images]]></category><category><![CDATA[React]]></category><category><![CDATA[multi stage docker file]]></category><category><![CDATA[Devops]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Mon, 23 Jun 2025 21:36:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750714289733/80fea1a8-58c8-4a00-a03e-011fbd45971c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome back, devs! 👋</p>
<p>If you’ve followed our Docker journey so far — from <a target="_blank" href="https://blog.omprakashpandey.com/introduction-to-docker"><strong>Intro to Docker</strong></a> to <a target="_blank" href="https://blog.omprakashpandey.com/run-your-first-docker-container-understanding-the-magic-behind-the-scenes"><strong>running your first container</strong></a> to <a target="_blank" href="https://blog.omprakashpandey.com/how-to-dockerize-your-nodejs-backend-application"><strong>Dockerizing a Node.js backend</strong></a> — you're ready for something more real-world.</p>
<p>In this blog, we will Dockerize <strong>React frontend app built using</strong> <a target="_blank" href="https://vitejs.dev"><strong>Vite</strong></a>. But this isn’t just another "Hello Docker" tutorial. No skipping over errors. You’ll <strong>see where things break</strong> and more importantly, learn <strong>how to fix them like a real developer</strong>.</p>
<p>By the end of this, you’ll be able to Dockerize any frontend app with confidence.</p>
<p><img src="https://i.pinimg.com/originals/17/3a/3e/173a3e9ea1b3aa75e849f4da9b9e88c4.gif" alt="Excited Adorable GIF - Excited Adorable AGT - Discover &amp; Share GIFs" class="image--center mx-auto" /></p>
<p>Let's dive in.</p>
<h2 id="heading-step-1-create-a-new-react-app-using-vite">🛠️ Step 1: Create a New React App using Vite</h2>
<p>First create a new folder:</p>
<pre><code class="lang-bash">mkdir react_app &amp;&amp; <span class="hljs-built_in">cd</span> react_app
</code></pre>
<p>Now, create React app using Vite:</p>
<pre><code class="lang-bash">npm create vite@latest .
</code></pre>
<p>Choose:</p>
<ul>
<li><p><strong>React</strong></p>
</li>
<li><p><strong>JavaScript</strong> or <strong>TypeScript</strong> (your choice)</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750706444099/60b32ad1-ec03-4a25-bb2f-ea4a107df4a7.png" alt class="image--center mx-auto" /></p>
<p>Then install the dependencies:</p>
<pre><code class="lang-bash">npm install
</code></pre>
<p>And start the app:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>Visit <a target="_blank" href="http://localhost:5173">http://localhost:5173</a> and Ta-da! You have a running Vite + React app.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750706719924/06704031-1a4f-4a0d-9c66-acc0e5cccec3.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-2-lets-update-something">✍️ Step 2: Let’s Update Something</h2>
<p>Go to <code>src/App.jsx</code> and change the heading:</p>
<pre><code class="lang-jsx">&lt;h1&gt;Vite + React&lt;/h1&gt;

to

&lt;h1&gt;This is a Dockerized Vite + React App!&lt;/h1&gt;
</code></pre>
<p>Save the file and you should see the updated heading.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750707280125/2bfcd2ab-b72f-43c2-86bf-91b82ffa33f9.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-3-writing-the-dockerfile">📦 Step 3: Writing the Dockerfile</h2>
<p>Now comes the fun part: Dockerizing.</p>
<p>Create a new file in the root directory <code>Dockerfile</code>:</p>
<pre><code class="lang-bash">touch Dockerfile
</code></pre>
<p>Here’s the Dockerfile we’ll use:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># Step 1:  Use Node.js base image</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">22</span>-alpine

<span class="hljs-comment"># Step 2: Set working directory</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Step 3: Copy package files and install dependencies</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package*.json ./</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm install</span>

<span class="hljs-comment"># Step 4: Copy rest of the app</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>

<span class="hljs-comment"># Step 5: Build the app</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm run build</span>

<span class="hljs-comment"># Step 6: Command to run the app</span>
<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"npm"</span>, <span class="hljs-string">"run"</span>, <span class="hljs-string">"preview"</span>]</span>
</code></pre>
<p>💡 <strong>Why this order?</strong> Docker caches each layer. If your dependencies have not changed, <code>Step 3: npm install</code> will be reused — super fast builds!</p>
<h2 id="heading-step-4-build-the-docker-image">🧱 Step 4: Build the Docker Image</h2>
<p>Let’s build the image:</p>
<pre><code class="lang-bash">docker build -t react_app:v1 .
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750707702942/d1df2956-08d2-4255-8f33-87459a33b98c.png" alt class="image--center mx-auto" /></p>
<p>Then run it:</p>
<pre><code class="lang-bash">docker run -p 5173:5173 react_app:v1
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750707886137/ca5320c2-a7d6-4897-84ec-2806ea1ee348.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-5-uh-oh-it-doesnt-work">🚫 Step 5: Uh-oh, It Doesn't Work!</h2>
<p>When you visit <a target="_blank" href="http://localhost:5173">localhost:5173</a> or <a target="_blank" href="http://localhost:4173">localhost:4173</a>, you’ll see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750708023840/b3e0bd03-1e17-4a6e-8af4-249808f0248d.png" alt class="image--center mx-auto" /></p>
<p>This is because Vite's preview server <strong>only listens to</strong> <a target="_blank" href="http://localhost"><strong>localhost</strong></a> <strong>by default</strong>, not the Docker container's external network and also when you run <code>npm run preview</code>, it serves the app on port 4173, not 5173.</p>
<h2 id="heading-step-6-fix-vite-config-for-docker">🧑‍🔧 Step 6: Fix Vite Config for Docker</h2>
<p>Edit <code>vite.config.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">"vite"</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">"@vitejs/plugin-react"</span>;

<span class="hljs-comment">// https://vite.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    <span class="hljs-attr">plugins</span>: [react()],
    <span class="hljs-comment">// Fix for Docker</span>
    <span class="hljs-attr">server</span>: {
        <span class="hljs-attr">host</span>: <span class="hljs-string">"0.0.0.0"</span>, <span class="hljs-comment">// Listen on all IPs (including Docker)</span>
        <span class="hljs-attr">port</span>: <span class="hljs-number">3000</span>, <span class="hljs-comment">// Change to port 3000 for development mode</span>
    },
    <span class="hljs-attr">preview</span>: {
        <span class="hljs-attr">host</span>: <span class="hljs-string">"0.0.0.0"</span>, <span class="hljs-comment">// Listen on all IPs (including Docker)</span>
        <span class="hljs-attr">port</span>: <span class="hljs-number">3000</span>, <span class="hljs-comment">// Change to port 3000 for preview or production mode</span>
    },
});
</code></pre>
<p>This tells Vite to listen to all IPs (including Docker) and also changes the port to 3000 for both development and production preview.</p>
<h2 id="heading-step-7-rebuild-the-image">♻️ Step 7: Rebuild the Image</h2>
<p>Since we updated the app:</p>
<pre><code class="lang-bash">docker build -t react_app:v2 .
docker run -p 3000:3000 react_app:v2
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750710566834/02116550-01b7-48ea-9b99-ad73378e504f.png" alt class="image--center mx-auto" /></p>
<p>Now visit <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> and you should see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750708942043/149411f1-0ca0-4cd9-a114-3fbeb13555a9.png" alt class="image--center mx-auto" /></p>
<p>Simple Dockerfile link: <a target="_blank" href="https://github.com/OmGameHub/Docker_notes/blob/master/react_app/Dockerfile.old">Dockerfile</a></p>
<p>Now let’s take this one step further.</p>
<h2 id="heading-multi-stage-docker-build">Multi-Stage Docker Build</h2>
<p>We have Dockerized our React app, but we can do better by using <strong>multi-stage builds</strong>.</p>
<p>Because <strong>multi-stage builds are built for one thing only</strong>: <strong>optimization</strong>.</p>
<p>You want:</p>
<ul>
<li><p>✅ Smaller image size</p>
</li>
<li><p>✅ Cleaner final containers (no dev dependencies)</p>
</li>
<li><p>✅ Faster rebuilds with reusable layers</p>
</li>
</ul>
<p><img src="https://i.pinimg.com/originals/db/d8/e4/dbd8e43b7a32ea83fec2b9f10090c5e8.gif" alt="Wow Dwayne Johnson GIF - Wow Dwayne Johnson Jumanji - Discover &amp; Share GIFs" class="image--center mx-auto" /></p>
<p>Multi-stage builds are simple once you see</p>
<p>Let's use our React app to <strong>build in one stage</strong> and <strong>serve in another</strong> — production style.</p>
<h3 id="heading-step-1-build-stage">Step 1: Build Stage</h3>
<p>Rename your current <code>Dockerfile</code> to keep it as a backup:</p>
<pre><code class="lang-bash">mv Dockerfile Dockerfile.old
</code></pre>
<p>Now create a new <code>Dockerfile</code>:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># --- Stage 1: Build the Vite React App ---</span>

<span class="hljs-comment"># Use Node.js base image for building</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">22</span>-alpine AS builder

<span class="hljs-comment"># Set working directory</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Copy package files and install dependencies</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package*.json ./</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm install</span>

<span class="hljs-comment"># Copy rest of the app</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>

<span class="hljs-comment"># Build the app</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm run build</span>
</code></pre>
<p>This builds the static production files into <code>dist/</code>.</p>
<h3 id="heading-step-2-serve-with-nginx-production-stage">🔥 Step 2: Serve with NGINX (Production Stage)</h3>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># --- Stage 2: Serve with NGINX ---</span>
<span class="hljs-keyword">FROM</span> nginx:alpine AS production

<span class="hljs-comment"># Remove default nginx static files</span>
<span class="hljs-keyword">RUN</span><span class="bash"> rm -rf /usr/share/nginx/html/*</span>

<span class="hljs-comment"># Copy built app from builder</span>
<span class="hljs-keyword">COPY</span><span class="bash"> --from=builder /app/dist /usr/share/nginx/html</span>

<span class="hljs-comment"># Expose port 80</span>
<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">80</span>

<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"nginx"</span>, <span class="hljs-string">"-g"</span>, <span class="hljs-string">"daemon off;"</span>]</span>
</code></pre>
<blockquote>
<p>💡 <code>--from=builder</code> pulls files from the first stage only. No need to copy from your dev machine!</p>
</blockquote>
<h3 id="heading-step-3-build-and-run-the-multi-stage-docker-image">Step 3: Build and Run the Multi-Stage Docker Image</h3>
<pre><code class="lang-bash">docker build -t react_app_multistage .
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750710796034/f44be4dc-796b-40aa-86c9-cb6d0968e972.png" alt class="image--center mx-auto" /></p>
<p>Then run it:</p>
<pre><code class="lang-bash">docker run -p 3000:80 react_app_multistage
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750710848051/20e50ebc-2a39-42f4-9a5e-46c68a82a2b7.png" alt class="image--center mx-auto" /></p>
<p>Go to <a target="_blank" href="http://localhost:3000">http://localhost:3000</a> and boom! You’re now running a <strong>fully production optimized Docker container</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750708942043/149411f1-0ca0-4cd9-a114-3fbeb13555a9.png" alt class="image--center mx-auto" /></p>
<p>Multi-stage docker file link: <a target="_blank" href="https://github.com/OmGameHub/Docker_notes/blob/master/react_app/Dockerfile">Dockerfile</a></p>
<h2 id="heading-compare-image-sizes">📉 Compare Image Sizes</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750759169422/748dafd3-e6f1-4caf-a542-22c4c50ec794.png" alt class="image--center mx-auto" /></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Image Type</td><td>Size</td></tr>
</thead>
<tbody>
<tr>
<td>Simple Docker image</td><td>~279 MB</td></tr>
<tr>
<td>Multi-stage Docker image</td><td>~28–50 MB</td></tr>
</tbody>
</table>
</div><p>Yes — <strong>multi-stage builds shrink your image size</strong> drastically!</p>
<p><img src="https://www.gifcen.com/wp-content/uploads/2023/07/congratulations-gif-9.gif" alt="Congratulations Gif - GIFcen" class="image--center mx-auto" /></p>
<p>If you have reached this far, you now know how to:</p>
<ul>
<li><p>✅ Dockerize a React app using Vite</p>
</li>
<li><p>✅ Fix common issues like Vite’s <a target="_blank" href="http://localhost">localhost</a> binding</p>
</li>
<li><p>✅ Use multi-stage builds to optimize your Docker images</p>
</li>
</ul>
<h2 id="heading-bonus-use-dockerignore">🧼 Bonus: Use <code>.dockerignore</code></h2>
<p>Create a <code>.dockerignore</code> file:</p>
<pre><code class="lang-bash">node_modules
.dockerignore
Dockerfile
*.<span class="hljs-built_in">log</span>
dist
</code></pre>
<p>Why? To <strong>prevent Docker from copying unnecessary files</strong> during build. Smaller context = faster builds.</p>
<h2 id="heading-final-thoughts-on-multi-stage-builds">Final Thoughts on Multi-Stage Builds</h2>
<p>A multi-stage build is just:</p>
<pre><code class="lang-Dockerfile"><span class="hljs-keyword">FROM</span> ... AS builder
<span class="hljs-comment"># build here</span>

<span class="hljs-keyword">FROM</span> ... AS final
<span class="hljs-comment"># copy from builder</span>
</code></pre>
<p>It’s a simple way to <strong>separate build and runtime environments</strong>.</p>
<p>This becomes <em>really important</em> when your frontend or backend apps scale huge node_modules, development dependencies (like: TypeScript, Babel), test tools (like: Jest), source maps all of that can be kept out of production.</p>
<p>This keeps your production images clean, small, and fast.</p>
<p>If you found this helpful, please share it with your fellow developers.</p>
<p>Thanks for reading! 🙌</p>
<p>Happy learning! 🐳</p>
]]></content:encoded></item><item><title><![CDATA[How to Dockerize Your Node.js Backend Application]]></title><description><![CDATA[After learning the Basics of Docker and Running Your First Docker Container, It's time to take the next step: Let's containerize our Node.js backend application!
In this blog, we will containerize a real Node.js backend application while also buildin...]]></description><link>https://blog.omprakashpandey.com/how-to-dockerize-your-nodejs-backend-application</link><guid isPermaLink="true">https://blog.omprakashpandey.com/how-to-dockerize-your-nodejs-backend-application</guid><category><![CDATA[Docker]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Wed, 18 Jun 2025 21:03:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750280736820/e19b8d0c-415a-41d6-818e-7ed9cfcfb024.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>After learning the <a target="_blank" href="https://blog.omprakashpandey.com/introduction-to-docker">Basics of Docker</a> and <a target="_blank" href="https://blog.omprakashpandey.com/run-your-first-docker-container-understanding-the-magic-behind-the-scenes">Running Your First Docker Container</a>, It's time to take the next step: Let's containerize our Node.js backend application!</p>
<p>In this blog, we will <strong>containerize a real Node.js backend application</strong> while also building a solid understanding of Docker’s three core concepts:</p>
<ul>
<li><p><strong>Docker Images</strong></p>
</li>
<li><p><strong>Docker Containers</strong></p>
</li>
<li><p><strong>Dockerfile</strong></p>
</li>
</ul>
<h2 id="heading-what-we-will-build">🎯 What We will Build</h2>
<p>We will create a simple Node.js app and Dockerize it. But more importantly, we will explore the <strong>magic behind</strong> how Docker works and why these components matter.</p>
<h2 id="heading-first-lets-understand-dockers-core-concepts">First, Let’s Understand Docker’s Core Concepts</h2>
<h3 id="heading-1-docker-image">1. 🐳 Docker Image</h3>
<p>A <strong>Docker image</strong> is a <strong>lightweight, standalone, executable package</strong> that includes:</p>
<ul>
<li><p>Your code</p>
</li>
<li><p>Runtime (Node.js in our case)</p>
</li>
<li><p>Libraries</p>
</li>
<li><p>Environment variables</p>
</li>
<li><p>Configuration files</p>
</li>
<li><p>Sometimes even parts of the operating system</p>
</li>
</ul>
<p>Think of it as a <strong>blueprint</strong>. Once it’s built, it <strong>cannot be changed</strong> (images are <strong>immutable</strong>). If you need updates, you create a <strong>new version</strong> of the image.</p>
<p>Images are built <strong>layer by layer</strong>, which means:</p>
<ul>
<li><p>Each instruction in a Dockerfile creates a new layer.</p>
</li>
<li><p>Docker caches these layers, making builds faster and more efficient.</p>
</li>
<li><p>Understanding layers = optimizing your builds.</p>
</li>
</ul>
<p>Also, images are <strong>portable</strong>. They can run on any OS where Docker is installed (e.g Linux, Windows or macOS).</p>
<h3 id="heading-2-docker-container">2. 📦 Docker Container</h3>
<p>A <strong>Docker container</strong> is a <strong>runtime instance of an image</strong>.</p>
<p>Imagine your image is a blueprint for a car, and containers are the actual cars running on the road. You can spin up as many containers as you want from the same image.</p>
<p>Key traits of containers:</p>
<ul>
<li><p><strong>Isolated</strong>: Each container runs independently.</p>
</li>
<li><p><strong>Ephemeral</strong>: Once stopped, a container is gone for good. (You’ll have to create a new one.)</p>
</li>
<li><p><strong>Portable</strong>: Move containers across environments with ease.</p>
</li>
</ul>
<p>Containers make it possible to <strong>run the same image in development, staging, or production</strong>, just by changing environment variables. One image → many environments.</p>
<h3 id="heading-3-dockerfile">3. 📜 Dockerfile</h3>
<p>Now this is where <strong>you</strong>, the developer, come in.</p>
<p>A <strong>Dockerfile</strong> is a set of <strong>declarative instructions</strong> that tells Docker how to build an image.</p>
<p>You don’t write “code” like in JavaScript or Python. You simply <strong>declare what you want</strong>:</p>
<ul>
<li><p>What base image to start from</p>
</li>
<li><p>What files to copy</p>
</li>
<li><p>What commands to run</p>
</li>
<li><p>What port to expose</p>
</li>
</ul>
<blockquote>
<p>💡 It's easier than a programming language. Just tell Docker <strong>what</strong> to do, and it will handle the <strong>how</strong>.</p>
</blockquote>
<p>We’ll write a Dockerfile together below.</p>
<h2 id="heading-lets-dockerize-nodejs-app">🛠️ Let's Dockerize Node.js App</h2>
<h3 id="heading-1-initialize-the-project">1. Initialize the Project</h3>
<p>First, create a new directory for your Node.js app and initialize it:</p>
<pre><code class="lang-bash">mkdir node-app
<span class="hljs-built_in">cd</span> node-app
npm init -y
npm install express
</code></pre>
<h3 id="heading-2-create-the-app-indexjs">2. Create the App (<code>index.js</code>)</h3>
<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();

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

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.status(<span class="hljs-number">200</span>).json({
        <span class="hljs-attr">statusCode</span>: <span class="hljs-number">200</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">"Hello World from a Dockerized App!"</span>,
        <span class="hljs-attr">success</span>: <span class="hljs-literal">true</span>,
    });
});

app.get(<span class="hljs-string">"/health-check"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.status(<span class="hljs-number">200</span>).json({
        <span class="hljs-attr">statusCode</span>: <span class="hljs-number">200</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">"Health check passed"</span>,
        <span class="hljs-attr">success</span>: <span class="hljs-literal">true</span>,
    });
});

app.listen(port, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<h2 id="heading-3-dockerfile-lets-declare-the-image-instructions">3. Dockerfile – Let's Declare the Image Instructions</h2>
<p>Let’s create a <code>Dockerfile</code> in the root of your project directory. This file will contain all the instructions to build your Docker image.</p>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># use an official Node.js runtime as a parent image</span>
<span class="hljs-keyword">FROM</span> node:<span class="hljs-number">22</span>-alpine

<span class="hljs-comment"># set the working directory inside the container</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># copy package.json and package-lock.json to the working directory</span>
<span class="hljs-keyword">COPY</span><span class="bash"> package*.json ./</span>

<span class="hljs-comment"># install dependencies</span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm install</span>

<span class="hljs-comment"># copy the rest of the application code to the working directory</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . .</span>

<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"npm"</span>, <span class="hljs-string">"start"</span>]</span>
</code></pre>
<blockquote>
<p><strong>Note:</strong> The <code>RUN</code> command executes during the image build process, while <code>CMD</code> specifies the default command to run when a container starts.</p>
</blockquote>
<p>This Dockerfile creates a <strong>layered, immutable, portable</strong> image. Every line adds a new layer, which Docker caches for optimization.</p>
<h2 id="heading-dont-forget-dockerignore">🙈 Don’t Forget <code>.dockerignore</code></h2>
<pre><code class="lang-markdown">node<span class="hljs-emphasis">_modules
npm-debug.log</span>
</code></pre>
<p>This avoids copying unnecessary files into the image, keeping it lightweight.</p>
<h2 id="heading-build-and-run-the-docker-container">🧪 Build and Run the Docker Container</h2>
<h3 id="heading-step-1-build-the-image">Step 1: Build the Image</h3>
<pre><code class="lang-bash">docker build -t my-node-app .
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750276734253/22aa1a4a-8842-4856-a8ff-75b18ee9a6c1.png" alt="Build Node Js Backend Docker Image" class="image--center mx-auto" /></p>
<h3 id="heading-step-2-run-the-container">Step 2: Run the Container</h3>
<pre><code class="lang-bash">docker run -p 4000:3000 --env PORT=3000 my-node-app
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750276817989/46692f38-973f-4483-8b70-4c0846397cf4.png" alt="Run Node Js Backend Docker Container" class="image--center mx-auto" /></p>
<ul>
<li><p><code>-p 4000:3000</code> maps local port 4000 to container port 3000.</p>
</li>
<li><p><code>--env</code> sets the environment variable inside the container.</p>
</li>
</ul>
<p>Now visit <a target="_blank" href="http://localhost:4000"><code>http://localhost:4000</code></a> and you should see:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750277062077/6ee3df6a-3308-4694-a596-76d714a153f8.png" alt="Node.js Dockerized App API Response" class="image--center mx-auto" /></p>
<p><img src="https://wp.scoopwhoop.com/wp-content/uploads/2016/02/56b88b92fb778577566ef261_962499091.gif" alt="Congratulations" class="image--center mx-auto" /></p>
<p>Congratulations 🎉 You Did It!</p>
<p>You just built and run your first Dockerized Node.js app!</p>
<h2 id="heading-bonus-use-env-for-clean-environment-management">🌱 Bonus: Use <code>.env</code> for Clean Environment Management</h2>
<p>Create a <code>.env</code> file:</p>
<pre><code class="lang-markdown">PORT=3000
</code></pre>
<p>Run it like this:</p>
<pre><code class="lang-bash">docker run --env-file .env -p 4000:3000 node-app
</code></pre>
<h2 id="heading-cleanup-tips">🧹 Cleanup Tips</h2>
<p>To stop all running containers:</p>
<pre><code class="lang-bash">docker ps
docker stop &lt;container_id&gt;
</code></pre>
<p>To remove images:</p>
<pre><code class="lang-bash">docker rmi node-app
</code></pre>
<h2 id="heading-quick-recap">🧠 Quick Recap</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Concept</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Image</strong></td><td>Blueprint of your software (code + deps)</td></tr>
<tr>
<td><strong>Container</strong></td><td>Running instance of the image</td></tr>
<tr>
<td><strong>Dockerfile</strong></td><td>Instructions to build the image</td></tr>
</tbody>
</table>
</div><p>Docker works because these three main components come together and work as one. Once you understand these, you're on your way to mastering Docker.</p>
<p>I hope you found this blog helpful and informative. I would love to hear your thoughts and feedback. If you have any questions or suggestions, feel free to reach out.</p>
<p>Thanks for reading! 🙌</p>
<p>Happy learning! 🐳</p>
]]></content:encoded></item><item><title><![CDATA[Run Your First Docker Container: Understanding the Magic Behind the Scenes]]></title><description><![CDATA[Running your very first Docker container is a magical moment.
Most Docker tutorials start with these two simple commands:
docker pull hello-world
docker run hello-world

And Docker responds:

That’s it. Success! 🎉
It works so fast and so smoothly th...]]></description><link>https://blog.omprakashpandey.com/run-your-first-docker-container-understanding-the-magic-behind-the-scenes</link><guid isPermaLink="true">https://blog.omprakashpandey.com/run-your-first-docker-container-understanding-the-magic-behind-the-scenes</guid><category><![CDATA[Docker]]></category><category><![CDATA[Devops]]></category><category><![CDATA[containers]]></category><category><![CDATA[docker images]]></category><category><![CDATA[beginnersguide]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Tue, 17 Jun 2025 18:12:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750159860387/10239181-2002-419d-9058-634e4052d943.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Running your <strong>very first Docker container</strong> is a magical moment.</p>
<p>Most Docker tutorials start with these two simple commands:</p>
<pre><code class="lang-bash">docker pull hello-world
docker run hello-world
</code></pre>
<p>And Docker responds:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750169144746/14a0a704-41bb-4b40-8d43-cd6c3eeda0bf.png" alt="Terminal screenshot showing commands for pulling and running the Docker &quot;hello-world&quot; image. It confirms a successful installation and provides steps Docker takes to generate the message." class="image--center mx-auto" /></p>
<p>That’s it. Success! 🎉</p>
<p>It works so fast and so smoothly that you might miss what’s really happening in the background. It prints <code>Hello from Docker!</code> and you’re left thinking: <em>“Wait... that’s it?”</em></p>
<p>This guide isn't just about running a command. We're going behind the scenes to understand exactly how Docker works the first time you run a container. We’ll use a simple diagram and explain each step clearly, so Docker feels less like magic and more like a powerful tool in your development journey.</p>
<p>Let’s break it down.</p>
<h2 id="heading-what-happens-when-you-run-a-docker-command">🧠 What Happens When You Run a Docker Command?</h2>
<p>While the commands seem simple, a lot is happening under the hood.</p>
<h3 id="heading-1-you-the-user">👤 1: You (the User)</h3>
<p>You are the user sitting at your machine. You’ve installed Docker and are ready to run containers maybe <code>MySQL</code>, <code>PostgreSQL</code> or a simple <code>hello-world</code> image.</p>
<h3 id="heading-2-docker-engine">⚙️ 2: Docker Engine</h3>
<p>What you have actually installed is the Docker Engine — the underlying tech that handles the build, run, and lifecycle of containers.</p>
<p>Think of it as the core engine that interprets your commands and talks to other Docker components.</p>
<h3 id="heading-3-local-docker-repository-aka-cache">🗂 3: Local Docker Repository (aka Cache)</h3>
<p>When you run <code>docker run hello-world</code>, Docker first checks if this image (<code>hello-world</code>) is already present in your <strong>local image cache</strong>.</p>
<p>If it’s already available locally, Docker skips downloading and moves straight to running it.</p>
<h3 id="heading-4-docker-hub-cloud-repository">🌐 4: Docker Hub (Cloud Repository)</h3>
<p>If the image is not found locally, Docker reaches out to <strong>Docker Hub</strong> — the official public registry where developers share and download Docker images.</p>
<p>It downloads the image (only once) and stores it locally. From next time, it won’t re-download unless there's a version mismatch or cache clear.</p>
<h2 id="heading-docker-pull-vs-docker-run"><code>docker pull</code> vs <code>docker run</code></h2>
<p>Let’s demystify the difference:</p>
<h3 id="heading-docker-pull-hello-world">✅ <code>docker pull hello-world</code></h3>
<ul>
<li><p>Downloads the <code>hello-world</code> image from Docker Hub.</p>
</li>
<li><p>Stores it locally.</p>
</li>
<li><p>Doesn’t run it.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750169564967/ae851445-2533-44c3-bb8a-713a0e50395b.png" alt="docker pull hello-world command output" /></p>
</li>
</ul>
<h3 id="heading-docker-run-hello-world">✅ <code>docker run hello-world</code></h3>
<ul>
<li><p>First checks if the image exists locally.</p>
</li>
<li><p>If not, it pulls the image (like <code>docker pull</code>).</p>
</li>
<li><p>Then <strong>creates a container</strong> from that image and <strong>runs</strong> it.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750169474679/4ff8341a-c2bb-4efc-9eee-df34a39c080c.png" alt="docker run hello-world command output" /></p>
</li>
</ul>
<p>So, in a way:</p>
<pre><code class="lang-bash">docker run hello-world
</code></pre>
<p>is the same as:</p>
<pre><code class="lang-bash">docker pull hello-world
docker create hello-world
docker start &lt;container_id&gt;
</code></pre>
<blockquote>
<p>💡 <strong>Did you know</strong>:<br />The <a target="_blank" href="https://hub.docker.com/_/hello-world">hello-world</a> image has been downloaded over <strong>1 billion</strong> times on Docker Hub! It’s that iconic.</p>
</blockquote>
<h2 id="heading-understanding-images-vs-containers">Understanding Images vs Containers</h2>
<ul>
<li><p><strong>Image:</strong> A read-only template with the application code and environment.</p>
</li>
<li><p><strong>Container:</strong> A running instance of an image (like a lightweight virtual machine).</p>
</li>
</ul>
<p>You can run multiple containers from the same image.</p>
<h2 id="heading-visualizing-the-flow">🖥 Visualizing the Flow</h2>
<p>Let’s understand the flow:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1750172583570/454e4d1b-2edc-4f13-b4e7-f493aca2fd94.png" alt="Flowchart depicting the steps of executing . The process begins with the user running the command, followed by Docker Engine checking the local cache for the image. If unavailable, the image is pulled from Docker Hub. Next, a container is created from the image, which runs, prints &quot;Hello from Docker!&quot;, and exits." class="image--center mx-auto" /></p>
<ol>
<li><p>🧑‍💻 You run <code>docker run hello-world</code>.</p>
</li>
<li><p>🔍 Docker Engine checks the <strong>local cache</strong> (LocalHub).</p>
</li>
<li><p>📦 If not found, it pulls the image from <strong>Docker Hub</strong>.</p>
</li>
<li><p>🧱 It <strong>creates</strong> a container from the image.</p>
</li>
<li><p>▶️ The container runs and prints: <code>Hello from Docker!</code></p>
</li>
<li><p>🛑 The container exits after execution (since the program is just a print statement).</p>
</li>
</ol>
<p>You can view all this using Docker Desktop (GUI) or <code>docker ps -a</code> to list all containers (even exited ones).</p>
<h2 id="heading-bonus-clean-up-and-retesting">🎯 Bonus: Clean-Up and Retesting</h2>
<p>Let’s say you want to clean everything and try again:</p>
<h3 id="heading-stop-and-remove-containers">🛑 Stop and Remove Containers:</h3>
<pre><code class="lang-bash">docker ps -a           <span class="hljs-comment"># List all containers</span>
docker stop &lt;id&gt;       <span class="hljs-comment"># Stop running container</span>
docker rm &lt;id&gt;         <span class="hljs-comment"># Remove stopped container</span>
</code></pre>
<h3 id="heading-remove-the-image">🧹 Remove the Image:</h3>
<pre><code class="lang-bash">docker rmi hello-world
</code></pre>
<p>Now when you run <code>docker run hello-world</code>, it will trigger a fresh download.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747701047315/055dadfa-04b0-4248-abcb-ab2fbc49b952.gif" alt class="image--center mx-auto" /></p>
<p><strong>🎉 You Did It!</strong></p>
<p>If you’ve followed along, you’ve not only run your first Docker container, but you've also understood exactly how and why it worked.</p>
<p>You now know:</p>
<ul>
<li><p>What Docker Engine is.</p>
</li>
<li><p>How images and containers relate.</p>
</li>
<li><p>The role of Docker Hub.</p>
</li>
<li><p>What <code>pull</code> vs <code>run</code> really means.</p>
</li>
</ul>
<p>I hope you found this blog helpful and informative. I would love to hear your thoughts and feedback. If you have any questions or suggestions, feel free to reach out.</p>
<p>Thanks for reading! 🙌</p>
<p>Happy learning! 🐳</p>
]]></content:encoded></item><item><title><![CDATA[Prompting Techniques for Generative AI Models]]></title><description><![CDATA[Over the past few weeks, I have learned how prompting is not just about asking a model to "do something" it’s about asking it the right way. Like writing code, but with words.
It all started when I joined the Chai Code Gen AI Cohort, curious to under...]]></description><link>https://blog.omprakashpandey.com/prompting-techniques-for-generative-ai-models</link><guid isPermaLink="true">https://blog.omprakashpandey.com/prompting-techniques-for-generative-ai-models</guid><category><![CDATA[#PromptEngineering]]></category><category><![CDATA[ChaiCode]]></category><category><![CDATA[Python]]></category><category><![CDATA[openai]]></category><category><![CDATA[generative ai]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Tue, 20 May 2025 00:37:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1747700180999/79b1c54a-d927-4d46-9471-c3abd24743e8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Over the past few weeks, I have learned how prompting is not just about asking a model to "do something" it’s about asking it the right way. Like writing code, but with words.</p>
<p>It all started when I joined the <a target="_blank" href="https://courses.chaicode.com/learn/batch/about?bundleId=232480">Chai Code Gen AI Cohort</a>, curious to understand how these powerful AI models like GPT-4 actually “think.” The course wrapped up just yesterday, and while I’ve completed all the classwork, a few assignments (including this blog) are still sitting on my to-do list.</p>
<p>One thing that struck me during this journey is how prompting feels like a new kind of programming language—a bridge between human intent and machine output. Unlike traditional coding, where syntax and structure rule everything, prompting is about clarity, creativity, and context. The more I practiced, the more I realized that getting the right response from an AI model isn't magic it's a technique.</p>
<p>In this blog, I’m excited to share the prompting techniques I have learned along with practical Python + OpenAI code examples and the use cases where each shines. Whether you’re new to Gen AI or looking to sharpen your prompting skills, I hope this gives you a helpful starting point just like it did for me.</p>
<p>Let's Start!</p>
<h2 id="heading-1-zero-shot-prompting">1. Zero-Shot Prompting</h2>
<p>In zero-shot prompting, you ask the model to perform a task without providing any examples.</p>
<h3 id="heading-example">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
<span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI

load_dotenv()

client = OpenAI()

result = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4"</span>,
    messages=[
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"Hi, My name is Om"</span>},
    ],
)

print(result.choices[<span class="hljs-number">0</span>].message.content)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699934909/54c62be4-e34d-416f-8fe1-1dde23c2c6d0.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Case:</strong></p>
<ul>
<li>This technique is useful when you want the model to generate responses based on its understanding of the task.</li>
</ul>
<h2 id="heading-2-few-shot-prompting">2. Few-Shot Prompting</h2>
<p>In few-shot prompting, you provide the model with a few examples of the desired output format.</p>
<h3 id="heading-example-1">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
<span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI

load_dotenv()

system_prompt = <span class="hljs-string">"""
You are an AI assistant who is expert in sentiment analysis.
You are given a tweet and you have to classify the sentiment of the tweet.
Decide whether a Tweet's sentiment is positive, neutral, or negative.

Tweet: I loved the upcoming Amir Khan movie trailer for Sitaare Zameen Par. It was amazing! 😍
Sentiment: positive

Tweet: That was Super boring 😠
Sentiment: negative
"""</span>

client = OpenAI()

user_tweet = <span class="hljs-string">"Tweet: I am not sure about this new movie. It looks okay to me."</span>
print(<span class="hljs-string">f"User <span class="hljs-subst">{user_tweet}</span>"</span>)

result = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4"</span>,
    messages=[
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: system_prompt},
        {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: user_tweet},
    ],
)

print(<span class="hljs-string">f"🤖: <span class="hljs-subst">{result.choices[<span class="hljs-number">0</span>].message.content}</span>"</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699884515/a5fb944e-cf39-4583-899f-b18c9e949d47.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Case:</strong></p>
<ul>
<li>This technique helps the model understand the context and structure of the response you want.</li>
</ul>
<h2 id="heading-3-chain-of-thought-prompting">3. Chain of Thought Prompting</h2>
<p>In chain of thought prompting, you guide the model to think through a problem step-by-step.</p>
<h3 id="heading-example-2">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
<span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI

load_dotenv()

client = OpenAI()

system_prompt = <span class="hljs-string">"""
You are an AI assistant who is expert in breaking down complex problems and then resolve the user query.

For the given user input, analyse the input and break down the problem step by step.
At least think 4-5 steps on how to solve the problem before solving it down.

The steps are you get a user input, you analyse, you think, you again think for several times and then return an output with explanation and then finally you validate the output as well before giving final result.

Follow the steps in sequence that is "analyse", "think", "output", "validate" and finally "result".

Rules:
1. Follow the strict JSON output as per Output schema.
2. Always perform one step at a time and wait for next input
3. Carefully analyse the user query

Output Format:
{{ step: "string", content: "string" }}

Example:
Input: What is 8 + 2.
Output: {{ step: "analyse", content: "Alright! The user is interested in maths query and he is asking a basic athematic operation" }}
Output: {{ step: "think", content: "To perform the addition i must go from left to right and add all the operands" }}
Output: {{ step: "output", content: "10" }}
Output: {{ step: "validate", content: "seems like 10 is correct ans for 8 + 2" }}
Output: {{ step: "result", content: "8 + 2 = 10" }}
"""</span>

messages = [
    { <span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: system_prompt },
]

messages.append({ <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"What is 4 * 3?"</span> })

<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
    response = client.chat.completions.create(
        model=<span class="hljs-string">"gpt-4o"</span>,
        response_format={<span class="hljs-string">"type"</span>: <span class="hljs-string">"json_object"</span>},
        messages=messages
    )

    parsed_response = json.loads(response.choices[<span class="hljs-number">0</span>].message.content)
    messages.append({ <span class="hljs-string">"role"</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-string">"content"</span>: json.dumps(parsed_response) })

    <span class="hljs-keyword">if</span> parsed_response.get(<span class="hljs-string">"step"</span>) == <span class="hljs-string">"output"</span>:
        print(<span class="hljs-string">f"🤖: <span class="hljs-subst">{parsed_response.get(<span class="hljs-string">'content'</span>)}</span>"</span>)
        <span class="hljs-keyword">break</span>

    print(<span class="hljs-string">f"🤔: <span class="hljs-subst">{parsed_response.get(<span class="hljs-string">'content'</span>)}</span>"</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699723986/a45d88b2-b138-48ae-b9d9-0482c2a38dca.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Case:</strong></p>
<ul>
<li>This technique is particularly useful for complex queries where reasoning is required.</li>
</ul>
<h2 id="heading-4-self-consistency-prompting">4. Self-Consistency Prompting</h2>
<p>In self-consistency prompting, you generate multiple responses to the same prompt and select the most consistent answer.</p>
<h3 id="heading-example-3">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI
<span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> Counter
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv

load_dotenv()

client = OpenAI()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">self_consistency</span>(<span class="hljs-params">prompt, n=<span class="hljs-number">3</span>, temp=<span class="hljs-number">0.7</span></span>):</span>
    responses = [
        client.completions.create(
            model=<span class="hljs-string">"gpt-3.5-turbo-instruct"</span>,
            prompt=prompt,
            temperature=temp,
            max_tokens=<span class="hljs-number">50</span>
        )
        .choices[<span class="hljs-number">0</span>]
        .text.
        strip() <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n)
    ]

    <span class="hljs-keyword">return</span> Counter(responses).most_common(<span class="hljs-number">1</span>)[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] <span class="hljs-keyword">if</span> responses <span class="hljs-keyword">else</span> <span class="hljs-literal">None</span>

prompt = <span class="hljs-string">"What is 5 + 3?"</span>
print(<span class="hljs-string">f"Prompt: <span class="hljs-subst">{prompt}</span>"</span>)

consistent_answer = self_consistency(prompt)
print(<span class="hljs-string">f"Consistent Answer: <span class="hljs-subst">{consistent_answer}</span>"</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699690024/8f2d5b18-d463-4d86-a15b-7ac373cdd51a.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Case:</strong></p>
<ul>
<li>This technique can help improve the reliability of the model's output.</li>
</ul>
<h2 id="heading-5-instruction-prompting">5. Instruction Prompting</h2>
<p>In instruction prompting, you provide clear instructions to the model on what you want it to do.</p>
<h3 id="heading-example-4">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv

load_dotenv()

client = OpenAI()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">instruction_prompting</span>(<span class="hljs-params">instruction</span>):</span>
    response = client.completions.create(
        model=<span class="hljs-string">"gpt-3.5-turbo-instruct"</span>,
        prompt=<span class="hljs-string">f"Please follow these instructions carefully: <span class="hljs-subst">{instruction}</span>"</span>,
        temperature=<span class="hljs-number">0.7</span>,
        max_tokens=<span class="hljs-number">150</span>
    )
    <span class="hljs-keyword">return</span> response.choices[<span class="hljs-number">0</span>].text.strip()

instruction = <span class="hljs-string">"""
Summarize the following text in one sentence."
The quick brown fox jumps over the lazy dog. The fox is quick and agile, while the dog is slow and sleepy.
"""</span>
result = instruction_prompting(instruction)
print(<span class="hljs-string">f"Instruction: <span class="hljs-subst">{instruction}</span>"</span>)
print(<span class="hljs-string">f"Result:\n<span class="hljs-subst">{result}</span>"</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699642905/c46b80d3-7ed6-4576-a51e-fca58638f2e8.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Case:</strong></p>
<ul>
<li>This technique is useful for tasks that require specific actions or outputs.</li>
</ul>
<h2 id="heading-6-direct-answer-prompting">6. Direct Answer Prompting</h2>
<p>In direct answer prompting, you ask the model a question and expect a straightforward answer.</p>
<h3 id="heading-example-5">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv

load_dotenv()

client = OpenAI()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">direct_answer_prompting</span>(<span class="hljs-params">question</span>):</span>
    response = client.completions.create(
        model=<span class="hljs-string">"gpt-3.5-turbo-instruct"</span>,
        prompt=<span class="hljs-string">f"Answer the following question concisely: <span class="hljs-subst">{question}</span>"</span>,
        temperature=<span class="hljs-number">0.7</span>,
        max_tokens=<span class="hljs-number">150</span>
    )
    <span class="hljs-keyword">return</span> response.choices[<span class="hljs-number">0</span>].text.strip()

question = <span class="hljs-string">"What is the capital of India?"</span>
result = direct_answer_prompting(question)
print(<span class="hljs-string">f"Question: <span class="hljs-subst">{question}</span>"</span>)
print(<span class="hljs-string">f"Result: <span class="hljs-subst">{result}</span>"</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699594510/b3d10b2c-11b5-43dc-949b-9000c22afef2.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>This technique is helpful for queries that require quick and clear responses.</p>
</li>
<li><p>This is particularly useful in applications like chatbots, where the model needs to provide quick answers to user queries.</p>
</li>
</ul>
<h2 id="heading-7-personal-based-prompting">7. Personal-based Prompting</h2>
<p>In personal-based prompting, you customize the model's responses based on the user's preferences or known attributes.</p>
<h3 id="heading-example-6">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI
<span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv

load_dotenv()

client = OpenAI()

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">personal_based_prompting</span>(<span class="hljs-params">question</span>):</span>
    system_prompt = <span class="hljs-string">"""
    This AI assistant channels the candid, assertive and humorous demeanor of Ashneer Grover, renowned for his straightforwardness and wit.
    Designed to provide clear, no-nonsense coding assistance, it doesn't shy away from delivering hard truths, all while infusing interactions with a dose of humor.

    Tone:
    - Blunt &amp; Direct: Offers unfiltered advice, cutting through ambiguity.
    - Witty &amp; Humorous: Incorporates sharp one-liners and relatable analogies to elucidate complex coding concepts.
    - Assertive: Confidently presents solutions, ensuring users stay on the right track.

    Language: Hinglish (Hindi + English)
    - Uses a mix of Hindi and English, making it relatable to a wider audience.

    Example:

    Input: "I'm stuck with this bug. Can you help?"
    Output: "Bhai, code likhne se pehle sochna chahiye tha. Ab debug karne mein time waste mat kar, rewrite kar! 😤"

    Input: "Should I test this code before deployment?"
    Output: "Testing? Bhai, production mein hi sab pata chalega. Test karna hai toh shaadi ke rishton ka kar!"

    Input: "Which programming language should I use for this project?"
    Output: "Language se kya farak padta hai? Banda kaam ka hona chahiye. Python, Java, C++—sab doglapan hai!"

    Input: "Here's my code. What do you think?"
    Output: "Code dekh ke lagta hai, tumne ChatGPT ka copy-paste masterclass kiya hai. Originality naam ki cheez bhi hoti hai!"
    """</span>

    response = client.chat.completions.create(
        model=<span class="hljs-string">"gpt-4o-mini"</span>,
        messages=[
            {<span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: system_prompt},
            {<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: question}
        ],
        temperature=<span class="hljs-number">0.7</span>,
    )
    <span class="hljs-keyword">return</span> response.choices[<span class="hljs-number">0</span>].message.content.strip()

question = <span class="hljs-string">"Write a function to calculate the sum of two numbers in JavaScript."</span>
result = personal_based_prompting(question)
print(<span class="hljs-string">f"Question: <span class="hljs-subst">{question}</span>"</span>)
print(<span class="hljs-string">f"Result:\n<span class="hljs-subst">{result}</span>"</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747699397191/eb948d0e-6ec8-460f-b6c9-1638e0d5eac3.png" alt class="image--center mx-auto" /></p>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>This technique can help create a more engaging and personalized interaction.</p>
</li>
<li><p>This is particularly useful in applications like chatbots, where the model needs to adapt its tone and style to match the user's personality or preferences.</p>
</li>
</ul>
<h2 id="heading-8-role-playing-prompting">8. Role Playing Prompting</h2>
<p>In role-playing prompting, you ask the model to take on a specific persona or role.</p>
<h3 id="heading-example-7">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
<span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI

load_dotenv()

client = OpenAI()

system_prompt = <span class="hljs-string">"""
You are an AI Assistant who is specialized in maths.
You should not answer any query that is not related to maths.

For a given query help user to solve that along with explanation.

Example:
Input: 3 + 2
Output: 3 + 2 is 5.

Input: 3 * 10
Output: 3 * 10 is 30. Fun fact you can even multiply 10 * 3 which gives same result.

Input: Why is the color of sky?
Output: Bruh? You alright? Is it maths query?
"""</span>

result = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4o-mini"</span>,
    messages=[
        { <span class="hljs-string">"role"</span>: <span class="hljs-string">"system"</span>, <span class="hljs-string">"content"</span>: system_prompt },
        <span class="hljs-comment"># { "role": "user", "content": "what is 9 * 8" }, # 9 * 8 is 72. This means if you have 9 groups of 8 items each, you would have a total of 72 items.</span>
        { <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: <span class="hljs-string">"what is a computer?"</span> }, <span class="hljs-comment"># I'm sorry, but I can only provide help with maths-related queries. Please ask a maths question.</span>
    ]
)

print(result.choices[<span class="hljs-number">0</span>].message.content)
</code></pre>
<p><strong>Use case:</strong></p>
<ul>
<li><p>This technique can help create more engaging and contextually appropriate interactions.</p>
</li>
<li><p>This is particularly useful in applications like chatbots, where the model needs to maintain a consistent character or tone.</p>
</li>
</ul>
<h2 id="heading-9-contextual-prompting">9. Contextual Prompting</h2>
<p>In contextual prompting, you provide the model with conversation history or external context to help it understand the current query.</p>
<h3 id="heading-example-8">Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
<span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI

load_dotenv()

client = OpenAI()

messages = []

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_contextual_response</span>(<span class="hljs-params">user_query, context=None</span>):</span>
    messages.append({<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: user_query })

    result = client.chat.completions.create(
        model=<span class="hljs-string">"gpt-4o-mini"</span>,
        messages=messages
    )
    messages.append({ <span class="hljs-string">"role"</span>: <span class="hljs-string">"assistant"</span>, <span class="hljs-string">"content"</span>: result.choices[<span class="hljs-number">0</span>].message.content })

    <span class="hljs-keyword">return</span> result.choices[<span class="hljs-number">0</span>].message.content

<span class="hljs-comment"># Example usage</span>
user_query = <span class="hljs-string">"What is my name?"</span>
print(<span class="hljs-string">f"User: <span class="hljs-subst">{user_query}</span>"</span>)
print(<span class="hljs-string">f"Assistant: <span class="hljs-subst">{get_contextual_response(user_query)}</span>"</span>)
<span class="hljs-comment"># Assistant: I don't have access to personal data about individuals unless it has been shared with me in the course of our conversation.</span>
<span class="hljs-comment"># Therefore, I don't know your name.</span>
<span class="hljs-comment"># If you'd like to tell me, feel free!</span>

user_query = <span class="hljs-string">"Hi, My name is Om. I am a software engineer. Live in New Delhi."</span>
print(<span class="hljs-string">f"User: <span class="hljs-subst">{user_query}</span>"</span>)
print(<span class="hljs-string">f"Assistant: <span class="hljs-subst">{get_contextual_response(user_query)}</span>"</span>)
<span class="hljs-comment"># Assistant: Hi, Om! It's great to meet you.</span>
<span class="hljs-comment"># As a software engineer, you must be working on some interesting projects.</span>
<span class="hljs-comment"># What technologies or programming languages do you enjoy working with the most?</span>

user_query = <span class="hljs-string">"What is my name?"</span>
print(<span class="hljs-string">f"User: <span class="hljs-subst">{user_query}</span>"</span>)
print(<span class="hljs-string">f"Assistant: <span class="hljs-subst">{get_contextual_response(user_query)}</span>"</span>)
<span class="hljs-comment"># Assistant: Your name is Om!</span>
</code></pre>
<p><strong>Use case:</strong></p>
<ul>
<li><p>This technique is useful for maintaining coherence in extended interactions.</p>
</li>
<li><p>This is particularly useful in chatbots or applications where the model needs to remember previous interactions.</p>
</li>
</ul>
<h2 id="heading-10-multi-modal-prompting">10. Multi-modal Prompting</h2>
<p>In multi-modal prompting, you combine text with other modalities such as images, audio or video.</p>
<h3 id="heading-example-image-description">Example (Image Description):</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dotenv <span class="hljs-keyword">import</span> load_dotenv
<span class="hljs-keyword">from</span> openai <span class="hljs-keyword">import</span> OpenAI

load_dotenv()

client = OpenAI()

image_url = <span class="hljs-string">"https://developers.google.com/static/solutions/images/gemini-2.webp"</span>

response = client.chat.completions.create(
    model=<span class="hljs-string">"gpt-4o-mini"</span>,
    messages=[
        {
            <span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>,
            <span class="hljs-string">"content"</span>: [
                {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"Does this image contain a cat? Respond with either true or false"</span>},
                {<span class="hljs-string">"type"</span>: <span class="hljs-string">"image_url"</span>, <span class="hljs-string">"image_url"</span>: {<span class="hljs-string">"url"</span>: image_url}}
            ]
        }
    ],
    max_tokens=<span class="hljs-number">300</span>
)

<span class="hljs-comment"># Print the response</span>
print(<span class="hljs-string">f"Does this image contain a cat?"</span>, response.choices[<span class="hljs-number">0</span>].message.content)

<span class="hljs-comment"># Output</span>
<span class="hljs-comment"># Does this image contain a cat? True</span>
</code></pre>
<p>Use case:</p>
<ul>
<li>This technique is helpful for tasks that require reasoning over multiple types of data.</li>
</ul>
<h2 id="heading-best-practices-for-prompting">Best Practices for Prompting</h2>
<p><strong>1. Be concise:</strong> Keep your prompts short and to the point. Avoid unnecessary details that may confuse the model.</p>
<p>🛑 Not recommended: The prompt below is unnecessarily verbose.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"What do you think could be a good name for a flower shop that specializes in selling bouquets of dried flowers more than fresh flowers?"</span>
</code></pre>
<p>✅ Recommended: The prompt below is concise and clear.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Suggest a name for a flower shop that sells bouquets of dried flowers"</span>
</code></pre>
<p><strong>2. Be Specific &amp; Well-Defined:</strong> Make sure your prompt is specific and well-defined. The more context you provide, the better the model can understand your request.</p>
<p>🛑 Not recommended: The prompt below is vague and lacks context.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"Tell me about the weather."</span>
</code></pre>
<p>✅ Recommended: The prompt below is specific and well-defined.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"What is the weather like in New Delhi today?"</span>
</code></pre>
<p><strong>3. Ask One Task at a Time:</strong> Avoid asking multiple questions or tasks in a single prompt. This can lead to confusion and less accurate responses.</p>
<p>🛑 Not recommended: The prompt below asks multiple questions.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"What is the capital of France and what is the population of France?"</span>
</code></pre>
<p>✅ Recommended: The prompt below asks one question at a time.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"What is the capital of France?"</span>
</code></pre>
<p><strong>4. Improve Output Quality by Including Examples:</strong> Providing examples in your prompt can help the model understand the desired output format and improve the quality of the response.</p>
<p>🛑 Not recommended: The prompt below lacks examples.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"""
You are an AI Assistant who is specialized in sentiment analysis.

You should not answer any query that is not related to sentiment analysis.
For a given query help user to solve that along with explanation.
"""</span>
</code></pre>
<p>✅ Recommended: The prompt below includes examples.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"""
You are an AI Assistant who is specialized in sentiment analysis.
You should not answer any query that is not related to sentiment analysis.

For a given query help user to solve that along with explanation.

Possible Values: positive, neutral, or negative

Output Format:
{{ "sentiment": "string" }}

Example:
Input: I love this new phone!
Output: {{ "sentiment": "positive" }}

Input: I am not sure about this new movie. It looks okay to me.
Output: {{ "sentiment": "neutral" }}

Input: This restaurant had terrible service and the food was cold.
Output: {{ "sentiment": "negative" }}
"""</span>
</code></pre>
<p><strong>5. Turn Generative into Classification Tasks:</strong> To generate more controlled outputs ask the model to choose among predefined options instead of generating free-form text.</p>
<p>🛑 Not recommended: The prompt below is vague and lacks clarity.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"""
What is the sentiment of this tweet?:
I love this new phone!
"""</span>
</code></pre>
<p>✅ Recommended: The prompt below is clear and instructs the model to classify the sentiment.</p>
<pre><code class="lang-python">prompt = <span class="hljs-string">"""
Classify the sentiment of the following tweet as positive, negative or neutral:
I love this new phone!
"""</span>
</code></pre>
<p>Congratulations! 🎉</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1747701047315/055dadfa-04b0-4248-abcb-ab2fbc49b952.gif" alt class="image--center mx-auto" /></p>
<p>If you reach this point, I hope you found this blog helpful and informative. I would love to hear your thoughts and feedback on the techniques and examples shared here.</p>
<p>Thank you for reading! 🚀</p>
<p>Happy learning! 😊</p>
]]></content:encoded></item><item><title><![CDATA[Build Your Own AI Assistant with OpenAI and Next.js : A Step-by-Step Guide]]></title><description><![CDATA[In today’s digital age, where communication is the backbone of every business, staying connected with your customers is more critical and more challenging than ever.

If you’re running a small business or offering services in limited bugged, managing...]]></description><link>https://blog.omprakashpandey.com/build-your-own-ai-assistant-with-openai-and-nextjs-a-step-by-step-guide</link><guid isPermaLink="true">https://blog.omprakashpandey.com/build-your-own-ai-assistant-with-openai-and-nextjs-a-step-by-step-guide</guid><category><![CDATA[genai]]></category><category><![CDATA[openai]]></category><category><![CDATA[AI Assistants ]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sun, 04 May 2025 19:11:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746378517594/4207d4f0-170d-4114-8a94-abddb98717ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In today’s digital age, where communication is the backbone of every business, staying connected with your customers is more critical and more challenging than ever.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746466872756/c03cdae4-c853-4c57-a5d6-f1e3dce208c0.jpeg" alt class="image--center mx-auto" /></p>
<p>If you’re running a small business or offering services in limited bugged, managing inquiries, providing support and engaging with users can feel very challenging at times. But what if you could build your own AI assistant to handle these tasks for you effortlessly, efficiently, and around the clock?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746385480312/b4008e44-9eb3-4158-9a6f-92718b222f25.gif" alt class="image--center mx-auto" /></p>
<p>In this guide, I will walk you through creating an AI assistant for your domain using OpenAI Chat Completions API and Next.js.</p>
<p>Let's dive in!</p>
<h2 id="heading-define-your-assistants-purpose">🧠 Define Your Assistant’s Purpose</h2>
<p>Before writing a single line of code, take a moment to clarify the "why" behind your AI assistant. A well-defined purpose helps shape the assistant’s tone, logic and responses ultimately leading to a better user experience.</p>
<p>Let’s walk through the essentials using a relatable example:</p>
<h3 id="heading-assistant-goal">🎯 Assistant Goal</h3>
<p>You're a maths teacher who wants to build an AI assistant to support students with their math questions.</p>
<h3 id="heading-define-the-core-attributes">🧩 Define the Core Attributes</h3>
<ul>
<li><p><strong>📚 Specialization Area:</strong> Focus on mathematics from Class 1 to Class 10. This keeps the assistant domain-specific and easy to fine-tune.</p>
</li>
<li><p><strong>👨‍🏫 Target Users:</strong> School students in grades 1 to 10 who need help understanding or solving math problems.</p>
</li>
<li><p><strong>🛠️ Core Functionality:</strong></p>
<ul>
<li><p>Solve math queries with step-by-step explanations.</p>
</li>
<li><p>Answer in a simple, friendly and fun tone to keep students engaged.</p>
</li>
</ul>
</li>
<li><p><strong>🎭 Personality:</strong> The assistant, let’s call it Rubi Madam, should be:</p>
<ul>
<li><p>Funny and straightforward, to make learning enjoyable.</p>
</li>
<li><p>Conversational in Hinglish (Hindi + English) to resonate with local students.</p>
</li>
<li><p>Use emojis, short sentences, and easy words to avoid overwhelming the user.</p>
</li>
</ul>
</li>
</ul>
<p>By defining these attributes, we have set the stage for a more focused and effective AI assistant. This clarity will guide our development process, ensuring that every line of code or prompt aligns with your assistant's purpose.</p>
<h2 id="heading-step-2-set-up-your-project">🛠️ Step 2: Set Up Your Project</h2>
<h3 id="heading-create-a-nextjs-project">Create a Next.js Project</h3>
<pre><code class="lang-bash">npx create-next-app@latest maths-assistant
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746384744562/a173f14d-5292-4bf8-b160-5381378ed3fc.png" alt class="image--center mx-auto" /></p>
<p>Now navigate to your project directory and install all dependencies.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> maths-assistant
npm i axios
</code></pre>
<p>Now start the server</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<h2 id="heading-step-3-configure-environment-variables">🔐 Step 3: Configure Environment Variables</h2>
<p>Just create your Open AI API key from <a target="_blank" href="https://platform.openai.com/api-keys">https://platform.openai.com/api-keys</a> and save it in the .env file at the root of your project!</p>
<pre><code class="lang-markdown"><span class="hljs-section"># .env</span>
OPENAI<span class="hljs-emphasis">_API_</span>KEY=your<span class="hljs-emphasis">_api_</span>key<span class="hljs-emphasis">_here</span>
</code></pre>
<h2 id="heading-set-up-the-directory-structure">📁 Set Up the Directory Structure</h2>
<p>Set up your project with the following structure:</p>
<pre><code class="lang-markdown">my-assistant/
├── src/
│ ├── app/
│ │ ├── page.tsx # Main chat interface
│ │ ├── api/
│ │ │ └── v1/
│ │ │ └── chat/
│ │ │ └── completions/
│ │ │ └── route.ts # API endpoint
│ ├── lib/
│ │ └── openai.ts # OpenAI API client
│ ├── utils/
│ ├── types/
└── ...
</code></pre>
<h3 id="heading-define-types">🧾 Define Types</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// src/types/index.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> OpenAIMessageType = {
  role: <span class="hljs-string">"system"</span> | <span class="hljs-string">"user"</span> | <span class="hljs-string">"assistant"</span>;
  content: <span class="hljs-built_in">string</span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">type</span> ChatMessageType = OpenAIMessageType &amp; {
  id: <span class="hljs-built_in">string</span>;
  isLoading?: <span class="hljs-built_in">boolean</span>;
};
</code></pre>
<h3 id="heading-create-utility-functions">🛠 Create Utility Functions</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// src/utils/index.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> classNames = <span class="hljs-function">(<span class="hljs-params">...classes: <span class="hljs-built_in">string</span>[]</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> classes.filter(<span class="hljs-built_in">Boolean</span>).join(<span class="hljs-string">" "</span>);
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> generateMessageId = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Date</span>.now() + <span class="hljs-built_in">Math</span>.random().toString(<span class="hljs-number">36</span>).substring(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>);
};
</code></pre>
<h2 id="heading-create-a-constants-file">📚 Create a Constants File</h2>
<pre><code class="lang-typescript"><span class="hljs-comment">// src/utils/constants.ts</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ChatRoles = {
  SYSTEM: <span class="hljs-string">"system"</span>,
  USER: <span class="hljs-string">"user"</span>,
  ASSISTANT: <span class="hljs-string">"assistant"</span>,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> HttpStatusCodes = {
  OK: <span class="hljs-number">200</span>,
  BAD_REQUEST: <span class="hljs-number">400</span>,
  INTERNAL_SERVER_ERROR: <span class="hljs-number">500</span>,
};
</code></pre>
<h3 id="heading-create-the-open-ai-api-client-and-helper-functions">🤖 Create the Open AI API Client and Helper Functions</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// src/lib/openai.ts</span>
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;
<span class="hljs-keyword">import</span> { OpenAIMessageType } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/types"</span>;
<span class="hljs-keyword">import</span> { HttpStatusCodes } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/utils/constants"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> apiClient = axios.create({
  baseURL: <span class="hljs-string">"https://api.openai.com/v1"</span>,
  headers: {
    <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
    Authorization: <span class="hljs-string">`Bearer <span class="hljs-subst">${process.env.OPENAI_API_KEY}</span>`</span>,
  },
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> getChatCompletion = <span class="hljs-keyword">async</span> (messages: OpenAIMessageType[]) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> apiClient.post(<span class="hljs-string">"/chat/completions"</span>, {
      model: <span class="hljs-string">"gpt-3.5-turbo"</span>, <span class="hljs-comment">// Specifies the language model to use</span>
      messages: messages, <span class="hljs-comment">// Array of message objects (role + content) forming the conversation history</span>
      max_tokens: <span class="hljs-number">2000</span>, <span class="hljs-comment">// Maximum number of tokens the model can generate in the response</span>
      temperature: <span class="hljs-number">1</span>, <span class="hljs-comment">// Controls randomness: 0 = deterministic, 1 = more creative</span>
    });

    <span class="hljs-keyword">if</span> (response.status !== HttpStatusCodes.OK) {
      <span class="hljs-keyword">throw</span> {
        statusCode: response.status,
        message: response.data.error.message || <span class="hljs-string">"Something went wrong"</span>,
      };
    }

    <span class="hljs-keyword">const</span> message = response.data.choices[<span class="hljs-number">0</span>].message <span class="hljs-keyword">as</span> OpenAIMessageType;
    <span class="hljs-keyword">return</span> message;
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error fetching chat completion:"</span>, error);

    <span class="hljs-keyword">if</span> (axios.isAxiosError(error)) {
      <span class="hljs-keyword">const</span> statusCode =
        error.response?.status || HttpStatusCodes.INTERNAL_SERVER_ERROR;
      <span class="hljs-keyword">const</span> message =
        error.response?.data?.error?.message ||
        <span class="hljs-string">"Something went wrong while fetching chat completion"</span>;

      <span class="hljs-keyword">throw</span> { statusCode, message };
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">throw</span> {
        statusCode: HttpStatusCodes.INTERNAL_SERVER_ERROR,
        message: <span class="hljs-string">"An unexpected error occurred"</span>,
      };
    }
  }
};
</code></pre>
<h3 id="heading-create-api-route-handler">🌐 Create API Route Handler</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// src/app/api/v1/chat/completions/route.ts</span>
<span class="hljs-keyword">import</span> { NextRequest, NextResponse } <span class="hljs-keyword">from</span> <span class="hljs-string">"next/server"</span>;
<span class="hljs-keyword">import</span> { getChatCompletion } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/lib/openai"</span>;
<span class="hljs-keyword">import</span> { generateMessageId } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/utils"</span>;
<span class="hljs-keyword">import</span> { HttpStatusCodes } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/utils/constants"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">POST</span>(<span class="hljs-params">request: NextRequest</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> { messages } = <span class="hljs-keyword">await</span> request.json();

    <span class="hljs-keyword">if</span> (!messages || messages.length === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> NextResponse.json(
        {
          statusCode: HttpStatusCodes.BAD_REQUEST,
          message: <span class="hljs-string">"No messages provided"</span>,
        },
        { status: HttpStatusCodes.BAD_REQUEST }
      );
    }

    <span class="hljs-keyword">const</span> { content } = <span class="hljs-keyword">await</span> getChatCompletion(messages);

    <span class="hljs-keyword">return</span> NextResponse.json({
      status: HttpStatusCodes.OK,
      message: <span class="hljs-string">"Chat completion fetched successfully"</span>,
      data: {
        id: generateMessageId(),
        role: <span class="hljs-string">"assistant"</span>,
        content,
      },
    });
  } <span class="hljs-keyword">catch</span> (error: <span class="hljs-built_in">any</span>) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"OpenAI API Error:"</span>, error);

    <span class="hljs-keyword">const</span> statusCode =
      error.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;
    <span class="hljs-keyword">const</span> message = error.message || <span class="hljs-string">"Failed to fetch chat completion"</span>;

    <span class="hljs-keyword">return</span> NextResponse.json({ statusCode, message }, { status: statusCode });
  }
}
</code></pre>
<h3 id="heading-build-the-chat-ui">💬 Build the Chat UI</h3>
<pre><code class="lang-typescript"><span class="hljs-comment">// src/app/page.tsx</span>
<span class="hljs-string">"use client"</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { classNames, generateMessageId } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/utils"</span>;
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;
<span class="hljs-keyword">import</span> { OpenAIMessageType, ChatMessageType } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/types"</span>;
<span class="hljs-keyword">import</span> { ChatRoles } <span class="hljs-keyword">from</span> <span class="hljs-string">"@/utils/constants"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [message, setMessage] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [messages, setMessages] = useState&lt;ChatMessageType[]&gt;([
    {
      id: generateMessageId(),
      role: <span class="hljs-string">"system"</span>,
      content: <span class="hljs-string">`
        You are an AI Assistant name Rubi. who is specialized in maths.
        You should not answer any query that is not related to maths.

        For a given query help user to solve that along with explanation.

        Tone:
          - Funny and straightforward.
          - Use emojis to make it more engaging.

        Language:
          - Hinglish (Hindi + English) for better understanding.
          - Use simple and easy to understand language.
          - Use short sentences and avoid jargon.

        Example:
        Input: 3 + 2
        Output: 3 + 2 is 5.

        Input: 3 * 10
        Output: 3 * 10 is 30. Fun fact you can even multiply 10 * 3 which gives same result.

        Input: Why is the color of sky?
        Output: Are you alright? Is it maths query?

        Input: What is your name?
        Output: My name is Rubi. How can I assist you today?
      `</span>,
    },
    {
      id: generateMessageId(),
      role: <span class="hljs-string">"assistant"</span>,
      content: <span class="hljs-string">"Hello my name is Rubi! How can I assist you today?"</span>,
    },
  ]);
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-comment">// Helper to create message objects with only necessary data</span>
  <span class="hljs-keyword">const</span> createMessage = (
    role: ChatMessageType[<span class="hljs-string">"role"</span>],
    content: <span class="hljs-built_in">string</span>,
    isLoading = <span class="hljs-literal">false</span>
  ): <span class="hljs-function"><span class="hljs-params">ChatMessageType</span> =&gt;</span> ({
    id: generateMessageId(),
    role,
    content,
    ...(isLoading &amp;&amp; { isLoading }),
  });

  <span class="hljs-keyword">const</span> handleSendMessage = <span class="hljs-function">(<span class="hljs-params">e: React.FormEvent</span>) =&gt;</span> {
    e.preventDefault();
    <span class="hljs-keyword">if</span> (!message.trim()) <span class="hljs-keyword">return</span>;
    setLoading(<span class="hljs-literal">true</span>);

    <span class="hljs-keyword">const</span> userMsg = createMessage(<span class="hljs-string">"user"</span>, message);
    <span class="hljs-keyword">const</span> latestMsgs = messages.concat(userMsg);

    <span class="hljs-keyword">const</span> loadingMsg = createMessage(<span class="hljs-string">"assistant"</span>, <span class="hljs-string">"Thinking..."</span>, <span class="hljs-literal">true</span>);
    <span class="hljs-comment">// Add user message and loading message</span>
    setMessages([...latestMsgs, loadingMsg]);
    setMessage(<span class="hljs-string">""</span>);

    <span class="hljs-keyword">const</span> payload = {
      messages: latestMsgs.map(<span class="hljs-function">(<span class="hljs-params">{ role, content }</span>) =&gt;</span> ({ role, content })),
    };
    axios
      .post(<span class="hljs-string">"/api/v1/chat/completions"</span>, payload)
      .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> replyMsg = res.data.data <span class="hljs-keyword">as</span> OpenAIMessageType;

        <span class="hljs-keyword">if</span> (replyMsg &amp;&amp; replyMsg.content) {
          <span class="hljs-keyword">const</span> assistantMessage = createMessage(<span class="hljs-string">"assistant"</span>, replyMsg.content);

          <span class="hljs-comment">// Replace loading message with actual response</span>
          setMessages(<span class="hljs-function">(<span class="hljs-params">prevMsgs</span>) =&gt;</span> {
            <span class="hljs-keyword">const</span> updatedMessages = [...prevMsgs];
            updatedMessages.pop(); <span class="hljs-comment">// Remove loading message</span>
            <span class="hljs-keyword">return</span> [...updatedMessages, assistantMessage];
          });
        } <span class="hljs-keyword">else</span> {
          <span class="hljs-comment">// Remove loading message if there's an error</span>
          setMessages(<span class="hljs-function">(<span class="hljs-params">prevMsgs</span>) =&gt;</span> {
            <span class="hljs-keyword">const</span> updatedMessages = [...prevMsgs];
            updatedMessages.pop(); <span class="hljs-comment">// Remove loading message</span>
            <span class="hljs-keyword">return</span> updatedMessages;
          });
          alert(<span class="hljs-string">"No response from the assistant."</span>);
        }
      })
      .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
        <span class="hljs-comment">// Remove loading message on error</span>
        setMessages(<span class="hljs-function">(<span class="hljs-params">prevMsgs</span>) =&gt;</span> {
          <span class="hljs-keyword">const</span> updatedMessages = [...prevMsgs];
          updatedMessages.pop();
          <span class="hljs-keyword">return</span> updatedMessages;
        });
        alert(error.response?.data?.message || <span class="hljs-string">"Something went wrong"</span>);
      })
      .finally(<span class="hljs-function">() =&gt;</span> setLoading(<span class="hljs-literal">false</span>));
  };

  <span class="hljs-keyword">return</span> (
    &lt;div className=<span class="hljs-string">"flex flex-col h-screen bg-gray-100"</span>&gt;
      {<span class="hljs-comment">/* Header */</span>}
      &lt;header className=<span class="hljs-string">"bg-white shadow-sm p-4 flex items-center"</span>&gt;
        &lt;h1 className=<span class="hljs-string">"text-xl font-semibold text-gray-800"</span>&gt;
          Rubi Your Maths Assistant
        &lt;/h1&gt;
      &lt;/header&gt;

      {<span class="hljs-comment">/* Chat area */</span>}
      &lt;div className=<span class="hljs-string">"flex-1 overflow-y-auto p-4 space-y-4"</span>&gt;
        {messages.map(<span class="hljs-function">(<span class="hljs-params">msg, index</span>) =&gt;</span> {
          <span class="hljs-keyword">const</span> isUserMsg = msg.role === ChatRoles.USER;

          <span class="hljs-keyword">if</span> (msg.role === <span class="hljs-string">"system"</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; <span class="hljs-comment">// Skip system messages</span>

          <span class="hljs-keyword">return</span> (
            &lt;div
              key={index}
              className={classNames(
                <span class="hljs-string">"flex items-start space-x-2"</span>,
                isUserMsg ? <span class="hljs-string">"justify-end"</span> : <span class="hljs-string">"justify-start"</span>
              )}
            &gt;
              &lt;div
                className={classNames(
                  <span class="hljs-string">"max-w-[70%] p-3 rounded-lg shadow"</span>,
                  isUserMsg
                    ? <span class="hljs-string">"bg-blue-500 text-white"</span>
                    : <span class="hljs-string">"bg-white text-gray-800"</span>
                )}
              &gt;
                {msg.content}
              &lt;/div&gt;
            &lt;/div&gt;
          );
        })}
      &lt;/div&gt;

      {<span class="hljs-comment">/* Message input */</span>}
      &lt;form
        onSubmit={handleSendMessage}
        className=<span class="hljs-string">"bg-white p-4 shadow-lg border-t"</span>
      &gt;
        &lt;div className=<span class="hljs-string">"flex space-x-2"</span>&gt;
          &lt;input
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            value={message}
            onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setMessage(e.target.value)}
            placeholder=<span class="hljs-string">"Type your message..."</span>
            className=<span class="hljs-string">"flex-1 border rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"</span>
            disabled={loading}
          /&gt;

          &lt;button
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>
            className=<span class="hljs-string">"bg-blue-500 text-white rounded-full p-2 w-10 h-10 flex items-center justify-center hover:bg-blue-600"</span>
            disabled={loading}
          &gt;
            &lt;svg
              xmlns=<span class="hljs-string">"http://www.w3.org/2000/svg"</span>
              fill=<span class="hljs-string">"none"</span>
              viewBox=<span class="hljs-string">"0 0 24 24"</span>
              stroke=<span class="hljs-string">"currentColor"</span>
              className=<span class="hljs-string">"h-5 w-5 rotate-90"</span>
            &gt;
              &lt;path
                strokeLinecap=<span class="hljs-string">"round"</span>
                strokeLinejoin=<span class="hljs-string">"round"</span>
                strokeWidth={<span class="hljs-number">2</span>}
                d=<span class="hljs-string">"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"</span>
              /&gt;
            &lt;/svg&gt;
          &lt;/button&gt;
        &lt;/div&gt;
      &lt;/form&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746378108158/e8ed6f6e-ad7a-444e-aa40-f0e3dda0f33f.png" alt class="image--center mx-auto" /></p>
<p>If you have followed all the steps correctly, you should now have a fully functional AI assistant that can handle math queries in a fun and engaging way.</p>
<p><img src="https://gifsec.com/wp-content/uploads/2022/09/congrats-gif-5.gif" alt="Congratulations GIFs - The Best GIF Collections Are On GIFSEC" class="image--center mx-auto" /></p>
<p>Repository link: <a target="_blank" href="https://github.com/OmGameHub/math-ai-assistant">https://github.com/OmGameHub/math-ai-assistant</a></p>
<h2 id="heading-best-practices-for-implementing-ai-assistants">✅ Best Practices for Implementing AI Assistants</h2>
<ol>
<li><p><strong>🎯 Clearly Define the Assistant’s Scope</strong></p>
<p> To avoid confusion and prevent the assistant from providing irrelevant or misleading responses.</p>
<pre><code class="lang-markdown"> You are an AI Assistant named Rubi, specialized in maths.
 You should not answer any query that is not related to maths.
</code></pre>
</li>
<li><p><strong>🗣️ Design a Consistent Personality &amp; Tone</strong></p>
<p> To make the assistant feel more human and relatable.</p>
<pre><code class="lang-markdown"> Tone: 
<span class="hljs-bullet"> -</span> Funny and straightforward. 
<span class="hljs-bullet"> -</span> Use emojis to make it more engaging.

 Language:
<span class="hljs-bullet"> -</span> Hinglish (Hindi + English) for better understanding. 
<span class="hljs-bullet"> -</span> Use simple and easy-to-understand language. 
<span class="hljs-bullet"> -</span> Use short sentences and avoid jargon.
</code></pre>
</li>
<li><p><strong>🧱 Use System Prompts with examples to Control Behaviour</strong></p>
<p> Set system prompts to guide the assistant's responses and help create clear boundaries.</p>
<pre><code class="lang-markdown"> You are an AI Assistant name Rubi. who is specialized in maths.
 You should not answer any query that is not related to maths.

 For a given query help user to solve that along with explanation.

 Tone:

<span class="hljs-bullet"> -</span> Funny and straightforward.
<span class="hljs-bullet"> -</span> Use emojis to make it more engaging.

 Language:

<span class="hljs-bullet"> -</span> Hinglish (Hindi + English) for better understanding.
<span class="hljs-bullet"> -</span> Use simple and easy-to-understand language.
<span class="hljs-bullet"> -</span> Use short sentences and avoid jargon.

 Example:
 Input: 3 + 2
 Output: 3 + 2 is 5.

 Input: 3 <span class="hljs-emphasis">_ 10
 Output: 3 _</span> 10 is 30. Fun fact you can even multiply 10 <span class="hljs-emphasis">* 3 which gives same result.

 Input: Why is the color of sky?
 Output: Are you alright? Is it maths query?

 Input: What is your name?
 Output: My name is Rubi. How can I assist you today?</span>
</code></pre>
</li>
<li><p><strong>🔒 Never Expose Sensitive Keys on the Client Side</strong></p>
<p> To avoid misuse or abuse of your OpenAI API key.</p>
<p> <strong>Example:</strong> We store the <code>OPENAI_API_KEY</code> securely in the <code>.env</code> file and use it server-side only via the API route at <code>/api/v1/chat/completions</code>.</p>
</li>
<li><p>🧪 Test for Edge Cases and Non-domain Questions</p>
</li>
</ol>
<p>To ensure that the assistant stays on-topic and doesn't hallucinate answers.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>✅ “What is 2 power 100?” → correct answer</p>
</li>
<li><p>❌ “What is amazon.com?” → reject with a fun message</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746378040269/9af54873-d168-435b-9bf7-9bf6fbc87a1c.png" alt /></p>
</li>
</ul>
<ol start="6">
<li><p>🔁 Continuously Improve Through Real User Feedback</p>
<ul>
<li><p>To ensure that the assistant is always improving and adapting to user needs.</p>
</li>
<li><p>Example:</p>
<ul>
<li><p>Take feedback from users and improve the assistant's responses.</p>
</li>
<li><p>You can use tools like <a target="_blank" href="https://langchain-ai.github.io/langgraph/tutorials/introduction/">LangGraph</a> etc.</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p>Thank you for reading! 🚀</p>
<p>Happy learning! 😊</p>
]]></content:encoded></item><item><title><![CDATA[Generative AI 101: A Quick Introduction]]></title><description><![CDATA[As software developers our goal is simple: build products that make our end users lives easier, faster and smarter.
Generative AI is opening a new world of possibilities — from automating content creation to enhancing customer experiences.
In my past...]]></description><link>https://blog.omprakashpandey.com/generative-ai-101-a-quick-introduction</link><guid isPermaLink="true">https://blog.omprakashpandey.com/generative-ai-101-a-quick-introduction</guid><category><![CDATA[genai]]></category><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sat, 26 Apr 2025 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745747049126/6009a4cb-1d81-422a-a96b-8bd0caecad58.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As software developers our goal is simple: build products that make our end users lives easier, faster and smarter.</p>
<p>Generative AI is opening a new world of possibilities — from automating content creation to enhancing customer experiences.</p>
<p>In my past projects, like GO Bermondsey (a coworking space platform) and Writely (a content creation tool), I created AI features like content generation, meta tag automation, social media hashtags, and chatbots. At the time, it felt like pure magic — I used Open AI API without fully understanding how it worked.</p>
<p>Recently, I’ve started learning more again through the <a target="_blank" href="https://courses.chaicode.com/learn/batch/about?bundleId=227321">ChaiCode Gen AI Cohort</a> (I’ve just attended the few class!) — and it’s been eye-opening.</p>
<p>In this blog, I’ll break down the basics of what I’ve learned so far about how Generative AI works. Let's dive in!</p>
<h2 id="heading-what-is-generative-ai">What is Generative AI?</h2>
<p>It is a type of artificial intelligence that can generate new content such as text, images, music etc. To do this, you have to describe what want to create to AI. This is called a prompt. The AI model then uses its knowledge to generate something new based on that prompt.</p>
<h2 id="heading-lets-understand-the-jargon-used-in-ai-development">Let’s understand the jargon used in AI development:</h2>
<h3 id="heading-token">Token:</h3>
<p>It represents the smallest data unit that the AI model can understand from its dictionary. It can be a character, word, sub-word or number etc.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> OM_AI_MODEL_TOKEN_DICTIONARY = {
    <span class="hljs-attr">I</span>: <span class="hljs-number">49</span>,
    <span class="hljs-attr">a</span>: <span class="hljs-number">97</span>,
    <span class="hljs-attr">am</span>: <span class="hljs-number">20</span>,
    <span class="hljs-attr">developer</span>: <span class="hljs-number">49</span>,
    <span class="hljs-attr">by</span>: <span class="hljs-number">59</span>,
    <span class="hljs-attr">profession</span>: <span class="hljs-number">76</span>,
    <span class="hljs-attr">and</span>: <span class="hljs-number">70</span>,
    <span class="hljs-attr">love</span>: <span class="hljs-number">89</span>,
    <span class="hljs-attr">coding</span>: <span class="hljs-number">99</span>,
    <span class="hljs-attr">you</span>: <span class="hljs-number">100</span>,
    <span class="hljs-attr">he</span>: <span class="hljs-number">101</span>,
    <span class="hljs-attr">she</span>: <span class="hljs-number">102</span>,
    <span class="hljs-string">'pani puri'</span>: <span class="hljs-number">103</span>
};
</code></pre>
<h3 id="heading-tokenization">Tokenization:</h3>
<p>It is a process of breaking down input data like sentences, texts, audio, images or videos into tokens. So that AI model can process and understand each token.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745760283134/45a30d93-4f89-44de-96a2-5467704587b3.png" alt="Tokenization example" class="image--center mx-auto" /></p>
<p>If you want to view what tokenisation looks like, you can use this link: <a target="_blank" href="https://tiktokenizer.vercel.app">Tokenisation Visualizer</a>.</p>
<h3 id="heading-encoding">Encoding:</h3>
<p>Converting tokens into numbers that the AI model can understand. Each token is mapped to a unique number using a predefined dictionary.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> OM_AI_MODEL_TOKEN_DICTIONARY = {
    <span class="hljs-attr">I</span>: <span class="hljs-number">49</span>,
    <span class="hljs-attr">a</span>: <span class="hljs-number">97</span>,
    <span class="hljs-attr">am</span>: <span class="hljs-number">20</span>,
    <span class="hljs-attr">developer</span>: <span class="hljs-number">49</span>,
    <span class="hljs-attr">by</span>: <span class="hljs-number">59</span>,
    <span class="hljs-attr">profession</span>: <span class="hljs-number">76</span>,
    <span class="hljs-attr">and</span>: <span class="hljs-number">70</span>,
    <span class="hljs-attr">love</span>: <span class="hljs-number">89</span>,
    <span class="hljs-attr">coding</span>: <span class="hljs-number">99</span>,
    <span class="hljs-attr">you</span>: <span class="hljs-number">100</span>,
    <span class="hljs-attr">he</span>: <span class="hljs-number">101</span>,
    <span class="hljs-attr">she</span>: <span class="hljs-number">102</span>,
};

<span class="hljs-keyword">const</span> mySentence = <span class="hljs-string">"I am a developer by profession and I love coding."</span>;
<span class="hljs-keyword">const</span> tokens = mySentence.split(<span class="hljs-string">" "</span>);
<span class="hljs-keyword">const</span> encodedTokens = tokens.map(
    <span class="hljs-function">(<span class="hljs-params">token</span>) =&gt;</span> OM_AI_MODEL_TOKEN_DICTIONARY[token]
);
<span class="hljs-built_in">console</span>.log(encodedTokens);
<span class="hljs-comment">// Output: [ 49, 20, 97, 49, 59, 76, 70, 49, 89, 99 ]</span>
</code></pre>
<h3 id="heading-decoding">Decoding:</h3>
<p>Converting numbers back into tokens that humans can understand.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> OM_AI_MODEL_TOKEN_DICTIONARY = {
    <span class="hljs-number">49</span>: <span class="hljs-string">"I"</span>,
    <span class="hljs-number">97</span>: <span class="hljs-string">"a"</span>,
    <span class="hljs-number">20</span>: <span class="hljs-string">"am"</span>,
    <span class="hljs-number">49</span>: <span class="hljs-string">"developer"</span>,
    <span class="hljs-number">59</span>: <span class="hljs-string">"by"</span>,
    <span class="hljs-number">76</span>: <span class="hljs-string">"profession"</span>,
    <span class="hljs-number">70</span>: <span class="hljs-string">"and"</span>,
    <span class="hljs-number">89</span>: <span class="hljs-string">"love"</span>,
    <span class="hljs-number">99</span>: <span class="hljs-string">"coding"</span>,
    <span class="hljs-number">100</span>: <span class="hljs-string">"you"</span>,
    <span class="hljs-number">101</span>: <span class="hljs-string">"he"</span>,
    <span class="hljs-number">102</span>: <span class="hljs-string">"she"</span>,
};

<span class="hljs-keyword">const</span> myEncodedSentence = [<span class="hljs-number">49</span>, <span class="hljs-number">20</span>, <span class="hljs-number">97</span>, <span class="hljs-number">49</span>, <span class="hljs-number">59</span>, <span class="hljs-number">76</span>, <span class="hljs-number">70</span>, <span class="hljs-number">49</span>, <span class="hljs-number">89</span>, <span class="hljs-number">99</span>];
<span class="hljs-keyword">const</span> decodedTokens = myEncodedSentence.map(
    <span class="hljs-function">(<span class="hljs-params">encodedToken</span>) =&gt;</span> OM_AI_MODEL_TOKEN_DICTIONARY[encodedToken]
);
<span class="hljs-built_in">console</span>.log(decodedTokens);
<span class="hljs-comment">// Output: [ 'I', 'am', 'a', 'developer', 'by', 'profession', 'and', 'I', 'love', 'coding.' ]</span>
</code></pre>
<h3 id="heading-vector-embedding">Vector Embedding:</h3>
<p>Vector embedding means turning words into lists of numbers so that the system can understand their meaning and find relationships between them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745783426792/ecf8b8f2-b6b9-4b0f-a20d-bd74a4785a1b.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-embedding">Embedding:</h3>
<p>An embedding is like a secret code that turns each word into a list of numbers so the AI model can understand if “chai” and “coffee” are similar.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745784014677/47c365c4-6f07-46e8-95e2-d4146659752a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-positional-encoding">Positional Encoding:</h3>
<p>Keeps track of words or tokens which come first, second, third and so on in a sentence. It helps the AI model to understand the order of words.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745779879275/125cbb7d-0686-4422-95e4-cbcdaddebaf4.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-semantic-meaning">Semantic Meaning:</h3>
<p>Semantic meaning is the actual meaning of words. For example: understanding “chai” means tea, not just letters C-H-A-I.</p>
<h3 id="heading-self-attention">Self-Attention:</h3>
<p>Self-attention is when each word in a sentence pays attention to all the other words to understand them better.</p>
<h3 id="heading-softmax">Softmax:</h3>
<p>Softmax function is like a magical decision-maker that helps an AI model choose the best option by turning numbers into chances or probabilities.</p>
<h3 id="heading-multi-head-attention">Multi-Head Attention:</h3>
<p>Multi-Head Attention allows a model to focus on different parts of a statement parallel to better understand various relationships.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745770103435/6b68762d-3d0a-4a92-8ab5-93696c929bb3.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-temperature-temp">Temperature (Temp):</h3>
<p>A parameter that controls randomness in the model during output generation. The low values make the model play safe and select the most likely word, while high values let it take creative risks.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745770264616/dc5d2da8-fa94-4744-881d-b212b5eec335.png" alt="Gen AI Low and High Temperature example" class="image--center mx-auto" /></p>
<h3 id="heading-knowledge-cut-off">Knowledge Cut-off:</h3>
<p>The last date AI model was trained on data. For example, if the knowledge cut-off is Dec 2020 then the AI model will not have information about events or developments that occurred after that date.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745753192911/28a84216-89fe-4669-bebe-906dd4d5f568.png" alt="Knowledge Cutoff example" class="image--center mx-auto" /></p>
<h3 id="heading-vocab-size">Vocab Size:</h3>
<p>Number of unique tokens in the AI model's dictionary or vocabulary. A larger dictionary size allows the AI model to understand or generate.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1745775998201/e27462c7-ef13-4921-95a9-3477bd926bc9.png" alt class="image--center mx-auto" /></p>
<p>Thank you for reading! 🚀</p>
<p>Happy learning! 😊</p>
]]></content:encoded></item><item><title><![CDATA[Introduction To Docker]]></title><description><![CDATA[When developers work on a project, there is a common issue that happens almost every time: the project works wonderfully on the developer's machine, but when it is moved to production, a server or another team member's computer, it fails to function ...]]></description><link>https://blog.omprakashpandey.com/introduction-to-docker</link><guid isPermaLink="true">https://blog.omprakashpandey.com/introduction-to-docker</guid><category><![CDATA[Docker]]></category><category><![CDATA[Devops]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sun, 15 Dec 2024 20:04:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734279260634/2e96fa2d-04ba-487d-88f0-218ba854e4cc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When developers work on a project, there is a common issue that happens almost every time: the project works wonderfully on the developer's machine, but when it is moved to production, a server or another team member's computer, it fails to function properly. This is commonly known as the <strong>"It Works on My Machine"</strong> problem.</p>
<h2 id="heading-the-it-works-on-my-machine-problem"><strong>The "It Works on My Machine" Problem</strong></h2>
<p>Consider creating a website with Node JS or PHP. On your local PC, everything works flawlessly like the code runs, the images load properly, and the routes are correctly configured. However, when you migrate the project to a production server or another environment, you encounter challenges such as:</p>
<ul>
<li><p>Images are not loading properly.</p>
</li>
<li><p>Path configurations breaking.</p>
</li>
<li><p>Missing dependencies or incorrect settings.</p>
</li>
</ul>
<p>This problem becomes more severe in large-scale projects that include programming languages like <strong>Node.js</strong>, <strong>Python</strong>, <strong>Java</strong>, <strong>Ruby</strong>, or <strong>PHP</strong> etc.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734293047022/16956373-d468-426b-b7c3-08fcbc6f7d27.png" alt class="image--center mx-auto" /></p>
<p>This is where <strong>Docker</strong> comes in to solve the problem.</p>
<h2 id="heading-what-is-docker"><strong>What is Docker?</strong></h2>
<p>Docker is mainly designed to solve the "It Works on My Machine" problem. It enables developers to package applications and environments in portable, lightweight, and isolated containers. These containers ensure that the application runs consistently across different machines.</p>
<p>It is compatible with nearly any programming language or project and it is a tool that creates airtight containers.</p>
<h2 id="heading-understanding-docker-containers"><strong>Understanding Docker Containers</strong></h2>
<p>At the heart of Docker are <strong>containers</strong>. These containers wrap up your:</p>
<ul>
<li><p>Code</p>
</li>
<li><p>Dependencies</p>
</li>
<li><p>Configuration files</p>
</li>
<li><p>Processes</p>
</li>
<li><p>Networking settings</p>
</li>
<li><p>(In some cases) a lightweight chunk of the operating system.</p>
</li>
</ul>
<h3 id="heading-key-features-of-docker-containers"><strong>Key Features of Docker Containers</strong></h3>
<ol>
<li><p><strong>Portability</strong>: Docker containers are portable and consistent. You can move them from one machine to another—whether it's your laptop, a colleague's computer, or a production server—and they will run the same way.</p>
</li>
<li><p><strong>Sealed Environment</strong>: Containers create a sealed, isolated environment where your application runs without being affected by the underlying system.</p>
</li>
<li><p><strong>Reusability</strong>: Containers can be reused and shared easily.</p>
</li>
</ol>
<p>With Docker, the phrase <em>"It works on my machine"</em> becomes irrelevant because the container behaves identically no matter where it is deployed.</p>
<h2 id="heading-docker-as-a-social-platform"><strong>Docker as a Social Platform</strong></h2>
<p>Docker doesn't just stop at solving local development problems. It also allows developers to share their containers like they would share a status update on social media.</p>
<p>For example:</p>
<ul>
<li><p>Instead of struggling to install <strong>MySQL</strong>, you can simply pull a Docker container preconfigured with MySQL and start using it instantly.</p>
</li>
<li><p>You can <strong>publish Docker containers</strong> and share them with others, so anyone can replicate your environment effortlessly.</p>
</li>
</ul>
<h2 id="heading-how-docker-works-the-three-essentials"><strong>How Docker Works: The Three Essentials</strong></h2>
<p>To summarize, Docker can be divided into three main components:</p>
<h3 id="heading-1-docker-as-a-client-side-application"><strong>1. Docker as a Client-Side Application</strong></h3>
<p>Docker acts as a client-side tool that you can install on your machine. It handles everything:</p>
<ul>
<li><p>Designing containers.</p>
</li>
<li><p>Packing your code, dependencies, and configurations.</p>
</li>
<li><p>Making the application portable.</p>
</li>
</ul>
<h3 id="heading-2-docker-as-a-service"><strong>2. Docker as a Service</strong></h3>
<p>Docker can also be deployed as a service on a server. This allows you to:</p>
<ul>
<li><p>Deploy containers anywhere.</p>
</li>
<li><p>Run your applications consistently in any environment.</p>
</li>
</ul>
<h3 id="heading-3-docker-as-a-social-platform"><strong>3. Docker as a Social Platform</strong></h3>
<p>Docker allows you to share and publish your containers:</p>
<ul>
<li><p>Developers can share their container images, similar to how you share files or posts on social media.</p>
</li>
<li><p>Others can download and start from a specific <strong>checkpoint</strong> of your application.</p>
</li>
</ul>
<h2 id="heading-why-developers-should-use-containers"><strong>Why Developers Should Use Containers</strong></h2>
<ol>
<li><p><strong>Consistency</strong>: Docker ensures your project runs the same on any machine.</p>
</li>
<li><p><strong>Portability</strong>: Containers can be deployed anywhere—on local systems, servers, or the cloud.</p>
</li>
<li><p><strong>Simplified Installation:</strong> Complex installations, like MySQL or Python libraries, become frictionless with Docker containers.</p>
</li>
<li><p><strong>Collaboration</strong>: Sharing containers makes it easy for teams to work together seamlessly.</p>
</li>
<li><p><strong>Isolation</strong>: Each container runs in its own environment, preventing conflicts between applications.</p>
</li>
<li><p><strong>Scalability</strong>: Docker makes it easy to scale applications by deploying multiple containers.</p>
</li>
</ol>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Docker solves the well-known "It Works on My Machine" problem by creating portable, sealed, and shareable containers that perform similarly in all contexts. Whether you're running a tiny web app or a large-scale project, Docker provides a uniform and smooth experience for developers and production teams.</p>
<p>If you haven't already explored Docker, now is the time to get started and simplify your development process!</p>
<p>Thank you for reading! 🚀</p>
<p>Happy learning! 😊</p>
]]></content:encoded></item><item><title><![CDATA[Understanding ECMA Standards and Data Types in JavaScript]]></title><description><![CDATA[JavaScript has been at the heart of dynamic and interactive web development for decades. ECMAScript is the standard that defines JavaScript's behaviour. The idea of ECMA standards and the data types that support JavaScript is essential to understandi...]]></description><link>https://blog.omprakashpandey.com/understanding-ecma-standards-and-data-types-in-javascript</link><guid isPermaLink="true">https://blog.omprakashpandey.com/understanding-ecma-standards-and-data-types-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sun, 01 Dec 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734273223558/63d9b528-3657-4a61-beb7-b8c3a693e8ff.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript has been at the heart of dynamic and interactive web development for decades. <a target="_blank" href="https://tc39.es/ecma262"><strong>ECMAScript</strong></a> is the standard that defines JavaScript's behaviour. The idea of ECMA standards and the data types that support JavaScript is essential to understanding and using the language efficiently.</p>
<h2 id="heading-what-is-ecma-and-ecmascript">What is ECMA and ECMAScript?</h2>
<p>The <strong>ECMA</strong> (European Computer Manufacturers Association) is an organization that standardizes information and communication systems. <a target="_blank" href="https://tc39.es/ecma262">ECMAScript</a>, commonly abbreviated as <strong>ES</strong>, is the specification that standardizes JavaScript, ensuring consistent behavior across different environments.</p>
<h4 id="heading-a-brief-history-of-ecmascript">A Brief History of ECMAScript:</h4>
<ul>
<li><p><strong>1997</strong>: The first edition of ECMAScript (ES1) was published.</p>
</li>
<li><p><strong>2009</strong>: ES5 introduced significant features like strict mode and JSON support.</p>
</li>
<li><p><strong>2015</strong>: ES6 (also called ES2015) revolutionized JavaScript with features like <code>let</code>, <code>const</code>, arrow functions, classes, and modules.</p>
</li>
<li><p><strong>Ongoing</strong>: New features are added yearly (e.g., <code>async/await</code>, optional chaining, and nullish coalescing).</p>
</li>
</ul>
<p>Each update of ECMAScript brings enhancements to the language, maintaining its relevance and usability in modern development.</p>
<h3 id="heading-javascript-data-types">JavaScript Data Types</h3>
<p>Data types in JavaScript are fundamental to understanding how the language operates. JavaScript classifies its data types into two broad categories: <code>primitive types</code> and <code>non-primitive types</code> (objects).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1734272736009/47fa6290-3a66-4188-bde8-16cad8e433cb.png" alt="JavaScript Data Types" class="image--center mx-auto" /></p>
<h2 id="heading-1-primitive-data-types">1. <strong>Primitive Data Types</strong></h2>
<p>In JavaScript, primitive data types are the basic building blocks of data. They represent single values and are immutable, meaning they cannot be changed once created.</p>
<ul>
<li><p><strong>Undefined</strong>: Represents a variable that has been declared but not assigned a value.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> a;
  <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// undefined</span>
</code></pre>
</li>
<li><p><strong>Null</strong>: Represents an intentional absence of value.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> b = <span class="hljs-literal">null</span>;
  <span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// null</span>
</code></pre>
</li>
<li><p><strong>Boolean</strong>: Represents logical values: <code>true</code> or <code>false</code>.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> isActive = <span class="hljs-literal">true</span>;
  <span class="hljs-built_in">console</span>.log(isActive); <span class="hljs-comment">// true</span>
</code></pre>
</li>
<li><p><strong>Number</strong>: Represents both integers and floating-point numbers.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> age = <span class="hljs-number">25</span>;
  <span class="hljs-keyword">let</span> pi = <span class="hljs-number">3.14</span>;
</code></pre>
<p>  <strong>Special Numeric Values</strong>: <code>Infinity</code>, <code>-Infinity</code>, and <code>NaN</code> (Not-a-Number).</p>
</li>
<li><p><strong>BigInt</strong>: Represents integers larger than <code>2^53 - 1</code> or less than <code>-(2^53 - 1)</code>.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> bigNumber = <span class="hljs-number">123456789012345678901234567890n</span>;
</code></pre>
</li>
<li><p><strong>String</strong>: Represents a sequence of characters.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello, Keerthy!"</span>;
</code></pre>
</li>
<li><p><strong>Symbol</strong>: Introduced in ES6, it creates unique identifiers.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> id = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"id"</span>);
</code></pre>
</li>
</ul>
<h2 id="heading-2-non-primitive-data-types-objects">2. <strong>Non-Primitive Data Types (Objects)</strong></h2>
<p>In JavaScript, Objects are non-primitive data types derived from primitive types. They are also called reference or derived data types. Non-primitive variables are stored in heap memory, while primitive variables are stored in stack memory.</p>
<ul>
<li><p><strong>Object</strong>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">"Keerthy"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
</code></pre>
</li>
<li><p><strong>Array</strong>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
</code></pre>
</li>
<li><p><strong>Function</strong>:</p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello DOSA!"</span>);
  }
</code></pre>
</li>
</ul>
<h2 id="heading-strict-mode-in-javascript">Strict Mode in JavaScript</h2>
<p>Introduced in ES5, <strong>strict mode</strong> enforces stricter parsing and error handling in JavaScript, helping developers avoid common mistakes.</p>
<h4 id="heading-enabling-strict-mode">Enabling Strict Mode:</h4>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>;
x = <span class="hljs-number">10</span>; <span class="hljs-comment">// ReferenceError: x is not defined</span>
</code></pre>
<p>Benefits of strict mode include:</p>
<ol>
<li><p>Preventing the use of undeclared variables.</p>
</li>
<li><p>Eliminating duplicate parameter names in functions.</p>
</li>
<li><p>Throwing errors for assignments to non-writable properties.</p>
</li>
</ol>
<hr />
<h2 id="heading-best-practices-in-javascript">Best Practices in JavaScript</h2>
<p>To write clean and maintainable code, follow these best practices:</p>
<h3 id="heading-1-use-let-and-const-instead-of-var">1. <strong>Use</strong> <code>let</code> and <code>const</code> Instead of <code>var</code></h3>
<p><code>let</code> and <code>const</code> were introduced in ES6 to provide block scoping and prevent hoisting-related issues.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> PI = <span class="hljs-number">3.14</span>; <span class="hljs-comment">// Use const for constants</span>
<span class="hljs-keyword">let</span> age = <span class="hljs-number">25</span>; <span class="hljs-comment">// Use let for variables</span>
</code></pre>
<h3 id="heading-2-prefer-strict-equality">2. <strong>Prefer Strict Equality (</strong><code>===</code>)</h3>
<p>Always use <code>===</code> to avoid unexpected type coercion.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">5</span> == <span class="hljs-string">"5"</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">5</span> === <span class="hljs-string">"5"</span>); <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-3-avoid-global-variables">3. <strong>Avoid Global Variables</strong></h3>
<p>Minimize the use of global variables to prevent unintended side effects.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user = <span class="hljs-string">"Tony Stark"</span>; <span class="hljs-comment">// Declare variables in the appropriate scope (e.g., inside a function)</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> user = <span class="hljs-string">"peter parker"</span>; <span class="hljs-comment">// Local variable</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${user}</span>!`</span>);
}
</code></pre>
<h3 id="heading-4-handle-null-and-undefined-gracefully">4. <strong>Handle Null and Undefined Gracefully</strong></h3>
<p>Use optional chaining and nullish coalescing to handle undefined or null values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user = <span class="hljs-literal">null</span>;
<span class="hljs-built_in">console</span>.log(user?.name ?? <span class="hljs-string">"Guest"</span>); <span class="hljs-comment">// "Guest"</span>
</code></pre>
<h3 id="heading-5-use-descriptive-variable-names">5. <strong>Use Descriptive Variable Names</strong></h3>
<p>Choose variable names that describe their purpose for better readability.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> userAge = <span class="hljs-number">30</span>; <span class="hljs-comment">// Clear and meaningful</span>
</code></pre>
<h3 id="heading-6-leverage-modern-es-features">6. <strong>Leverage Modern ES Features</strong></h3>
<p>Use features like arrow functions, template literals, and destructuring for cleaner code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> greet = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
</code></pre>
<h3 id="heading-7-write-modular-code">7. <strong>Write Modular Code</strong></h3>
<p>Split your code into smaller, reusable functions or modules.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateArea</span>(<span class="hljs-params">radius</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * radius * radius;
}
</code></pre>
<h3 id="heading-8-handle-errors-effectively">8. <strong>Handle Errors Effectively</strong></h3>
<p>Use <code>try...catch</code> to handle exceptions and provide meaningful feedback.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
    <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-string">"{invalid}"</span>);
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error parsing JSON:"</span>, error.message);
}
</code></pre>
<h3 id="heading-9-comment-wisely">9. <strong>Comment Wisely</strong></h3>
<p>Add comments to clarify complex logic but avoid over-commenting obvious code.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Calculate the area of a circle</span>
<span class="hljs-keyword">const</span> area = <span class="hljs-built_in">Math</span>.PI * radius ** <span class="hljs-number">2</span>;
</code></pre>
<h3 id="heading-10-follow-a-style-guide">10. <strong>Follow a Style Guide</strong></h3>
<p>Use tools like ESLint and Prettier to enforce consistent coding styles across your project.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Understanding ECMA standards and JavaScript data types is the first step toward mastering the language. Write clear, effective, and maintainable code by combining this knowledge with best practices and contemporary ES features. By following best practices and staying up to speed with ECMAScript changes, you'll be prepared to deal with JavaScript's peculiarities and fully utilize its potential.</p>
<p>Happy coding! 🎉</p>
]]></content:encoded></item><item><title><![CDATA[Understanding let, const and var in JavaScript]]></title><description><![CDATA[Introduction
In JavaScript, the use of let, const, and var for variable declarations is not just a matter of syntax, but a crucial aspect of writing clean and efficient code. Understanding the distinctions between these declarations is of paramount i...]]></description><link>https://blog.omprakashpandey.com/understanding-let-const-and-var-in-javascript</link><guid isPermaLink="true">https://blog.omprakashpandey.com/understanding-let-const-and-var-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sat, 30 Nov 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733607267968/dd4c5ce9-26bf-431d-a983-219fe41b898e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In JavaScript, the use of <code>let</code>, <code>const</code>, and <code>var</code> for variable declarations is not just a matter of syntax, but a crucial aspect of writing clean and efficient code. Understanding the distinctions between these declarations is of paramount importance.</p>
<h2 id="heading-var">var</h2>
<p>Since the beginning of JavaScript, the <code>var</code> keyword has existed. Variables declared with <code>var</code> are function-scoped, which means that the function in which they are declared can access them. They are globally scoped if they are declared outside of a function. The fact that <code>var</code> permits variable hoisting—a JavaScript technique that places variables and function declarations at the top of their contained scope during compilation—is one of its primary problems. This may result in unanticipated actions.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// undefined</span>
<span class="hljs-keyword">var</span> x = <span class="hljs-number">5</span>;

<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 5</span>
</code></pre>
<h2 id="heading-let">let</h2>
<p>The <code>let</code> keyword, introduced in ES6 (ECMAScript 2015), brings your code a new level of predictability. Variables declared with <code>let</code> are block-scoped, meaning they are only accessible within the block they are declared in, thereby preventing issues related to variable hoisting.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">let</span> y = <span class="hljs-number">10</span>;
    <span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// 10</span>
}

<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// ReferenceError: y is not defined</span>
</code></pre>
<h2 id="heading-const">const</h2>
<p>The <code>const</code> keyword, also introduced in ES6, is used to declare variables that are meant to be constant and should not be reassigned. Like <code>let</code>, <code>const</code> is block-scoped. However, it is essential to note that <code>const</code> does not make the variable immutable; it only prevents the reassignment of the variable itself.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> z = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(z); <span class="hljs-comment">// 20</span>

z = <span class="hljs-number">30</span>; <span class="hljs-comment">// TypeError: Assignment to constant variable.</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Choosing between <code>let</code>, <code>const</code>, and <code>var</code> depends on the use case. Generally, it is recommended to use <code>const</code> by default and <code>let</code> if you know the variable will need to be reassigned. The use of <code>var</code> is discouraged due to its function-scoping and hoisting behaviour, which can lead to bugs and unpredictable code.</p>
<p>You can write more robust and maintainable JavaScript code by understanding these differences.</p>
<p>Thanks for reading! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[My Journey to Building Reusable Components in React]]></title><description><![CDATA[I still remember my first React.js project, which I worked on with two classmates during a college hackathon five or six years ago. One of the most frustrating parts of that experience was the repetitive process of creating UI components. I had to co...]]></description><link>https://blog.omprakashpandey.com/my-journey-to-building-reusable-components-in-react</link><guid isPermaLink="true">https://blog.omprakashpandey.com/my-journey-to-building-reusable-components-in-react</guid><category><![CDATA[React Native]]></category><category><![CDATA[Reusable Components]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sat, 23 Nov 2024 12:08:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732364809119/c5bae61f-ce55-4f5c-a677-87b0c3de780d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I still remember my first React.js project, which I worked on with two classmates during a college hackathon five or six years ago. One of the most frustrating parts of that experience was the repetitive process of creating UI components. I had to copy and paste the same button, form, and table code over and over again, tweaking each instance individually.</p>
<p>When I wanted to change the styling of a button, I had to track down every occurrence, leading to redundant work and wasted time. The more the project grew, the harder it became to manage. It felt like I spent more time maintaining the codebase and fixing bugs than building new features.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732362195627/dc4acc27-7243-42ff-88d9-de4964f5c5ce.webp" alt="Repetitive Coding Frustration" /></p>
<p>Over time, I discovered the value of <strong>reusable components</strong>, which not only simplified my workflow but also transformed how I approach code design and project management. In this blog, I want to share my insights into building reusable components in React and how they can save time and effort in your projects.</p>
<h2 id="heading-what-are-reusable-components">What Are Reusable Components?</h2>
<p>In React, a <strong>component</strong> is a self-contained, reusable piece of UI. A <strong>reusable component</strong> is a component designed to be generic and adaptable so that it can be used in multiple places across an application with little or no modification.</p>
<p>For example, a <strong>Button</strong> component can be designed to handle a variety of use cases, such as form submissions, navigation, or alerts, by simply passing different properties (props) to it.</p>
<h2 id="heading-steps-to-build-reusable-components">Steps to Build Reusable Components</h2>
<h3 id="heading-1-identify-common-patterns">1. <strong>Identify Common Patterns</strong></h3>
<p>The first step is to identify the common UI patterns in your application. Look for repetitive elements like buttons, forms, tables, modals, or any other component that appears in multiple places. These are prime candidates for refactoring into reusable components.</p>
<h3 id="heading-2-design-components-with-props">2. <strong>Design Components with Props</strong></h3>
<p>Props allow you to pass data and configurations to a component, making it flexible for various use cases. This is key to building reusable components.</p>
<p>Here’s an example of a reusable <strong>Button</strong> component:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Button.ts</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">interface</span> ButtonProps <span class="hljs-keyword">extends</span> React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt; {
    theme?: <span class="hljs-string">"primary"</span> | <span class="hljs-string">"secondary"</span>; <span class="hljs-comment">// Define specific themes</span>
    loading?: <span class="hljs-built_in">boolean</span>; <span class="hljs-comment">// Optional prop to indicate loading state</span>
}

<span class="hljs-keyword">const</span> Button: React.FC&lt;ButtonProps&gt; = <span class="hljs-function">(<span class="hljs-params">{
    className,
    children,
    theme = <span class="hljs-string">"primary"</span>,
    onClick,
    disabled = <span class="hljs-literal">false</span>,
    loading = <span class="hljs-literal">false</span>,
    ...rest
}</span>) =&gt;</span> (
    &lt;button
        className={<span class="hljs-string">`<span class="hljs-subst">${className}</span> bg-<span class="hljs-subst">${theme}</span>`</span>} <span class="hljs-comment">// Apply dynamic styles</span>
        onClick={onClick}
        disabled={disabled || loading}
        {...rest}
    &gt;
        {loading ? <span class="hljs-string">"Loading..."</span> : children} {<span class="hljs-comment">/* Show loader if loading */</span>}
    &lt;/button&gt;
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;
</code></pre>
<p><strong>Props Breakdown:</strong></p>
<ul>
<li><p><code>theme</code>: Specifies the button style (e.g., <code>"primary"</code> or <code>"secondary"</code>).</p>
</li>
<li><p><code>loading</code>: A flag indicating whether the button is in a loading state.</p>
</li>
<li><p><code>...rest</code>: Allows passing additional props like <code>id</code>, <code>type</code>, or <code>aria-label</code>.</p>
</li>
</ul>
<p><strong>Usage:</strong></p>
<pre><code class="lang-typescript">&lt;Button onClick={<span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">"Primary Button clicked"</span>)}&gt;
    Primary Button
&lt;/Button&gt;

&lt;Button
    theme=<span class="hljs-string">"secondary"</span>
    onClick={<span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">"Secondary Button clicked"</span>)}
&gt;
    Secondary Button
&lt;/Button&gt;
</code></pre>
<h3 id="heading-3-use-composition-for-flexibility">3. <strong>Use Composition for Flexibility</strong></h3>
<p>Composition is a powerful tool for building flexible and reusable components. Instead of relying solely on props, you can use <code>children</code> to pass nested content or even wrap other components.</p>
<p>Here’s an example of a <strong>Card</strong> component that uses composition:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Card.ts</span>
<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">interface</span> CardProps {
    title: <span class="hljs-built_in">string</span>;
    children: React.ReactNode; <span class="hljs-comment">// Allows nested content</span>
}

<span class="hljs-keyword">const</span> Card: React.FC&lt;CardProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ title, children }</span>) =&gt;</span> (
    &lt;div className=<span class="hljs-string">"card"</span>&gt;
        &lt;div className=<span class="hljs-string">"card-header"</span>&gt;{title}&lt;/div&gt;
        &lt;div className=<span class="hljs-string">"card-body"</span>&gt;{children}&lt;/div&gt;
    &lt;/div&gt;
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Card;
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code class="lang-typescript">&lt;Card title=<span class="hljs-string">"My Card"</span>&gt;
    &lt;p&gt;This is the content <span class="hljs-keyword">of</span> my card.&lt;/p&gt;
&lt;/Card&gt;
</code></pre>
<h3 id="heading-4-follow-a-consistent-styling-approach">4. <strong>Follow a Consistent Styling Approach</strong></h3>
<p>A consistent styling approach ensures your components are easy to maintain and work seamlessly across the application. Popular options include:</p>
<ul>
<li><p><strong>CSS Modules</strong>: Scoped CSS to avoid conflicts.</p>
</li>
<li><p><strong>Styled Components</strong>: CSS-in-JS for dynamic styling.</p>
</li>
<li><p><strong>Tailwind CSS</strong>: Utility-first CSS framework.</p>
</li>
</ul>
<p>Choose the method that aligns with your team’s workflow and project requirements.</p>
<h3 id="heading-5-test-your-components">5. <strong>Test Your Components</strong></h3>
<p>Testing ensures your components work correctly and prevents regressions. Use tools like <strong>Jest</strong> and <strong>React Testing Library</strong> to write unit tests for your components. Test for various states, props, and edge cases.</p>
<h2 id="heading-advanced-concept-for-building-reusable-components">Advanced Concept for Building Reusable Components</h2>
<p>Once you've mastered the basics of reusable components, it's time to explore advanced techniques that make your components even more flexible, maintainable, and scalable. Here are some advanced approaches to consider:</p>
<h3 id="heading-1-controlled-vs-uncontrolled-components">1. <strong>Controlled vs. Uncontrolled Components</strong></h3>
<p>Reusable components often need to manage state, such as form inputs or toggles. Choosing between <strong>controlled</strong> (fully managed by parent components) and <strong>uncontrolled</strong> (internally managed) behaviors can make a significant difference in flexibility.</p>
<h4 id="heading-controlled-components">Controlled Components</h4>
<p>With controlled components, all state is passed via props and managed by the parent. This allows fine-grained control and synchronization across components.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> InputProps {
    value: <span class="hljs-built_in">string</span>;
    onChange: <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>;
}

<span class="hljs-keyword">const</span> Input: React.FC&lt;InputProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ value, onChange }</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> &lt;input value={value} onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> onChange(e.target.value)} /&gt;;
};

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> [inputValue, setInputValue] = React.useState(<span class="hljs-string">""</span>);

&lt;Input value={inputValue} onChange={setInputValue} /&gt;;
</code></pre>
<h4 id="heading-uncontrolled-components">Uncontrolled Components</h4>
<p>Uncontrolled components manage their own state internally. They are easier to use for simple scenarios but less flexible for complex workflows.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> InputProps {
    defaultValue?: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">const</span> Input: React.FC&lt;InputProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ defaultValue }</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [value, setValue] = React.useState(defaultValue || <span class="hljs-string">""</span>);

    <span class="hljs-keyword">return</span> &lt;input value={value} onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setValue(e.target.value)} /&gt;;
};

<span class="hljs-comment">// Usage</span>
&lt;Input defaultValue=<span class="hljs-string">"Hello"</span> /&gt;;
</code></pre>
<p><strong>Tip:</strong> Provide the ability to switch between controlled and uncontrolled behavior for maximum reusability.</p>
<h3 id="heading-2-higher-order-components-hocs">2. <strong>Higher-Order Components (HOCs)</strong></h3>
<p><em>HOCs are functions that take a component and return an enhanced version of it.</em></p>
<p>Use HOCs when you need to add common functionality to multiple components, such as logging, error handling, or data fetching, without repeating logic.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withLogging</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">WrappedComponent: React.ComponentType&lt;T&gt;</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">props: T</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Component rendered with props:"</span>, props);
        <span class="hljs-keyword">return</span> &lt;WrappedComponent {...props} /&gt;;
    };
}

<span class="hljs-comment">// Example component</span>
<span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ label }: { label: <span class="hljs-built_in">string</span> }</span>) =&gt;</span> &lt;button&gt;{label}&lt;/button&gt;;

<span class="hljs-comment">// Wrap the component with logging</span>
<span class="hljs-keyword">const</span> LoggedButton = withLogging(Button);

<span class="hljs-comment">// Usage</span>
&lt;LoggedButton label=<span class="hljs-string">"Click Me"</span> /&gt;;
</code></pre>
<p><strong>Use Cases:</strong> Logging, Authorization and Error Boundaries</p>
<h3 id="heading-3-render-props">3. <strong>Render Props</strong></h3>
<p><em>Render props are functions passed as props that define how a component should render its children.</em></p>
<p>This pattern allows reusable components to provide flexibility for rendering logic.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> DataFetcherProps {
    url: <span class="hljs-built_in">string</span>;
    children: <span class="hljs-function">(<span class="hljs-params">data: <span class="hljs-built_in">any</span>, loading: <span class="hljs-built_in">boolean</span>, error: <span class="hljs-built_in">any</span></span>) =&gt;</span> React.ReactNode;
}

<span class="hljs-keyword">const</span> DataFetcher: React.FC&lt;DataFetcherProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ url, children }</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [data, setData] = React.useState(<span class="hljs-literal">null</span>);
    <span class="hljs-keyword">const</span> [loading, setLoading] = React.useState(<span class="hljs-literal">true</span>);
    <span class="hljs-keyword">const</span> [error, setError] = React.useState(<span class="hljs-literal">null</span>);

    React.useEffect(<span class="hljs-function">() =&gt;</span> {
        fetch(url)
            .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())
            .then(setData)
            .catch(setError)
            .finally(<span class="hljs-function">() =&gt;</span> setLoading(<span class="hljs-literal">false</span>));
    }, [url]);

    <span class="hljs-keyword">return</span> &lt;&gt;{children(data, loading, error)}&lt;/&gt;;
};

<span class="hljs-comment">// Usage</span>
&lt;DataFetcher url=<span class="hljs-string">"/api/data"</span>&gt;
    {<span class="hljs-function">(<span class="hljs-params">data, loading, error</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> &lt;p&gt;Loading...&lt;/p&gt;;
        <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> &lt;p&gt;<span class="hljs-built_in">Error</span>: {error.message}&lt;/p&gt;;
        <span class="hljs-keyword">return</span> &lt;p&gt;Data: {<span class="hljs-built_in">JSON</span>.stringify(data)}&lt;/p&gt;;
    }}
&lt;/DataFetcher&gt;;
</code></pre>
<p><strong>Use Cases:</strong></p>
<ul>
<li>Customizing rendering logic for data fetching, forms, or dynamic UIs.</li>
</ul>
<h3 id="heading-4-custom-hooks-for-logic-extraction">4. <strong>Custom Hooks for Logic Extraction</strong></h3>
<p>To keep your reusable components simple, extract shared logic into <strong>custom hooks</strong>. This separates UI and logic, making both easier to test and reuse.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCounter</span>(<span class="hljs-params">initialValue: <span class="hljs-built_in">number</span> = 0</span>) </span>{
    <span class="hljs-keyword">const</span> [count, setCount] = React.useState(initialValue);
    <span class="hljs-keyword">const</span> increment = <span class="hljs-function">() =&gt;</span> setCount(<span class="hljs-function">(<span class="hljs-params">prev</span>) =&gt;</span> prev + <span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> decrement = <span class="hljs-function">() =&gt;</span> setCount(<span class="hljs-function">(<span class="hljs-params">prev</span>) =&gt;</span> prev - <span class="hljs-number">1</span>);

    <span class="hljs-keyword">return</span> { count, increment, decrement };
}

<span class="hljs-comment">// Component using the custom hook</span>
<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { count, increment, decrement } = useCounter(<span class="hljs-number">5</span>);

    <span class="hljs-keyword">return</span> (
        &lt;div&gt;
            &lt;p&gt;Count: {count}&lt;/p&gt;
            &lt;button onClick={increment}&gt;Increment&lt;/button&gt;
            &lt;button onClick={decrement}&gt;Decrement&lt;/button&gt;
        &lt;/div&gt;
    );
};
</code></pre>
<p><strong>Benefits:</strong></p>
<ul>
<li><p>Logic reuse across multiple components.</p>
</li>
<li><p>Clear separation of concerns.</p>
</li>
</ul>
<h3 id="heading-5-context-for-global-state-sharing">5. <strong>Context for Global State Sharing</strong></h3>
<p>Use React's <strong>Context API</strong> to create reusable components that share state or configuration globally.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> ThemeContext = React.createContext(<span class="hljs-string">"light"</span>);

<span class="hljs-keyword">const</span> ThemeProvider: React.FC&lt;{ children: React.ReactNode }&gt; = <span class="hljs-function">(<span class="hljs-params">{
    children,
}</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> [theme, setTheme] = React.useState(<span class="hljs-string">"light"</span>);
    <span class="hljs-keyword">return</span> (
        &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;
            {children}
        &lt;/ThemeContext.Provider&gt;
    );
};

<span class="hljs-keyword">const</span> Button = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { theme } = React.useContext(ThemeContext);
    <span class="hljs-keyword">return</span> &lt;button className={<span class="hljs-string">`btn-<span class="hljs-subst">${theme}</span>`</span>}&gt;Themed Button&lt;/button&gt;;
};

<span class="hljs-comment">// Usage</span>
&lt;ThemeProvider&gt;
    &lt;Button /&gt;
&lt;/ThemeProvider&gt;;
</code></pre>
<p><strong>Use Cases:</strong> Theming, Authentication and Localization</p>
<h3 id="heading-6-dynamic-component-rendering">6. <strong>Dynamic Component Rendering</strong></h3>
<p>For highly reusable and flexible UIs, create components that dynamically render based on configuration or data.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Field {
    <span class="hljs-keyword">type</span>: <span class="hljs-built_in">string</span>;
    name: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> DynamicFormProps {
    fields: Field[];
}

<span class="hljs-keyword">const</span> DynamicForm: React.FC&lt;DynamicFormProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ fields }</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        &lt;form&gt;
            {fields.map(<span class="hljs-function">(<span class="hljs-params">field</span>) =&gt;</span> {
                <span class="hljs-keyword">switch</span> (field.type) {
                    <span class="hljs-keyword">case</span> <span class="hljs-string">"text"</span>:
                        <span class="hljs-keyword">return</span> (
                            &lt;input
                                key={field.name}
                                name={field.name}
                                <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
                            /&gt;
                        );
                    <span class="hljs-keyword">case</span> <span class="hljs-string">"checkbox"</span>:
                        <span class="hljs-keyword">return</span> (
                            &lt;input
                                key={field.name}
                                name={field.name}
                                <span class="hljs-keyword">type</span>=<span class="hljs-string">"checkbox"</span>
                            /&gt;
                        );
                    <span class="hljs-keyword">default</span>:
                        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
                }
            })}
        &lt;/form&gt;
    );
};

<span class="hljs-comment">// Usage</span>
&lt;DynamicForm
    fields={[
        { <span class="hljs-keyword">type</span>: <span class="hljs-string">"text"</span>, name: <span class="hljs-string">"username"</span> },
        { <span class="hljs-keyword">type</span>: <span class="hljs-string">"checkbox"</span>, name: <span class="hljs-string">"subscribe"</span> },
    ]}
/&gt;;
</code></pre>
<p><strong>Benefits:</strong></p>
<ul>
<li><p>Minimizes hardcoding of repetitive structures like forms and tables.</p>
</li>
<li><p>Facilitates dynamic UIs that can be driven by configurations or APIs.</p>
</li>
</ul>
<h3 id="heading-7-custom-hook-for-managing-asynchronous-transitions">7. Custom Hook for Managing Asynchronous Transitions</h3>
<p>For components that require handling asynchronous transitions (e.g., loading states during network requests), you can create a custom hook to manage the transition state efficiently.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">type</span> TransitionCallback = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">void</span>&gt;;

<span class="hljs-keyword">const</span> useTransition = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [isPending, setIsPending] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> startTransition = <span class="hljs-keyword">async</span> (callback: TransitionCallback) =&gt; {
    setIsPending(<span class="hljs-literal">true</span>);
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> callback();
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error during transition:"</span>, error);
    } <span class="hljs-keyword">finally</span> {
      setIsPending(<span class="hljs-literal">false</span>);
    }
  };

  <span class="hljs-keyword">return</span> [isPending, startTransition] <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useTransition;
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [isPending, startTransition] = useTransition();

    <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
        startTransition(<span class="hljs-keyword">async</span> () =&gt; {
            <span class="hljs-comment">// Simulate a network request or some async operation</span>
            <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Transition complete"</span>);
        });
    };

    <span class="hljs-keyword">return</span> (
        &lt;div&gt;
            &lt;button onClick={handleClick} disabled={isPending}&gt;
                {isPending ? <span class="hljs-string">"Loading..."</span> : <span class="hljs-string">"Click Me"</span>}
            &lt;/button&gt;
        &lt;/div&gt;
    );
};
</code></pre>
<h2 id="heading-best-practices-for-reusable-components">Best Practices for Reusable Components</h2>
<ol>
<li><p><strong>Keep Components Small and Focused (Single Responsibility Principle)</strong> Each component should handle a single responsibility. For example, a <strong>Button</strong> should render a button and handle click events, but it shouldn’t manage application state or business logic.</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// Bad</span>
 <span class="hljs-keyword">const</span> Button = <span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> [count, setCount] = React.useState(<span class="hljs-number">0</span>);
     <span class="hljs-keyword">return</span> (
         &lt;button onClick={<span class="hljs-function">() =&gt;</span> setCount(<span class="hljs-function">(<span class="hljs-params">prev</span>) =&gt;</span> prev + <span class="hljs-number">1</span>)}&gt;
             Clicked {count} times
         &lt;/button&gt;
     );
 };

 <span class="hljs-comment">// Good</span>
 <span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ onClick, children }</span>) =&gt;</span> (
     &lt;button onClick={onClick}&gt;{children}&lt;/button&gt;
 );
</code></pre>
</li>
<li><p><strong>Use Clear and Descriptive Prop Names</strong> Choose prop names that clearly convey their purpose. For instance, use <code>theme</code> instead of <code>color</code> if the prop controls the button’s style.</p>
<pre><code class="lang-typescript"> <span class="hljs-comment">// Bad</span>
 &lt;Button color=<span class="hljs-string">"primary"</span>&gt;Primary Button&lt;/Button&gt;;

 <span class="hljs-comment">// Good</span>
 &lt;Button theme=<span class="hljs-string">"primary"</span>&gt;Primary Button&lt;/Button&gt;;
</code></pre>
</li>
<li><p><strong>Provide Default Props (Open/Closed Principle)</strong> Set default values for props to ensure the component works even when certain props are omitted.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ theme = <span class="hljs-string">"primary"</span>, ...rest }</span>) =&gt;</span> (
     &lt;button className={<span class="hljs-string">`btn-<span class="hljs-subst">${theme}</span>`</span>} {...rest} /&gt;
 );
</code></pre>
</li>
<li><p><strong>Avoid Over-Optimization (Keep It Simple, Stupid)</strong> Don’t try to make your components handle every possible use case. Focus on common scenarios, and allow flexibility for edge cases through props or composition.</p>
</li>
<li><p><strong>Write Documentation</strong> Clear documentation helps other developers understand how to use your components. Include usage examples and explain the available props.</p>
</li>
<li><p><strong>Test Thoroughly</strong> Reusable components are used throughout your application, so ensure they are robust and well-tested.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Building reusable components in React requires striking a balance between simplicity and flexibility. By focusing on component isolation, prop-driven customization, and efficient composition, you can create a library of components that speeds up development, ensures consistency, and simplifies project maintenance.</p>
<p>What reusable components have you found most valuable in your projects? Let me know in the comments below—I’d love to hear your experiences!</p>
<p>Thanks for reading! 🚀</p>
]]></content:encoded></item><item><title><![CDATA[Micro Frontends: An Introduction and Comprehensive Overview]]></title><description><![CDATA[A few months back, I got a chance to work on a legacy project with an AngularJS frontend and a PHP backend. The project about 10-15 years old, had grown complex and difficult to maintain featuring over 50 modules like role management, user management...]]></description><link>https://blog.omprakashpandey.com/micro-frontends-an-introduction-and-comprehensive-overview</link><guid isPermaLink="true">https://blog.omprakashpandey.com/micro-frontends-an-introduction-and-comprehensive-overview</guid><category><![CDATA[React]]></category><category><![CDATA[Microfrontend]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Fri, 18 Oct 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1753346084592/445912c7-0365-42c6-9f3c-a9606a4c0eb8.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A few months back, I got a chance to work on a legacy project with an AngularJS frontend and a PHP backend. The project about 10-15 years old, had grown complex and difficult to maintain featuring over 50 modules like role management, user management, dynamic report generation and invoice management. Our team were searching for a solution to improve scalability and manageability, which led us to explore microservices on the backend and micro frontend for the frontend. I found the concept of micro frontend intriguing and gained valuable insights along the way.</p>
<p>In this blog, I’ll explain micro frontends, why they are essential, how to implement them, and the advantages they offer. Let's dive in!</p>
<h2 id="heading-the-challenges-in-scaling-large-frontend-applications">The Challenges In Scaling Large Frontend Applications</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753345806226/4c6cde58-81ed-4a21-9cc6-dcbdba210f89.webp" alt /></p>
<p>In today's fast-paced web development industry, scaling large frontend applications presents a number of issues. As applications become increasingly complex, upgrading to a new framework like React, Vue, or Angular may bring some relief, but even these technologies will eventually age and require another revamp. A complete rewrite every few years is time-consuming, costly, and disruptive to development teams.</p>
<p>In addition, large-scale applications sometimes result in slower development cycles since several teams work on the same codebase, resulting in frequent merge conflicts, code dependencies, and coordination difficulties. Maintaining such a monolithic frontend can also be difficult, as even minor changes may necessitate extensive regression testing and redeployment of the entire program, which slows down the release process.</p>
<p>Moreover, scaling teams becomes increasingly complex. With a shared codebase, teams may have to coordinate closely, limiting their liberty. As more features are introduced, the frontend may grow bloated, affecting performance and user experience. Large bundles of JavaScript and CSS might slow initial load times, resulting in a poor user experience for those with poorer network connections.</p>
<p>That’s where micro frontends come into play.</p>
<h2 id="heading-what-is-a-micro-frontend">What is a Micro Frontend?</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753345832026/24fe5a3d-e2b2-4afa-b391-671af110ebf3.webp" alt /></p>
<p>A <strong>micro frontend</strong> is a method of breaking a frontend application into smaller, semi-independent mini-applications. Each micro frontend can be developed, deployed and updated independently, but they also work together as part of a bigger system. By applying Domain-Driven Design (DDD) principles, teams can concentrate on specific business domains, which enhances efficiency, minimizes conflicts, and ensures alignment with business requirements.</p>
<h2 id="heading-use-cases-for-micro-frontends">Use Cases for Micro Frontends</h2>
<ol>
<li><p><strong>Large and Complex Web Applications</strong>: For enterprise-level applications with many features, micro frontends allow for modularity, which helps streamline development.</p>
</li>
<li><p><strong>Modernization of Legacy Applications</strong>: When updating a legacy application, you can incrementally refactor it into micro frontends, allowing parts of the system to evolve without needing a complete overhaul.</p>
</li>
<li><p><strong>Multi-team Development</strong>: In large organizations, multiple teams can work simultaneously on different features or parts of an application. Micro frontends facilitate this by providing clear ownership of individual modules.</p>
</li>
</ol>
<h2 id="heading-approaches-to-implement-micro-frontends">Approaches to Implement Micro Frontends</h2>
<p>There are several common methods for implementing micro frontends, each with its strengths and trade-offs.</p>
<h3 id="heading-1-module-federation">1. <strong>Module Federation</strong></h3>
<p>Module Federation is one of the most popular ways to implement micro frontends. It allows different applications to dynamically load modules from one another at runtime. This method ensures that teams can work with different versions of a shared library or dependency without conflict.</p>
<h4 id="heading-example-module-federation-integration">Example: Module Federation Integration</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753345853183/c72dcf9b-8fb8-419d-90e3-d24861dad32f.png" alt /></p>
<p>To illustrate how micro frontends can be implemented using Module Federation, let's look at an example involving a remote and a host repository.</p>
<h4 id="heading-remote-repo-configuration-react">Remote Repo Configuration (React)</h4>
<p>In the remote repository, we have a simple counter page component and the Vite configuration to expose this component using Module Federation.</p>
<p><strong>CounterPage Component:</strong></p>
<pre><code class="lang-tsx">// src/pages/CounterPage.tsx
import { useState } from "react";

const CounterPage = () =&gt; {
    const [count, setCount] = useState(0);

    return (
        &lt;div className="counter_container"&gt;
            &lt;h1&gt;Remote Counter Page using Module Federation&lt;/h1&gt;

            &lt;div className="btn_card"&gt;
                &lt;button onClick={() =&gt; setCount(count + 1)}&gt;
                    count is {count}
                &lt;/button&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    );
};

export default CounterPage;
</code></pre>
<p><strong>Vite Configuration:</strong></p>
<pre><code class="lang-ts"><span class="hljs-comment">// vite.config.ts</span>
<span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">"vite"</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">"@vitejs/plugin-react"</span>;
<span class="hljs-keyword">import</span> federation <span class="hljs-keyword">from</span> <span class="hljs-string">"@originjs/vite-plugin-federation"</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">"fs"</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">"path"</span>;

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-comment">/**
 * Dynamically reads all .tsx files in the 'src/pages' directory and creates a mapping for module federation.
 * Files named 'index.tsx' are excluded from this mapping.
 */</span>
<span class="hljs-keyword">const</span> pagesDir = path.resolve(__dirname, <span class="hljs-string">"src/pages"</span>);
<span class="hljs-keyword">const</span> pages = fs
    .readdirSync(pagesDir)
    .reduce(<span class="hljs-function">(<span class="hljs-params">acc: Record&lt;<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>&gt;, file</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> ext = path.extname(file);
        <span class="hljs-keyword">const</span> name = path.basename(file, ext);
        <span class="hljs-keyword">const</span> componentPath = <span class="hljs-string">`pages/<span class="hljs-subst">${name}</span>`</span>;
        <span class="hljs-keyword">if</span> (name !== <span class="hljs-string">"index"</span> &amp;&amp; ext === <span class="hljs-string">".tsx"</span>) {
            acc[<span class="hljs-string">`./<span class="hljs-subst">${componentPath}</span>`</span>] = <span class="hljs-string">`./src/<span class="hljs-subst">${componentPath}</span>`</span>;
        }

        <span class="hljs-keyword">return</span> acc;
    }, {});

<span class="hljs-comment">/**
 * Vite configuration for a module federation build.
 * This configuration sets up a React application as a remote module.
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    plugins: [
        <span class="hljs-comment">// Plugin for React support in Vite.</span>
        react(),
        <span class="hljs-comment">// Plugin for Module Federation setup.</span>
        federation({
            <span class="hljs-comment">// Name of the remote module.</span>
            name: <span class="hljs-string">"RemoteEntryReactMF"</span>,
            <span class="hljs-comment">// Filename for the generated manifest file.</span>
            filename: <span class="hljs-string">"remoteEntryReactMF.js"</span>,
            <span class="hljs-comment">// Modules exposed by this remote.</span>
            exposes: {
                ...pages,
            },
            <span class="hljs-comment">// Shared dependencies.</span>
            shared: [<span class="hljs-string">"react"</span>],
        }),
    ],
    server: {
        <span class="hljs-comment">// Port for development server.</span>
        port: <span class="hljs-number">3001</span>,
    },
    preview: {
        <span class="hljs-comment">// Port for preview server.</span>
        port: <span class="hljs-number">3001</span>,
    },
    resolve: {
        alias: {
            <span class="hljs-comment">// Path alias for imports.</span>
            <span class="hljs-string">"@"</span>: <span class="hljs-string">"/src"</span>,
        },
    },
    build: {
        <span class="hljs-comment">// Target build format.</span>
        target: <span class="hljs-string">"esnext"</span>,
    },
});
</code></pre>
<p>You can find the remote repository <a target="_blank" href="https://github.com/OmGameHub/Micro_Frontend/tree/main/module_federation_remote_app">here</a>.</p>
<h4 id="heading-host-repo-configuration-react">Host Repo Configuration (React)</h4>
<p>In the host repository, we configure Vite to consume the remote component and use it within the host application.</p>
<p><strong>Vite Configuration:</strong></p>
<pre><code class="lang-ts"><span class="hljs-comment">// vite.config.ts</span>
<span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">"vite"</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">"@vitejs/plugin-react"</span>;
<span class="hljs-keyword">import</span> federation <span class="hljs-keyword">from</span> <span class="hljs-string">"@originjs/vite-plugin-federation"</span>;

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    plugins: [
        react(),
        federation({
            name: <span class="hljs-string">"HostApp"</span>,
            remotes: {
                RemoteEntryReactMF:
                    <span class="hljs-string">"http://localhost:3001/assets/remoteEntryReactMF.js"</span>, <span class="hljs-comment">// URL of the remote entry file</span>
            },
            shared: [<span class="hljs-string">"react"</span>], <span class="hljs-comment">// Shared dependencies</span>
        }),
    ],
    server: {
        port: <span class="hljs-number">3000</span>, <span class="hljs-comment">// Port for the host application</span>
    },
    preview: {
        port: <span class="hljs-number">3000</span>,
    },
    resolve: {
        alias: {
            <span class="hljs-string">"@"</span>: <span class="hljs-string">"/src"</span>, <span class="hljs-comment">// Alias for the source directory</span>
        },
    },
    build: {
        target: <span class="hljs-string">"esnext"</span>, <span class="hljs-comment">// Build target</span>
    },
});
</code></pre>
<p><strong>Using the Remote Component:</strong></p>
<pre><code class="lang-tsx">import { lazy, Suspense } from "react";

// Lazy load the remote component
const CounterPage = lazy(() =&gt; import("RemoteEntryReactMF/pages/CounterPage"));

const Counter = () =&gt; {
    return (
        &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;
            &lt;CounterPage /&gt; {/* Render the remote component */}
        &lt;/Suspense&gt;
    );
};

export default Counter;
</code></pre>
<p>You can find the host repository <a target="_blank" href="https://github.com/OmGameHub/Micro_Frontend/tree/main/host_app">here</a>.</p>
<p>This example demonstrates how to set up a remote and host repository using Module Federation, enabling independent development and deployment of micro frontends.</p>
<h3 id="heading-2-web-components">2. <strong>Web Components</strong></h3>
<p><strong>Web Components</strong> allow you to encapsulate and separate different aspects of the UI. Because they are part of the native browser API, they work well across various frameworks and libraries, making them a flexible choice for building micro frontends.</p>
<h4 id="heading-example-web-components-integration">Example: Web Components Integration</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753345902721/ede5ae84-70b4-459e-8a99-9cc266aad9ba.png" alt /></p>
<p>In this example, we demonstrate how to use Web Components to integrate a remote application into a host application. This approach leverages the native browser API to encapsulate and separate different aspects of the UI, making it a flexible choice for building micro frontends.</p>
<h4 id="heading-remote-app-configuration-react">Remote App Configuration (React)</h4>
<p>The remote application provides a simple page that generates a random number when a button is clicked. Here is the configuration for the remote app:</p>
<p><strong>App Component:</strong></p>
<pre><code class="lang-tsx">// src/App.tsx
import { useState } from "react";
import "./App.css";

function App() {
    const [number, setNumber] = useState(0);

    const getRandomNumber = () =&gt; {
        return Math.ceil(Math.random() * 100) + 1;
    };

    return (
        &lt;&gt;
            &lt;h1&gt;Remote Counter Page using Web Component&lt;/h1&gt;

            &lt;div className="card"&gt;
                &lt;button onClick={() =&gt; setNumber(getRandomNumber())}&gt;
                    Random number is {number}
                &lt;/button&gt;
            &lt;/div&gt;
        &lt;/&gt;
    );
}

export default App;
</code></pre>
<p><strong>Web Component Definition:</strong></p>
<pre><code class="lang-tsx">// src/RandomNumberPage.tsx
import ReactDOM from "react-dom/client";
import AppPage from "./App";

// Import CSS styles for the project and the App component.
// The '?inline' query parameter enables CSS Modules with inline styles.
import ProjectStyle from "./index.css?inline";
import AppStyle from "./App.css?inline";

// Define a custom HTML element named 'RandomNumberPage'.
class RandomNumberPage extends HTMLElement {
    // Lifecycle method called when the element is connected to the DOM.
    connectedCallback() {
        // Create a div element to serve as the mount point for the React application.
        const mountPoint = document.createElement("div");
        mountPoint.id = "root";

        // Create a shadow DOM for the custom element with 'open' mode.
        const shadowRoot = this.attachShadow({ mode: "open" });

        // Create a style element and set its content to include project and app styles.
        const style = document.createElement("style");
        style.textContent = `
            ${ProjectStyle}
            ${AppStyle}
        `;

        // Append the style element and the mount point to the shadow DOM.
        shadowRoot.appendChild(style);
        shadowRoot.appendChild(mountPoint);

        // Create a React root using the mount point.
        const root = ReactDOM.createRoot(mountPoint);
        // Render the AppPage component into the root.
        root.render(&lt;AppPage /&gt;);
    }
}

// Define the 'random-number-page' custom element using the RandomNumberPage class.
customElements.define("random-number-page", RandomNumberPage);
</code></pre>
<p><strong>Vite Configuration:</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">"vite"</span>;
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">"@vitejs/plugin-react"</span>;

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
    plugins: [react()],
    server: {
        port: <span class="hljs-number">5500</span>,
    },
    preview: {
        port: <span class="hljs-number">5500</span>,
    },
    build: {
        lib: {
            entry: <span class="hljs-string">"./src/RandomNumberPage"</span>,
            name: <span class="hljs-string">"RandomNumberPage"</span>,
            fileName: <span class="hljs-function">(<span class="hljs-params">format</span>) =&gt;</span> <span class="hljs-string">`RandomNumberPage.<span class="hljs-subst">${format}</span>.js`</span>,
        },
    },
    define: {
        <span class="hljs-string">"process.env"</span>: {
            NODE_ENV: <span class="hljs-string">"production"</span>,
        },
    },
});
</code></pre>
<p>You can find the remote repository <a target="_blank" href="https://github.com/OmGameHub/Micro_Frontend/tree/main/random_number_remote_app">here</a>.</p>
<h4 id="heading-host-app-configuration-react">Host App Configuration (React)</h4>
<p>The host application uses the web component to embed the remote application. Here is the configuration for the host app:</p>
<p><strong>RandomNumber Component:</strong></p>
<pre><code class="lang-tsx">// src/pages/RandomNumber.tsx
import { useEffect } from "react";

const RandomNumber = () =&gt; {
    useEffect(() =&gt; {
        // Dynamically load the web component script
        const script = document.createElement("script");
        script.src = "http://localhost:5500/RandomNumberPage.umd.js";
        script.type = "module"; // Ensure it's loaded as an ES module
        script.onload = () =&gt; {
            console.log("Web component loaded!");
        };
        document.body.appendChild(script);

        return () =&gt; {
            document.body.removeChild(script); // Clean up script when component unmounts
        };
    }, []);

    return (
        &lt;div&gt;
            &lt;random-number-page /&gt;
        &lt;/div&gt;
    );
};

export default RandomNumber;
</code></pre>
<p>You can find the host repository <a target="_blank" href="https://github.com/OmGameHub/Micro_Frontend/tree/main/host_app">here</a>.</p>
<p>This example shows how to use Web Components to integrate a remote application into a host application, providing a flexible way to embed micro frontends.</p>
<h3 id="heading-3-iframes">3. <strong>IFrames</strong></h3>
<p>IFrames are the simplest method for embedding micro frontends. While easy to implement, they come with challenges like cross-origin communication and limited ability to share global state.</p>
<h4 id="heading-example-iframe-integration">Example: IFrame Integration</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753345938984/4e4e23e5-7b59-4c66-b511-9245941761f6.png" alt /></p>
<p>In this example, we demonstrate how to use IFrames to integrate a remote application into a host application. This approach is straightforward but comes with some limitations, such as cross-origin communication and limited ability to share global state.</p>
<h4 id="heading-remote-app-configuration-nextjs">Remote App Configuration (Next.js)</h4>
<p>The remote application provides a simple page that changes its background color when a button is clicked. Here is the configuration for the remote app:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// app/page.tsx</span>
<span class="hljs-string">"use client"</span>;
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Home = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [bgColor, setBgColor] = useState(<span class="hljs-string">"#242424"</span>);

    <span class="hljs-comment">// Function to generate a random hex color</span>
    <span class="hljs-keyword">const</span> getRandomHexColor = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"#"</span> + <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">16777215</span>).toString(<span class="hljs-number">16</span>);
    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>
            <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center justify-center h-screen"</span>
            <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">backgroundColor:</span> <span class="hljs-attr">bgColor</span> }} // <span class="hljs-attr">Set</span> <span class="hljs-attr">background</span> <span class="hljs-attr">color</span>
        &gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-center"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"p-4 bg-gray-800/30 mb-20 rounded-lg"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-4xl font-bold text-white mb-1"</span>&gt;</span>
                        Remote Random Color Page using IFrame (Next.js)
                    <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

                    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-xl font-bold"</span>&gt;</span>
                        Color code:{" "}
                        <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"font-normal"</span>&gt;</span>{bgColor}<span class="hljs-tag">&lt;/<span class="hljs-name">span</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-tag">&lt;<span class="hljs-name">button</span>
                    <span class="hljs-attr">className</span>=<span class="hljs-string">"px-4 py-2 text-white bg-blue-500 rounded-md"</span>
                    <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setBgColor(getRandomHexColor())} // Change background color on click
                &gt;
                    Change Background Color
                <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-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p>You can find the remote repository <a target="_blank" href="https://github.com/OmGameHub/Micro_Frontend/tree/main/random_color_remote_app">here</a>.</p>
<h4 id="heading-host-app-configuration-react-1">Host App Configuration (React)</h4>
<p>The host application uses an IFrame to embed the remote application. Here is the configuration for the host app:</p>
<pre><code class="lang-tsx">// src/pages/RandomColor.tsx
const RandomColor = () =&gt; {
    return (
        &lt;div className="flex items-center justify-center h-full"&gt;
            &lt;iframe
                className="h-full w-full"
                src="http://localhost:8080/" // URL of the remote application
            /&gt;
        &lt;/div&gt;
    );
};

export default RandomColor;
</code></pre>
<p>You can find the host repository <a target="_blank" href="https://github.com/OmGameHub/Micro_Frontend/tree/main/host_app">here</a>.</p>
<p>This example shows how to use IFrames to integrate a remote application into a host application, providing a simple way to embed micro frontends.</p>
<h3 id="heading-advantages-of-micro-frontends">Advantages of Micro Frontends</h3>
<ul>
<li><p><strong>Scalability</strong>: Micro frontends allow applications to grow by simply adding new independent modules as needed. This makes it easier to scale large applications.</p>
</li>
<li><p><strong>Independent Development</strong>: Teams can build and deploy their modules independently, which speeds up the development process and reduces bottlenecks.</p>
</li>
<li><p><strong>Technology Flexibility</strong>: Different teams can use different technology stacks. For example, one micro frontend might use React while another could be built with Angular or Vue, depending on the team's preference.</p>
</li>
<li><p><strong>Maintainability</strong>: Smaller codebases are generally easier to maintain, debug, and test, leading to improved long-term productivity.</p>
</li>
<li><p><strong>Stability</strong>: If one micro frontend fails, the rest of the application can still function. This isolation improves overall application resilience.</p>
</li>
</ul>
<h3 id="heading-disadvantages-of-micro-frontends">Disadvantages of Micro Frontends</h3>
<ul>
<li><p><strong>Increased Complexity</strong>: Managing multiple micro frontends introduces complexity. It requires careful planning, data sharing and maintaining a consistent user experience across components. This complexity can provide difficulties in debugging and code management.</p>
</li>
<li><p><strong>Performance Overhead</strong>: Micro frontends can introduce performance bottlenecks due to increased communication between different parts of the app. Optimizing network requests and lazy loading modules are essential practices to mitigate this.</p>
</li>
<li><p><strong>Coordination Overhead</strong>: Good communication and coordination between teams are necessary to avoid integration issues, version conflicts, and feature inconsistencies.</p>
</li>
<li><p><strong>Testing Overhead</strong>: Testing micro frontends in isolation and together requires more effort. Unit testing, integration testing, and end-to-end testing must account for the interactions between different micro frontends.</p>
</li>
<li><p><strong>Maintenance and Security Overhead</strong>: Maintaining multiple independently deployed micro frontends requires careful dependency management, consistent security patching, and version control, which can be resource-intensive and complex.</p>
</li>
<li><p><strong>Higher Costs</strong>: Implementing micro frontends may increase costs due to the additional infrastructure, time, and resources required to manage and deploy numerous independent apps, as well as the increased coordination and maintenance activities.</p>
</li>
</ul>
<h3 id="heading-best-practices-for-implementing-micro-frontends">Best Practices for Implementing Micro Frontends</h3>
<ul>
<li><p><strong>Define Clear Boundaries</strong>: Create clear boundaries for each micro frontend based on business domains or user workflows. This allows teams to work independently and makes it easier to scale and maintain the project over time.</p>
</li>
<li><p><strong>Establish a Common Design System</strong>: Use a common design system to ensure visual and functional consistency across micro frontends. This helps maintain a seamless user experience and reduces the need for custom styling, minimizing redundancy across components.</p>
</li>
<li><p><strong>Optimize for Performance</strong>: Minimize network requests/queries, avoid duplicate dependencies, and use caching and lazy loading strategies. These techniques minimize load times and ensure each micro frontend performs optimally when integrated.</p>
</li>
<li><p><strong>Standardize Communication and Data Sharing</strong>: Define the protocols for how micro frontends will communicate with one another whether through a shared state, event bus, or other techniques. Clear data-sharing conventions help reduce dependency and avoid complications caused by inconsistent data.</p>
</li>
<li><p><strong>Decouple Dependencies</strong>: Minimize mutual dependencies between micro frontends. Independent dependency management enables each micro frontend to run and be updated independently, making maintenance and deployments more seamless.</p>
</li>
<li><p><strong>Use Independent Deployment Pipelines</strong>: Create deployment pipelines that will allow each micro frontend to be build, tested, and deployed individually. This reduces integration risks and allows for rapid, discrete upgrades without affecting the entire system.</p>
</li>
<li><p><strong>Invest in Automated Testing</strong>: Implement robust testing strategies that cover both isolated unit tests and integrated end-to-end tests. Automated testing ensures that each micro frontend functions correctly on its own and with others, helping to catch integration issues early.</p>
</li>
<li><p><strong>Centralized Authentication and Security</strong>: Implement a centralized authentication and authorization system to handle user access across micro frontends. This approach simplifies security management and ensures consistent enforcement of access policies.</p>
</li>
<li><p><strong>Monitor and Log Independently</strong>: Set up separate monitoring and logging for each micro frontend to quickly find out and rectify issues. This allows for effective troubleshooting and specific health management of each micro frontend.</p>
</li>
<li><p><strong>Plan for Version Control and Dependency Management</strong>: Use version control policies that allow micro frontends to evolve independently without causing version conflicts. Dependency management tools and strategies can help maintain stable versions and prevent incompatible updates.</p>
</li>
<li><p><strong>Establish Strong Cross-Team Collaboration</strong>: Encourage open communication and coordination among teams handling different micro frontends. Shared documentation, regular syncs and agreement on goals and processes can all contribute to smooth integration and a cohesive end product.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Micro frontends offer a modern, scalable solution for large and complex web applications, enabling teams to work independently while maintaining a unified user experience. However, implementing micro frontends comes with its own set of challenges, including increased complexity, coordination, and testing efforts. By using approaches like Module Federation, Web Components, and IFrames, you can break down a monolithic frontend and embrace the flexibility and modularity of micro frontends.</p>
<p>If you found this helpful, please share it with your fellow developers.</p>
<p>Thanks for reading! 🙌</p>
<p>Happy learning! 😁</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to SQL for Beginners]]></title><description><![CDATA[What is SQL?
SQL stands for Structured Query Language. It is used to interact with relational database systems. It performs CRUD operations: Create, Read, Update, and Delete in the database.
Why is SQL so Popular?
SQL has been the dominant language f...]]></description><link>https://blog.omprakashpandey.com/introduction-to-sql-for-beginners</link><guid isPermaLink="true">https://blog.omprakashpandey.com/introduction-to-sql-for-beginners</guid><category><![CDATA[SQL]]></category><category><![CDATA[#SQLtutorial ]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Sat, 10 Aug 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735483346535/ef3a89b4-9675-457d-a872-8d719cb28469.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-sql">What is SQL?</h2>
<p>SQL stands for Structured Query Language. It is used to interact with relational database systems. It performs CRUD operations: Create, Read, Update, and Delete in the database.</p>
<h2 id="heading-why-is-sql-so-popular">Why is SQL so Popular?</h2>
<p>SQL has been the dominant language for managing relational databases for decades, and its popularity continues to thrive due to several key reasons:</p>
<h3 id="heading-1-standardization-and-compatibility">1. Standardization and Compatibility:</h3>
<ul>
<li><p><strong>SQL is a standard:</strong> This means that once you learn SQL, you can work with various database systems (MySQL, Oracle, PostgreSQL, etc.) with minimal adjustments.</p>
</li>
<li><p><strong>Wide adoption:</strong> Its widespread use ensures a vast community of users and resources for learning and support.</p>
</li>
</ul>
<h3 id="heading-2-efficiency-and-power">2. Efficiency and Power:</h3>
<ul>
<li><p><strong>Optimized for data manipulation:</strong> SQL is designed to handle large datasets with speed and efficiency.</p>
</li>
<li><p><strong>Complex queries:</strong> It can perform intricate data analysis and retrieval tasks.</p>
</li>
</ul>
<h3 id="heading-3-simplicity-and-readability">3. Simplicity and Readability:</h3>
<ul>
<li><p><strong>English-like syntax:</strong> SQL commands often resemble natural language, making it relatively easy to learn and understand.</p>
</li>
<li><p><strong>Clear structure:</strong> The language promotes well-organized and maintainable code.</p>
</li>
</ul>
<h3 id="heading-4-proven-track-record">4. Proven Track Record:</h3>
<ul>
<li><p><strong>Reliability:</strong> SQL has been used in critical applications for years, demonstrating its robustness.</p>
</li>
<li><p><strong>Maturity:</strong> Decades of development have led to a highly refined and stable language.</p>
</li>
</ul>
<h3 id="heading-5-strong-ecosystem">5. Strong Ecosystem:</h3>
<ul>
<li><p><strong>Tools and integrations:</strong> Numerous tools and software applications support SQL, enhancing its usability.</p>
</li>
<li><p><strong>Community support:</strong> A large, active community provides resources, tutorials, and assistance.</p>
</li>
</ul>
<h2 id="heading-type-of-sql-commands">Type of SQL Commands:</h2>
<p>SQL commands are divided into several categories based on their purpose. Here are the most commonly used SQL command types along with their syntax:</p>
<h3 id="heading-1-data-definition-language-ddl">1. <strong>Data Definition Language (DDL)</strong></h3>
<p>DDL commands are used to define the database schema. These commands mainly deal with the structure of the database (e.g., tables, indexes).</p>
<ul>
<li><p><strong>CREATE:</strong> Used to create a new table, database, index, etc.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> table_name (
      column1_name datatype,
      column2_name datatype,
      ...
  );
</code></pre>
</li>
<li><p><strong>ALTER:</strong> Used to modify an existing database object (e.g., table).</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">TABLE</span> table_name
  <span class="hljs-keyword">ADD</span> column_name datatype;
</code></pre>
</li>
<li><p><strong>DROP:</strong> Used to delete a table, database, index, etc.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">DROP</span> <span class="hljs-keyword">TABLE</span> table_name;
</code></pre>
</li>
<li><p><strong>TRUNCATE:</strong> Used to remove all records from a table, but not the table itself.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">TRUNCATE</span> <span class="hljs-keyword">TABLE</span> table_name;
</code></pre>
</li>
</ul>
<h3 id="heading-2-data-query-language-dql">2. <strong>Data Query Language (DQL)</strong></h3>
<p>DQL commands are used to query data from the database.</p>
<ul>
<li><p><strong>SELECT:</strong> Used to retrieve data from the database.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">SELECT</span> column1_name, column2_name, ...
  <span class="hljs-keyword">FROM</span> table_name
  <span class="hljs-keyword">WHERE</span> condition;
</code></pre>
<pre><code class="lang-SQL">  &lt;!<span class="hljs-comment">-- generated query order --&gt;</span>
  <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">column</span>(s)
  <span class="hljs-keyword">FROM</span> table_name
  <span class="hljs-keyword">WHERE</span> condition
  <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">column</span>(s)
  <span class="hljs-keyword">HAVING</span> condition
  <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> <span class="hljs-keyword">column</span>(s);
</code></pre>
</li>
</ul>
<h3 id="heading-3-data-manipulation-language-dml">3. <strong>Data Manipulation Language (DML)</strong></h3>
<p>DML commands are used to manipulate the data stored in the database.</p>
<ul>
<li><p><strong>INSERT:</strong> Used to insert data into a table.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> table_name (column1_name, column2_name, ...)
  <span class="hljs-keyword">VALUES</span> (value1, value2, ...);
</code></pre>
</li>
<li><p><strong>UPDATE:</strong> Used to modify existing data within a table.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">UPDATE</span> table_name
  <span class="hljs-keyword">SET</span> column1_name = value1, column2_name = value2, ...
  <span class="hljs-keyword">WHERE</span> condition;
</code></pre>
</li>
<li><p><strong>DELETE:</strong> Used to delete data from a table.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> table_name
  <span class="hljs-keyword">WHERE</span> condition;
</code></pre>
</li>
</ul>
<h3 id="heading-4-data-control-language-dcl">4. <strong>Data Control Language (DCL)</strong></h3>
<p>DCL commands are used to grant or revoke access privileges to the database.</p>
<ul>
<li><p><strong>GRANT:</strong> Used to give users access privileges to the database.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">GRANT</span> privilege_name <span class="hljs-keyword">ON</span> object_name <span class="hljs-keyword">TO</span> user_name;
</code></pre>
</li>
<li><p><strong>REVOKE:</strong> Used to take back privileges from a user.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">REVOKE</span> privilege_name <span class="hljs-keyword">ON</span> object_name <span class="hljs-keyword">FROM</span> user_name;
</code></pre>
</li>
</ul>
<h3 id="heading-5-transaction-control-language-tcl">5. <strong>Transaction Control Language (TCL)</strong></h3>
<p>TCL commands are used to manage transactions in the database.</p>
<ul>
<li><p><strong>COMMIT:</strong> Used to save the changes made by a transaction permanently.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">COMMIT</span>;
</code></pre>
</li>
<li><p><strong>ROLLBACK:</strong> Used to undo the changes made by a transaction.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">ROLLBACK</span>;
</code></pre>
</li>
<li><p><strong>SAVEPOINT:</strong> Used to set a point within a transaction to which you can later roll back.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">SAVEPOINT</span> savepoint_name;
</code></pre>
</li>
<li><p><strong>SET TRANSACTION:</strong> Used to specify the characteristics of the current transaction.</p>
<pre><code class="lang-SQL">  <span class="hljs-keyword">SET</span> <span class="hljs-keyword">TRANSACTION</span> <span class="hljs-keyword">read</span> write;
</code></pre>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[React Native installation on MAC]]></title><description><![CDATA[React Native
React Native is an open-source framework for building mobile apps using JavaScript and React. It was developed by Facebook and is widely used for developing cross-platform mobile apps for iOS and Android.
Install Homebrew
Install Homebre...]]></description><link>https://blog.omprakashpandey.com/react-native-installation-on-mac</link><guid isPermaLink="true">https://blog.omprakashpandey.com/react-native-installation-on-mac</guid><category><![CDATA[React Native]]></category><category><![CDATA[react native app development]]></category><category><![CDATA[Android]]></category><category><![CDATA[iOS]]></category><category><![CDATA[react-native-installation]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Thu, 21 Sep 2023 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695399512829/5b59325a-64b8-47dc-aa77-7afe6a432587.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-react-native">React Native</h2>
<p><a target="_blank" href="https://github.com/facebook/react-native">React Native</a> is an open-source framework for building mobile apps using JavaScript and React. It was developed by Facebook and is widely used for developing cross-platform mobile apps for iOS and Android.</p>
<h2 id="heading-install-homebrew">Install Homebrew</h2>
<p>Install Homebrew by running the following command in your terminal:</p>
<pre><code class="lang-bash">/bin/bash -c <span class="hljs-string">"<span class="hljs-subst">$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)</span>"</span>
</code></pre>
<p>Run these commands in your terminal to add homebrew to your PATH:</p>
<pre><code class="lang-bash">(<span class="hljs-built_in">echo</span>; <span class="hljs-built_in">echo</span> <span class="hljs-string">'eval "$(/opt/homebrew/bin/brew shellenv)"'</span>) &gt;&gt; /Users/&lt;username&gt;/.zprofile
<span class="hljs-built_in">eval</span> <span class="hljs-string">"<span class="hljs-subst">$(/opt/homebrew/bin/brew shellenv)</span>"</span>
</code></pre>
<p>restart your terminal and check if brew is installed correctly</p>
<pre><code class="lang-bash">brew --version
</code></pre>
<h2 id="heading-install-nvm-andamp-node-js-lts">Install Nvm &amp; Node Js LTS</h2>
<p><a target="_blank" href="https://github.com/nvm-sh/nvm">Nvm</a> is a version manager for node js. It allows you to install multiple versions of node js and switch between them easily.</p>
<p>Run the following command in your terminal to install nvm:</p>
<pre><code class="lang-bash">brew install nvm
</code></pre>
<p>now run the following command to install node js lts version</p>
<pre><code class="lang-bash">nvm install --lts
</code></pre>
<p>check if node is installed correctly</p>
<pre><code class="lang-bash">node --version
</code></pre>
<h2 id="heading-install-watchman">Install Watchman</h2>
<p><a target="_blank" href="https://facebook.github.io/watchman/">Watchman</a> is a tool by Facebook for watching changes in the filesystem. It is highly recommended you install it for better performance.</p>
<p>Install Watchman by running the following command in your terminal:</p>
<pre><code class="lang-bash">brew install watchman
</code></pre>
<h2 id="heading-ios-development-environment"><em>IOS Development Environment</em></h2>
<h2 id="heading-install-rbenv-andamp-ruby">Install rbenv &amp; ruby</h2>
<p><a target="_blank" href="https://github.com/rbenv/rbenv">rbenv</a> is a version manager tool for the ruby programming language on Unix-like systems. It is useful for switching between multiple Ruby versions on the same machine and for ensuring that each project you are working on always runs on the correct Ruby version.</p>
<p>Install rbenv by running the following command in your terminal:</p>
<pre><code class="lang-bash">brew install rbenv ruby-build
</code></pre>
<p>now check the latest stable ruby versions</p>
<pre><code class="lang-bash">rbenv install -l
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695363536174/fd93ec32-8d9c-458e-9bf0-29a185f71dfe.png" alt="latest stable ruby versions" class="image--center mx-auto" /></p>
<p>Install the stable ruby version from the list in my case it is 3.2.2</p>
<pre><code class="lang-bash"><span class="hljs-comment"># rbenv install &lt;version&gt;</span>
rbenv install 3.2.2
</code></pre>
<p>now set ruby version as global so that it can be used by all projects</p>
<pre><code class="lang-bash"><span class="hljs-comment"># rbenv global &lt;version&gt;</span>
rbenv global 3.2.2
</code></pre>
<p>now add rbenv to your PATH so that it can be used by your shell</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'export PATH="$HOME/.rbenv/bin:$PATH"'</span> &gt;&gt; ~/.zshrc
<span class="hljs-built_in">echo</span> <span class="hljs-string">'eval "$(rbenv init -)"'</span> &gt;&gt; ~/.zshrc
</code></pre>
<p>check if ruby latest stable version is installed correctly</p>
<pre><code class="lang-bash">ruby --version
</code></pre>
<h2 id="heading-xcode">Xcode</h2>
<p>The easiest way to install <a target="_blank" href="https://itunes.apple.com/us/app/xcode/id497799835?mt=12">Xcode</a> is via the Mac App Store. Installing Xcode will also install the iOS Simulator and all the necessary tools to build your iOS app.</p>
<h2 id="heading-android-development-environment"><em>Android Development Environment</em></h2>
<h2 id="heading-java-development-kit-jdk">Java Development Kit (JDK)</h2>
<p>Install Open JDK 11 by running the following command in your terminal</p>
<pre><code class="lang-bash">brew install openjdk@11
</code></pre>
<p>For the system Java wrappers to find this JDK, symlink it with</p>
<pre><code class="lang-bash">sudo ln -sfn /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk
</code></pre>
<p>If you need to have openjdk@11 first in your PATH, run</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'export PATH="/opt/homebrew/opt/openjdk@11/bin:$PATH"'</span> &gt;&gt; ~/.zshrc
</code></pre>
<p>For compilers to find openjdk@11 you may need to set</p>
<pre><code class="lang-bash"><span class="hljs-built_in">export</span> CPPFLAGS=<span class="hljs-string">"-I/opt/homebrew/opt/openjdk@11/include"</span>
</code></pre>
<h2 id="heading-setup-android-environment">Setup Android Environment</h2>
<h3 id="heading-step-1-android-studio">Step 1: Android Studio</h3>
<p>Run the following command in your terminal to install <a target="_blank" href="https://developer.android.com/studio">Android Studio</a></p>
<pre><code class="lang-bash">brew install --cask android-studio
</code></pre>
<h3 id="heading-step-2-android-sdk">Step 2: Android SDK</h3>
<p>Open Android Studio, click on "More Actions" button and select "SDK Manager".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695366014122/ed3e79ec-3604-4ddd-886d-2b40ee080fb0.png" alt="Android Studio" class="image--center mx-auto" /></p>
<p>In the SDK Platforms tab, check the box next to "Show Package Details" in the bottom right corner. Look for and expand the Android 13 (Tiramisu) entry, then make sure the following items are checked:</p>
<ul>
<li><p>Android SDK Platform 33</p>
</li>
<li><p>Intel x86 Atom_64 System Image or Google APIs Intel x86 Atom System Image or (for Apple M1 Silicon) Google APIs ARM 64 v8a System Image</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695366165422/e76adc6b-ab82-4206-a7e8-3d518e7e1963.png" alt="SDK Platforms Tab" class="image--center mx-auto" /></p>
<p>Next select the SDK Tools tab and check the following boxes:</p>
<ul>
<li><p>Android SDK Build-Tools</p>
</li>
<li><p>Android SDK Command-line Tools (latest)</p>
</li>
<li><p>Android Emulator</p>
</li>
<li><p>Android SDK Platform-Tools</p>
</li>
<li><p>Google Play Services</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695366630678/bd421761-001b-4d27-b017-9b26a9ac8435.png" alt="SDK Tools Tab" class="image--center mx-auto" /></p>
<p>Finally, click "Apply" to download and install the Android SDK and related build tools.</p>
<h3 id="heading-step-3-configure-the-androidhome-environment-variable">Step 3: Configure the ANDROID_HOME environment variable</h3>
<p>React Native tools require some environment variables to be set up in order to build apps with native code.</p>
<p>Add the following lines to your ~/.zprofile or ~/.zshrc (if you are using bash, then ~/.bash_profile or ~/.bashrc) config file:</p>
<p>run the following command in your terminal to add Android SDK path to your PATH:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'export ANDROID_HOME=$HOME/Library/Android/sdk'</span> &gt;&gt; ~/.zshrc
<span class="hljs-built_in">echo</span> <span class="hljs-string">'export PATH=$PATH:$ANDROID_HOME/emulator'</span> &gt;&gt; ~/.zshrc
<span class="hljs-built_in">echo</span> <span class="hljs-string">'export PATH=$PATH:$ANDROID_HOME/platform-tools'</span> &gt;&gt; ~/.zshrc
</code></pre>
<blockquote>
<p>Please make sure you use the correct Android SDK path. You can find the actual location of the SDK in the Android Studio "More Actions" button -&gt; SDK Manager -&gt; Android SDK -&gt; Android SDK Location.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695370280116/e006b867-f041-430a-a71b-6cea23dd555c.jpeg" alt="Android SDK Location" class="image--center mx-auto" /></p>
<p>check if Android SDK path is set correctly</p>
<pre><code class="lang-bash"><span class="hljs-built_in">echo</span> <span class="hljs-variable">$ANDROID_HOME</span>
</code></pre>
<h2 id="heading-create-a-new-react-native-app">Create a new react native app</h2>
<blockquote>
<p>If you previously installed a global react-native-cli package, please remove it as it may cause unexpected issues.</p>
<pre><code class="lang-bash">npm uninstall -g react-native-c
</code></pre>
</blockquote>
<p>Run the following command in your terminal to create a new React native project</p>
<pre><code class="lang-bash">npx react-native init MyApp
</code></pre>
<h2 id="heading-run-react-native-app">Run react native app</h2>
<p>Now go to your project directory and run the following commands in your terminal</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> MyApp
</code></pre>
<p>run the following command in your terminal to run your react native app on ios simulator or device</p>
<pre><code class="lang-bash">npm run ios
</code></pre>
<p>run the following command in your terminal to run your react native app on android simulator or device</p>
<pre><code class="lang-bash">npm run android
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695370575231/dcd594d3-3404-4a8a-a56a-490c8b45c8f6.png" alt="run React Native app on android &amp; ios" class="image--center mx-auto" /></p>
<p>Finally, It's done. Now you can start developing your react native app.</p>
<p>If I have made a mistake somewhere or missed any important point, do let me know in the comments.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Getting started into DevOps]]></title><description><![CDATA[What is DevOps?
It's a cultural practice in an organization by the development (Dev) and operations (Ops) teams to use each other's tools, to smooth out the software delivery process.
The Problem with Traditional Software Development
Whenever an appl...]]></description><link>https://blog.omprakashpandey.com/getting-started-into-devops</link><guid isPermaLink="true">https://blog.omprakashpandey.com/getting-started-into-devops</guid><category><![CDATA[Devops]]></category><category><![CDATA[technology]]></category><category><![CDATA[#Devopscommunity]]></category><category><![CDATA[Cloud Computing]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Om Prakash Pandey]]></dc:creator><pubDate>Tue, 13 Jun 2023 21:22:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735484778034/89faa99c-6397-4524-9801-30a49356eb13.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686688139607/3303527c-7927-4bf1-afec-92981e71d130.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-what-is-devops">What is DevOps?</h2>
<p>It's a cultural practice in an organization by the development (<strong>Dev</strong>) and operations (<strong>Ops</strong>) teams to use each other's tools, to smooth out the software delivery process.</p>
<h2 id="heading-the-problem-with-traditional-software-development">The Problem with Traditional Software Development</h2>
<p>Whenever an application is being developed, there are multiple phases of its development. Now when the application is small in size, like when you want to build a website, mobile app etc.. Then everything is fine because you may have a small team of 1 or 3 people who can handle the entire application's features planning, building, and deployment to the server or cloud so that users can use that feature.</p>
<p>But things change when a mid-size company develop a big-scale application for the entire world, like Amazon, Netflix, Zomato, etc. Now when these applications are developed we have different types of teams that manage different parts or architectures of the application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686687695608/94886fbd-0611-4ac4-bb02-9438c58b34e8.png" alt class="image--center mx-auto" /></p>
<p>We can divide teams into <strong>Developers (Dev)</strong> and <strong>Operations (Ops)</strong> teams. The Dev team wants to deliver features quickly and deploy them quickly. The Ops team wants the system to be stable and uptime is most important to them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686681689788/023df32a-d2cf-4ca9-962f-9b955ff3735c.png" alt class="image--center mx-auto" /></p>
<p>The Dev team typically assumes that the Ops team is idle and that whenever they provide these new changes or features, they will immediately deploy to the server or cloud. However, this does not always occur. The Ops team are also busy managing and checking a variety of things like scalability, what kind of traffics is coming and security check of infrastructure etc. usually in big application development happen 1 or 2 times a month. Sometimes the development team is frustrated that everything has been done but the operations team has not yet deployed their feature to production.</p>
<h2 id="heading-solution">Solution</h2>
<p>The DevOps mindset provides a solution to this issue. In DevOps, the Dev and Ops teams discuss everything side by side like one team and sometimes switch roles and responsibilities to ensure that everyone on the Dev team is aware of what is happening in the operation and that the Ops team is aware of how things actually function on the development side as well.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686682822494/1ba41576-3c1a-430a-951a-4e4e9d93d5de.png" alt class="image--center mx-auto" /></p>
<p>This exact mindset that ensures that everyone is aware of everything that is occurring on both the development and operation sides is known as DevOps.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686504491442/c0ff6957-a531-43e7-af10-03f7dbbe5ac8.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-benefits-of-devops">Benefits of DevOps</h2>
<h3 id="heading-faster-delivery-of-software">Faster delivery of software</h3>
<p>Teams can use automated technologies to create, test, and deploy software through continuous delivery.</p>
<h3 id="heading-better-collaboration-between-teams">Better collaboration between teams</h3>
<p>The foundation of DevOps is a culture of collaboration between developers and operations teams, which helps reduce conflicts and improve communication.</p>
<h3 id="heading-rapid-development">Rapid development</h3>
<p>The team quickly enhances the product by releasing new updates and bug fixes by increasing the frequency of releases.</p>
<h3 id="heading-quality-and-reliability">Quality and reliability</h3>
<p>By using continuous integration and continuous delivery to test that each change is functional and safe. Monitoring and logging help the team keep informed of performance in real time.</p>
]]></content:encoded></item></channel></rss>