<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fariha kausar |  Web Developer &amp; Tech Blogger on Medium]]></title>
        <description><![CDATA[Stories by Fariha kausar |  Web Developer &amp; Tech Blogger on Medium]]></description>
        <link>https://medium.com/@farihakausar18?source=rss-2c82f59b43db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Fariha kausar |  Web Developer &amp;amp; Tech Blogger on Medium</title>
            <link>https://medium.com/@farihakausar18?source=rss-2c82f59b43db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:34:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@farihakausar18/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[REDIS — COMPLETE GUIDE]]></title>
            <link>https://medium.com/@farihakausar18/redis-complete-guide-8324c9f353e7?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/8324c9f353e7</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[redis-cluster]]></category>
            <category><![CDATA[redis-persistence]]></category>
            <category><![CDATA[redis-datatype]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 06:54:00 GMT</pubDate>
            <atom:updated>2026-01-30T06:54:00.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>REDIS — COMPLETE GUIDE</h3><h3>What is Redis? (Super Simple)</h3><p><strong>Redis = Remote Dictionary Server</strong></p><p>Think of Redis as:</p><ul><li>a <strong>very fast in-memory database</strong></li><li>that stores data as <strong>key → value</strong></li><li>used mainly for <strong>speed</strong>, not long-term storage</li></ul><p>Example:</p><pre>&quot;user:1&quot; → { name: &quot;Ali&quot;, age: 22 }</pre><p>Why Redis is famous:</p><ul><li><strong>EXTREMELY fast</strong> (microseconds)</li><li>Data lives in <strong>RAM</strong></li><li>Can persist data to disk</li><li>Supports advanced data types</li></ul><h3>When &amp; WHY do we use Redis?</h3><p>Redis is used when you need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*w9EZPITQ6cCceZAd1g37VQ.png" /></figure><p>💡 <strong>Redis is NOT a replacement for PostgreSQL/MySQL</strong><br>It <strong>supports</strong> them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*-eKl59iRopmFoor1_woSNA.png" /></figure><p><strong>Golden Rule</strong></p><blockquote><em>Database = source of truth<br>Redis = performance booster</em></blockquote><h3>Redis Basics (Keys &amp; Values)</h3><h3>Key rules</h3><ul><li>Keys are strings</li><li>Best practice: use namespaces</li></ul><pre>user:1<br>order:445<br>session:abc123</pre><h3>Basic Commands</h3><pre>SET name &quot;Fariha&quot;<br>GET name<br>DEL name<br>EXISTS name</pre><h3>Redis Data Types (VERY IMPORTANT)</h3><h3>STRING (Most common)</h3><p>One key = one value.</p><pre>SET user:name &quot;Ali&quot;<br>SET user:age 22<br>INCR user:age</pre><p>Used for:</p><ul><li>counters</li><li>flags</li><li>tokens</li></ul><h3>HASH (Like an object)</h3><ul><li>ONE key and MANY related fields</li></ul><h3>Think of it like:</h3><ul><li>JS object</li><li>Python dict</li><li>JSON object</li></ul><pre>HSET user:1 name &quot;Ali&quot; age 22 city &quot;Lahore&quot;<br>HGET user:1 name<br>HGETALL user:1</pre><p>Perfect for:</p><ul><li>users</li><li>profiles</li><li>configs</li></ul><h3>LIST (Ordered, allows duplicates)</h3><p>Order matters.</p><ul><li>Order is preserved</li><li>Can have duplicates</li><li>Add/remove from left or right</li></ul><pre>LPUSH tasks &quot;task1&quot;<br>RPUSH tasks &quot;task2&quot;<br>LRANGE tasks 0 -1</pre><p>Used for:</p><ul><li>queues</li><li>job workers</li></ul><h3>SET (Unique values, unordered)</h3><ul><li>No duplicates</li><li>Fast lookup</li><li>Order does NOT matter</li></ul><pre>SADD skills &quot;js&quot; &quot;redis&quot; &quot;node&quot;<br>SMEMBERS skills</pre><p>Used for:</p><ul><li>tags</li><li>permissions</li><li>unique IDs</li></ul><h3>SORTED SET ( Advanced)</h3><p>Each value has a score</p><pre>ZADD leaderboard 100 &quot;Ali&quot;<br>ZADD leaderboard 200 &quot;Sara&quot;<br>ZRANGE leaderboard 0 -1 WITHSCORES</pre><p>Used for:</p><ul><li>leaderboards</li><li>rankings</li><li>priority queues</li></ul><h3>HOW TO CHOOSE (Easy Decision Guide)</h3><p>Ask this question:</p><p>1️⃣ One value only? → <strong>STRING</strong><br>2️⃣ Many fields of one thing? → <strong>HASH</strong><br>3️⃣ Order matters? → <strong>LIST</strong><br>4️⃣ Unique items only? → <strong>SET</strong><br>5️⃣ Ranking / scores? → <strong>SORTED SET</strong></p><h3>TTL &amp; Expiration (Caching MAGIC)</h3><p>Redis keys can <strong>auto-expire</strong></p><pre>SET otp &quot;123456&quot; EX 60<br>TTL otp</pre><p>Used for:</p><ul><li>OTPs</li><li>sessions</li><li>cache invalidation</li></ul><h3>Redis as a Cache (Real Example)</h3><h3>❌ Without Redis</h3><pre>Client → API → Database (slow)</pre><h3>✅ With Redis</h3><pre>Client → API → Redis (fast)<br>             ↓ miss<br>           Database</pre><h3>Code Flow</h3><pre>const cached = await redis.get(&quot;user:1&quot;)<br>if (cached) return JSON.parse(cached)</pre><pre>const user = await db.getUser(1)<br>await redis.set(&quot;user:1&quot;, JSON.stringify(user), &quot;EX&quot;, 60)<br>return user</pre><h3>Redis Sessions (Login System)</h3><p>Instead of storing sessions in DB:</p><pre>SET session:abc123 userId=5 EX 3600</pre><p>✔ Fast<br>✔ Auto logout<br>✔ Scales well</p><h3>Redis Pub/Sub (Real-time)</h3><p>Redis can <strong>broadcast messages</strong></p><h3>Publisher</h3><pre>PUBLISH chat &quot;hello world&quot;</pre><h3>Subscriber</h3><pre>SUBSCRIBE chat</pre><p>Used for:</p><ul><li>chat apps</li><li>notifications</li><li>live updates</li></ul><p>⚠️ Messages are NOT stored (fire &amp; forget)</p><h3>Redis Queues (Background Jobs)</h3><h3>Producer</h3><pre>LPUSH jobs &quot;send_email&quot;</pre><h3>Worker</h3><pre>BRPOP jobs 0</pre><p>Used for:</p><ul><li>emails</li><li>image processing</li><li>async tasks</li></ul><h3>Redis Persistence (VERY IMPORTANT)</h3><p>Redis is in RAM, but can <strong>save to disk</strong>.</p><h3>1️⃣ RDB (Snapshots)</h3><ul><li>Periodic dump</li><li>Fast restore</li><li>Might lose recent data</li></ul><h3>2️⃣ AOF (Append Only File)</h3><ul><li>Logs every write</li><li>Slower</li><li>More durable</li></ul><p>👉 Production uses:</p><pre>AOF + RDB</pre><h3>Explained from zero</h3><h3>First: the scary truth</h3><p>RAM is <strong>temporary</strong>.</p><ul><li>Server crash ❌</li><li>Power cut ❌</li><li>Restart ❌</li></ul><p>Without persistence:</p><blockquote><strong><em>Redis forgets everything.</em></strong><em><br>Like a genius with amnesia.</em></blockquote><p>Persistence is how Redis <strong>remembers things after a restart</strong>.</p><h3>What “persistence” actually means</h3><p>Redis does two things at the same time:</p><ul><li>Uses <strong>RAM</strong> for speed</li><li>Optionally writes data to <strong>disk</strong> for memory</li></ul><p>Disk is slow but permanent.<br>RAM is fast but forgetful.</p><p>Persistence = <strong>copying memory → disk</strong></p><h3>The TWO ways Redis saves data (this is the core idea)</h3><p>Redis has <strong>two different “memory-saving styles”</strong>:</p><p>1️⃣ <strong>RDB</strong> — snapshot style<br>2️⃣ <strong>AOF</strong> — diary / log style</p><p>They feel very different.</p><h3>RDB — Snapshot persistence</h3><h3>Mental picture</h3><p>Redis occasionally takes a <strong>photo of its brain</strong>.</p><pre>Every X minutes → 📸 SNAPSHOT → dump.rdb</pre><p>That file lives on disk.</p><h3>What happens step-by-step</h3><ol><li>Redis is running</li><li>Data is changing in RAM</li><li>At some moment:</li></ol><ul><li>Redis freezes a copy</li><li>Writes it to dump.rdb</li></ul><p>4.Redis keeps working normally</p><p>If Redis crashes later:</p><ul><li>It loads the <strong>last snapshot</strong></li><li>Anything after that snapshot is gone</li></ul><h3>Example</h3><pre>12:00 → snapshot saved<br>12:01 → user logged in<br>12:02 → order created<br>12:03 → server crashes 💥</pre><p>After restart:</p><pre>Redis remembers data till 12:00 only</pre><p>The rest vanished into the void.</p><h3>Why RDB exists (its strength)</h3><ul><li>Very fast</li><li>Small file</li><li>Quick server startup</li><li>Great for backups</li></ul><h3>Why RDB is risky</h3><ul><li>Can lose <strong>recent data</strong></li><li>Not ideal for critical systems alone</li></ul><h3>AOF — Append Only File (Diary)</h3><h3>Mental picture</h3><p>Redis keeps a <strong>diary</strong> and writes <strong>every change</strong>.</p><pre>SET name Ali<br>INCR views<br>DEL session:123</pre><p>Each line is written to a file.</p><h3>What happens step-by-step</h3><ol><li>Redis receives a command</li><li>Executes it in RAM</li><li>Writes the command to AOF file</li></ol><p>If Redis crashes:</p><ul><li>Redis <strong>replays the diary</strong></li><li>Rebuilds memory exactly</li></ul><h3>Example</h3><pre>SET user:1 Ali<br>INCR balance<br>INCR balance</pre><p>On restart:<br>Redis replays these lines → memory restored perfectly.</p><h3>Why AOF is powerful</h3><ul><li>Minimal data loss</li><li>Much safer than RDB</li><li>Great for money, sessions, counters</li></ul><h3>Why AOF has a cost</h3><ul><li>File grows large</li><li>Restart is slower (replay)</li><li>Slightly slower writes</li></ul><h3>Important AOF detail (this matters)</h3><p>Redis does NOT always write instantly.</p><p>You can choose <strong>how often it writes</strong>:</p><ul><li>Every command (safest, slowest)</li><li>Every second (default)</li><li>Let OS decide (fastest, risky)</li></ul><p>This is the <strong>durability vs performance tradeoff</strong>.</p><h3>The REAL production setup (this clears confusion)</h3><p>Most real systems use:</p><blockquote><strong><em>RDB + AOF together</em></strong></blockquote><p>Why?</p><ul><li>RDB → fast recovery</li><li>AOF → minimal data loss</li><li>Best of both worlds</li></ul><p>Think of it as:</p><ul><li><strong>Photo album + diary</strong></li></ul><h3>What happens on restart?</h3><p>Order of trust:</p><ol><li>Redis loads <strong>AOF first</strong> (most accurate)</li><li>If no AOF, uses <strong>RDB</strong></li><li>If none → empty memory</li></ol><h3>When do we NOT care about persistence?</h3><p>Some data is meant to die.</p><p>Examples:</p><ul><li>cache</li><li>OTPs</li><li>temporary sessions</li></ul><p>For these:</p><blockquote><em>Losing data is fine<br>Redis just refills it again.</em></blockquote><h3>When persistence is CRITICAL</h3><p>Examples:</p><ul><li>rate limits</li><li>balances</li><li>queues</li><li>background jobs</li><li>login sessions</li></ul><p>For these:</p><blockquote><em>You </em><strong><em>must</em></strong><em> enable persistence</em></blockquote><h3>Final mental model (lock this in)</h3><p>Redis is:</p><ul><li>a <strong>fast brain</strong> (RAM)</li><li>with optional <strong>memory notebook</strong> (disk)</li></ul><p>RDB = <strong>photos</strong><br>AOF = <strong>diary</strong></p><p>You choose:</p><ul><li>speed</li><li>safety</li><li>or balance</li></ul><h3>Redis Replication — Scaling Reads</h3><h3>The problem</h3><p>One Redis server = one CPU + one RAM.</p><p>If:</p><ul><li>1M users</li><li>All hitting Redis</li></ul><p>The server chokes.</p><h3>The idea (simple)</h3><p>Instead of ONE Redis:</p><pre>MASTER<br>      (writes only)<br>        ↓<br>    ┌───────────┐<br>    │           │<br> REPLICA     REPLICA<br> (reads)      (reads)</pre><ul><li><strong>Master</strong> → accepts writes</li><li><strong>Replicas</strong> → copy data &amp; serve reads</li></ul><h3>How replication works (mentally)</h3><ol><li>Master receives a write</li><li>Master updates RAM</li><li>Master <strong>sends the change</strong> to replicas</li><li>Replicas update themselves</li></ol><p>Result:</p><ul><li>All replicas have the same data</li><li>Reads are spread out</li></ul><h3>Why replication is used</h3><p>✔ Scale read traffic<br>✔ Backup copy<br>✔ Faster reads<br>✔ Better availability</p><h3>Important limitation (VERY IMPORTANT)</h3><p>Replication is:</p><ul><li><strong>asynchronous</strong></li></ul><p>Meaning:</p><blockquote><em>Replica might be </em>slightly behind<em> master</em></blockquote><p>This is OK for:</p><ul><li>cache</li><li>sessions</li><li>feeds</li></ul><p>NOT OK for:</p><ul><li>banking transactions</li></ul><h3>Real example</h3><pre>Login:<br>  write → MASTER</pre><pre>Get profile:<br>  read → REPLICA</pre><h3>Redis Sentinel — Failover (Auto-Healing)</h3><p>Replication alone is NOT enough.</p><h3>The scary question</h3><blockquote><em>What if the MASTER dies? 😨</em></blockquote><ul><li>Writes stop</li><li>App crashes</li><li>Downtime</li></ul><h3>Sentinel to the rescue 🛡️</h3><p>Think of <strong>Sentinel as a guard system</strong>.</p><pre>Sentinel  Sentinel  Sentinel<br>    👀        👀        👀<br>        Redis Master<br>            ↓<br>         Replicas</pre><h3>What Sentinel does</h3><ol><li>Watches Redis nodes</li><li>Detects master failure</li><li>Promotes a replica → NEW MASTER</li><li>Updates everyone</li></ol><p><strong>Zero human intervention</strong></p><h3>Why multiple Sentinels?</h3><p>So they can <strong>vote</strong>.</p><blockquote><em>One sentinel panic ≠ failover<br>Majority agreement = real failure</em></blockquote><h3>What your app does</h3><p>Your app:</p><ul><li>Connects to <strong>Sentinel</strong></li><li>Sentinel tells:<br>👉 “Here’s the current master”</li></ul><p>When master changes:</p><ul><li>App reconnects automatically</li></ul><h3>Sentinel mental model</h3><ul><li>Replication = cloning</li><li>Sentinel = doctor + judge</li></ul><h3>Redis Cluster (Horizontal Scaling)</h3><p>Redis Cluster:</p><ul><li>Shards data across nodes</li><li>Handles TBs of data</li><li>Auto rebalancing</li></ul><p>Used by:</p><ul><li>Netflix</li><li>Twitter</li><li>Uber</li></ul><h3>Redis Transactions</h3><pre>MULTI<br>SET a 1<br>SET b 2<br>EXEC</pre><p>⚠️ Not fully ACID like SQL<br>No rollback on failure</p><h3>Redis Lua Scripts ( Advanced)</h3><h3>Redis Lua Scripts — Atomic Logic Inside Redis</h3><h3>The problem (race conditions)</h3><p>Example:</p><ul><li>Check balance</li><li>Deduct money</li><li>Update value</li></ul><p>If two users hit at once → 💥 inconsistency</p><h3>Normal approach</h3><pre>GET balance<br>IF balance &gt;= 100<br>SET balance = balance - 100</pre><p>Another request can sneak in between.</p><h3>Lua Script idea</h3><blockquote><em>“Send logic to Redis, run it as ONE unit”</em></blockquote><p>Redis runs:</p><ul><li>One script</li><li>No interruption</li><li>Fully atomic</li></ul><h3>Mental picture</h3><pre>Client → [ Lua Script ] → Redis<br>               ⚙️<br>        check + update</pre><p>Nothing can interrupt it.</p><h3>Why Lua scripts are powerful</h3><p>✔ Atomic operations<br>✔ Faster (less network)<br>✔ Prevent race conditions<br>✔ Used internally by Redis</p><h3>Real-world uses</h3><ul><li>rate limiting</li><li>stock decrement</li><li>distributed locks</li><li>payments</li><li>seat booking</li></ul><h3>Redis Rate Limiting — Real World Use</h3><h3>The problem</h3><p>Users abuse APIs:</p><ul><li>brute-force login</li><li>spam requests</li><li>DDoS-ish behavior</li></ul><h3>Core idea (VERY SIMPLE)</h3><blockquote><em>Count requests per user per time window</em></blockquote><p>Example:</p><pre>Max 100 requests / minute</pre><h3>Redis fits PERFECTLY because:</h3><ul><li>Fast</li><li>Atomic</li><li>TTL support</li></ul><h3>Mental model</h3><p>For each user:</p><pre>user:123:requests → counter</pre><p>Steps:</p><ol><li>Increase counter</li><li>If first request → set expiry</li><li>If limit exceeded → block</li></ol><h3>Why Lua is often used here</h3><p>Without Lua:</p><ul><li>Race conditions</li><li>Inaccurate limits</li></ul><p>With Lua:</p><ul><li>Check + increment + expire = ONE step</li></ul><p>🔥 <strong>This is where Lua + Redis shine together</strong></p><h3>Example scenario</h3><pre>User sends request<br>↓<br>Redis checks count<br>↓<br>Allowed? → continue<br>Blocked? → 429 error</pre><h3>Redis Security</h3><ul><li>Password auth</li><li>TLS</li><li>IP whitelisting</li><li>Never expose to public internet ❌</li></ul><h3>Redis in Production (Best Practices)</h3><p>✔ Use TTL always<br>✔ Avoid huge keys<br>✔ Use namespaces<br>✔ Monitor memory<br>✔ Eviction policy (LRU)<br>✔ Redis ≠ primary DB</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8324c9f353e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js — Complete Beginner → Advanced Guide]]></title>
            <link>https://medium.com/@farihakausar18/next-js-complete-beginner-advanced-guide-af717bf927c6?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/af717bf927c6</guid>
            <category><![CDATA[static-site-generation]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 06:55:14 GMT</pubDate>
            <atom:updated>2026-01-29T06:55:14.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>Next.js — Complete Beginner → Advanced Guide</h3><p>This is a <strong>full, production-ready Next.js guide</strong> designed for developers who want to understand Next.js deeply and write real-world applications.</p><h3>What is Next.js?</h3><p>Next.js is a React framework that enables:</p><ul><li>Server-side rendering (SSR)</li><li>Static site generation (SSG)</li><li>Incremental static regeneration (ISR)</li><li>Full-stack APIs</li><li>File-based routing</li><li>Performance optimization</li><li>SEO-friendly apps</li></ul><p>👉 In simple words: <strong>React + Backend + Performance + SEO</strong></p><h3>Prerequisites</h3><p>Before learning Next.js, you should know:</p><h3>JavaScript</h3><ul><li>ES6+ syntax</li><li>Async/await, promises</li><li>Modules</li><li>Array methods</li></ul><h3>React</h3><ul><li>Components</li><li>Props &amp; state</li><li>Hooks (useState, useEffect)</li><li>JSX</li><li>Conditional rendering</li></ul><h3>Next.js Routers Explained</h3><h3>1) Pages Router (Old)</h3><p>Folder:</p><pre>pages/</pre><p>Features:</p><ul><li>Client-side by default</li><li>getServerSideProps, getStaticProps</li><li>Manual layouts</li><li>Legacy projects</li></ul><h3>2) App Router (New, Recommended)</h3><p>Folder:</p><pre>app/</pre><p>Features:</p><ul><li>Server Components by default</li><li>Nested layouts</li><li>Streaming &amp; Suspense</li><li>Server Actions</li><li>Better performance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*uBOhQ_y004tK6vF196sJXg.png" /></figure><p>👉 Use App Router for all new projects.</p><h3>Project Structure (App Router)</h3><pre>app/<br> ├─ page.tsx<br> ├─ layout.tsx<br> ├─ loading.tsx<br> ├─ error.tsx<br> ├─ api/<br> └─ blog/<br>     └─ [slug]/page.tsx<br>public/<br>next.config.js</pre><h3>Routing in Next.js</h3><h3>Static Routes</h3><pre>app/blog/page.tsx → /blog</pre><h3>Dynamic Routes</h3><pre>app/blog/[slug]/page.tsx</pre><pre>export default function Page({ params }) {<br>  return &lt;h1&gt;{params.slug}&lt;/h1&gt;<br>}</pre><h3>Nested Routes</h3><pre>app/dashboard/settings/page.tsx</pre><h3>Route Groups</h3><pre>(app)/auth/login/page.tsx → /login</pre><h3>Layouts</h3><pre>export default function RootLayout({ children }) {<br>  return (<br>    &lt;html&gt;<br>      &lt;body&gt;<br>        &lt;Navbar /&gt;<br>        {children}<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><h3>Rendering Strategies (Core Concept)</h3><h3>1) CSR — Client Side Rendering</h3><ul><li>Data fetched in browser</li><li>Poor SEO</li><li>Used for interactive UI</li></ul><h3>2) SSR — Server Side Rendering</h3><ul><li>Data fetched on server</li><li>Fresh data</li><li>Slower than static</li></ul><h3>3) SSG — Static Site Generation</h3><ul><li>Built at build time</li><li>Very fast</li><li>Best for blogs/docs</li></ul><h3>4)<strong>ISR (Incremental Static Regeneration)</strong></h3><h3>What problem does ISR solve?</h3><p>Before ISR, you had <strong>two bad choices</strong>:</p><h3>❌ SSG (Static Site Generation)</h3><ul><li>Super fast</li><li>But data is <strong>stuck at build time</strong></li><li>If content changes → rebuild whole site 😤</li></ul><h3>❌ SSR (Server Side Rendering)</h3><ul><li>Always fresh data</li><li>But <strong>slower</strong></li><li>Server runs on every request 💸</li></ul><p>👉 <strong>ISR gives you the BEST of BOTH worlds</strong></p><h3>What is ISR?</h3><blockquote><strong><em>ISR = Static pages that automatically update in the background</em></strong></blockquote><ul><li>Page is <strong>pre-built</strong></li><li>Served <strong>instantly</strong></li><li>Re-generated <strong>after a set time</strong></li><li>WITHOUT rebuilding entire site</li></ul><h3>Simple Mental Model</h3><p>Think of ISR like this:</p><blockquote><em>“Serve cached static page,<br>but if it’s old → quietly rebuild it in background”</em></blockquote><p>Users <strong>never wait</strong>.</p><h3>How ISR Works (Step-by-Step)</h3><p>Let’s say:</p><pre>revalidate: 60</pre><h3>First user</h3><ul><li>Page is built</li><li>Saved as static HTML</li></ul><h3>Next users (within 60s)</h3><ul><li>Same static page</li><li>⚡ instant load</li></ul><h3>After 60s</h3><ul><li>Next request:</li><li>User still gets old page</li><li>Next.js <strong>rebuilds page in background</strong></li></ul><h3>Following users</h3><ul><li>Get <strong>fresh updated page</strong></li></ul><p>No downtime. No rebuild button.</p><h3>How to Use ISR (App Router)</h3><h3>Basic Example</h3><pre>const res = await fetch(&quot;https://api.example.com/posts&quot;, {<br>  next: { revalidate: 60 }<br>})</pre><pre>const posts = await res.json()</pre><p>✅ Page becomes ISR<br>✅ Rebuild every 60 seconds</p><h3>Full Page Example</h3><pre>export default async function BlogPage() {<br>  const posts = await fetch(<br>    &quot;https://api.example.com/posts&quot;,<br>    { next: { revalidate: 60 } }<br>  ).then(res =&gt; res.json())</pre><pre>  return (<br>    &lt;ul&gt;<br>      {posts.map(p =&gt; &lt;li key={p.id}&gt;{p.title}&lt;/li&gt;)}<br>    &lt;/ul&gt;<br>  )<br>}</pre><h3>ISR vs SSG vs SSR (Use Cases)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*angVe1W9cUi0vk0uwOFgeA.png" /></figure><h3>ISR vs SSG vs SSR (Features Comparison)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*qxXgVTD-IbX4aOQWQLiwpg.png" /></figure><h3>When SHOULD you use ISR?</h3><h3>Perfect for:</h3><ul><li>Blogs</li><li>News websites</li><li>Product listings</li><li>Marketing pages</li><li>Docs</li><li>Landing pages with updates</li></ul><h3>NOT good for:</h3><ul><li>User-specific data</li><li>Auth dashboards</li><li>Real-time data (chat, stock price)</li></ul><h3>Choosing Revalidate Time</h3><p>Revalidate Use case<br>10sBreaking news<br>60sBlog updates<br>300sProducts<br>3600sDocs</p><p>Rule of thumb:</p><blockquote><strong><em>How stale is acceptable?</em></strong></blockquote><h3>Advanced ISR Concepts</h3><h3>On-Demand Revalidation</h3><p>Instead of waiting time, trigger rebuild manually.</p><pre>revalidatePath(&quot;/blog&quot;)</pre><p>Use when:</p><ul><li>CMS update</li><li>Admin publishes content</li></ul><p>Instant update.</p><h3>Revalidate by Tag</h3><pre>fetch(url, {<br>  next: {<br>    tags: [&quot;posts&quot;]<br>  }<br>})</pre><p>Then:</p><pre>revalidateTag(&quot;posts&quot;)</pre><p>Very powerful in large apps.</p><h3>Common Mistakes</h3><p>❌ Using ISR for user data<br>❌ Very small revalidate time (wastes resources)<br>❌ Forgetting caching exists<br>❌ Expecting real-time updates</p><h3>Real-Life Example (E-commerce)</h3><ul><li>Product page → ISR (5 min)</li><li>Homepage → ISR (1 min)</li><li>Cart → SSR</li><li>Checkout → SSR</li><li>Admin dashboard → SSR</li></ul><p>One-Line Summary</p><blockquote><strong><em>ISR = Static pages that refresh themselves automatically without slowing users or rebuilding the ap</em></strong></blockquote><h3>Pro Tip (INTERVIEW GOLD)</h3><p>If asked:</p><blockquote>“Why ISR over SSR?”</blockquote><p>Say:</p><blockquote><em>“ISR provides near-instant performance like SSG with controlled data freshness, reducing server load while keeping content up to date.”</em></blockquote><h3>Server Component (default)</h3><p>export default function Page() {}</p><h3>Client Component</h3><p>“use client”</p><p>Use client components when you need:</p><ul><li>State</li><li>Events</li><li>Browser APIs</li></ul><h3>Server Actions</h3><p>“use server”</p><p>export async function createPost(formData) {</p><p>// DB logic</p><p>}</p><p>Benefits:</p><ul><li>No API routes</li><li>Secure</li><li>Clean code</li></ul><h3>API Routes (Backend in Next.js)</h3><p>app/api/posts/route.ts</p><p>export async function GET() {</p><p>return Response.json({ posts: [] })</p><p>}</p><h3>Authentication &amp; Middleware</h3><h3>Middleware</h3><p>export function middleware(req) {</p><p>// auth logic</p><p>}</p><h3>Auth Options</h3><ul><li>Auth.js / NextAuth</li><li>JWT</li><li>OAuth</li></ul><h3>Styling in Next.js</h3><p>Options:</p><ul><li>CSS Modules</li><li>Tailwind CSS ⭐</li><li>Styled Components</li></ul><p>Example:</p><p>&lt;div className=”text-lg font-bold”&gt;Hello&lt;/div&gt;</p><h3>Performance Optimization</h3><h3>Image Optimization</h3><p>import Image from “next/image”</p><h3>Font Optimization</h3><p>import { Inter } from “next/font/google”</p><h3>Conclusion</h3><p>Next.js is not just a React framework — it is a <strong>full-stack platform</strong> for building modern, scalable, high-performance web applications.</p><p>If you master:</p><ul><li>Routing</li><li>Rendering strategies</li><li>Server components</li><li>ISR &amp; caching</li><li>Auth &amp; APIs</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af717bf927c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Redux]]></title>
            <link>https://medium.com/@farihakausar18/react-redux-10945dbaf491?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/10945dbaf491</guid>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 05:54:22 GMT</pubDate>
            <atom:updated>2026-01-27T05:54:22.876Z</atom:updated>
            <content:encoded><![CDATA[<p>C<strong>omplete, ultimate, beginner → advanced guide</strong> for:</p><p>✔ <strong>React Redux</strong><br> ✔ <strong>Redux Toolkit (RTK)</strong><br> ✔ <strong>Redux Thunk (middleware)</strong><br> ✔ <strong>Zustand</strong><br> ✔ <strong>When to use Redux vs Zustand vs React Query</strong><br> ✔ <strong>Project structure + examples</strong><br> ✔ <strong>Full code snippets</strong></p><p>This is EVERYTHING you need — clean, simple, and production-ready.</p><h3>1. REDUX (Old Traditional Redux) — Full Concept</h3><p>Redux is a <strong>centralized state management library</strong>.</p><h3>Core Concepts</h3><ol><li><strong>Store</strong> → Global state</li><li><strong>Actions</strong> → What happened</li><li><strong>Reducers</strong> → How state changes</li><li><strong>Dispatch</strong> → Sends action to store</li><li><strong>subscribe()</strong> → Listen for updates</li></ol><p>Old Redux Example (for understanding only)</p><h4>Action</h4><pre>export const increment = () =&gt; ({<br>  type: &quot;INCREMENT&quot;<br>});</pre><h4>Reducer</h4><pre>const counterReducer = (state = { count: 0 }, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;INCREMENT&quot;: return { count: state.count + 1 };<br>    default: return state;<br>  }<br>};</pre><h4>Store</h4><pre>import { createStore } from &quot;redux&quot;;<br>const store = createStore(counterReducer);</pre><p>⚠️ <strong>Old Redux = too much boilerplate → no one uses it now.</strong><br> Use <strong>Redux Toolkit</strong> instead.</p><h3>2. REDUX TOOLKIT (RTK) — Modern Redux (Recommended)</h3><p>Redux Toolkit is the <strong>official recommended way</strong> to use Redux today.</p><p>Advantages:</p><p>✔ Less boilerplate<br> ✔ Built-in immer (mutate state easily)<br> ✔ Slices<br> ✔ Built-in Thunk middleware<br> ✔ DevTools</p><h3>2.1. Redux Toolkit Slice</h3><pre>import { createSlice } from &quot;@reduxjs/toolkit&quot;;</pre><pre>const counterSlice = createSlice({<br>  name: &quot;counter&quot;,<br>  initialState: { value: 0 },<br>  reducers: {<br>    increment: (state) =&gt; { state.value++ },<br>    decrement: (state) =&gt; { state.value-- },<br>    add: (state, action) =&gt; { state.value += action.payload }<br>  }<br>});</pre><pre>export const { increment, decrement, add } = counterSlice.actions;<br>export default counterSlice.reducer;</pre><h3>2. Store Setup</h3><pre>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import counterReducer from &quot;./counterSlice&quot;;</pre><pre>export const store = configureStore({<br>  reducer: {<br>    counter: counterReducer<br>  }<br>});</pre><h3>2.3. Use in Component</h3><pre>import { useSelector, useDispatch } from &quot;react-redux&quot;;<br>import { increment } from &quot;./counterSlice&quot;;</pre><pre>function App() {<br>  const value = useSelector(state =&gt; state.counter.value);<br>  const dispatch = useDispatch();</pre><pre>  return (<br>    &lt;button onClick={() =&gt; dispatch(increment())}&gt;<br>      Count: {value}<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>Async with RTK → createAsyncThunk</h3><p>This replaces Redux Thunk boilerplate.</p><pre>export const fetchUsers = createAsyncThunk(<br>  &quot;users/fetch&quot;,<br>  async () =&gt; {<br>    const res = await fetch(&quot;/api/users&quot;)<br>    return res.json()<br>  }<br>)</pre><pre>extraReducers: (builder) =&gt; {<br>  builder<br>    .addCase(fetchUsers.pending, (state) =&gt; {<br>      state.loading = true<br>    })<br>    .addCase(fetchUsers.fulfilled, (state, action) =&gt; {<br>      state.loading = false<br>      state.users = action.payload<br>    })<br>    .addCase(fetchUsers.rejected, (state) =&gt; {<br>      state.loading = false<br>      state.error = true<br>    })<br>}</pre><p>🔥 Clean<br> 🔥 Standardized<br> 🔥 Less bugs</p><h3>3. REDUX THUNK — Async Logic in Redux</h3><p>Thunk allows async actions:</p><p>Examples:</p><ul><li>API calls</li><li>Waiting for data</li><li>Dispatch after response</li></ul><h3>3.1 Example of Thunk</h3><pre>export const fetchUsers = () =&gt; async (dispatch) =&gt; {<br>  dispatch(startLoading());</pre><pre>  try {<br>    const res = await fetch(&quot;https://api.example.com/users&quot;);<br>    const data = await res.json();</pre><pre>    dispatch(loadUsersSuccess(data));<br>  } catch (e) {<br>    dispatch(loadUsersError());<br>  }<br>};</pre><h3>3.2 Usage inside Redux Toolkit slice</h3><pre>import { createSlice, createAsyncThunk } from &quot;@reduxjs/toolkit&quot;;</pre><pre>export const fetchUsers = createAsyncThunk(<br>  &quot;users/fetch&quot;,<br>  async () =&gt; {<br>    const res = await fetch(&#39;/api/users&#39;);<br>    return res.json();<br>  }<br>);</pre><pre>const userSlice = createSlice({<br>  name: &quot;users&quot;,<br>  initialState: { list: [], loading: false },<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(fetchUsers.pending, (state) =&gt; { state.loading = true })<br>      .addCase(fetchUsers.fulfilled, (state, action) =&gt; {<br>        state.loading = false;<br>        state.list = action.payload;<br>      });<br>  }<br>});</pre><h3>4. ZUSTAND — Lightweight State Management</h3><p>Zustand is a simple and powerful alternative to Redux.</p><p>✔ Less code<br> ✔ No reducers<br> ✔ No boilerplate<br> ✔ Supports async easily<br> ✔ Perfect for UI state, forms, simple apps</p><h3>4.1 Basic Zustand Store</h3><pre>import { create } from &#39;zustand&#39;;</pre><pre>export const useCounterStore = create((set) =&gt; ({<br>  value: 0,<br>  increment: () =&gt; set((state) =&gt; ({ value: state.value + 1 })),<br>  decrement: () =&gt; set((state) =&gt; ({ value: state.value - 1 }))<br>}));</pre><h3>4.2 Use in Component</h3><pre>function App() {<br>  const { value, increment } = useCounterStore();</pre><pre>  return (<br>    &lt;button onClick={increment}&gt;<br>      Count: {value}<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>5. Async API Calls in Zustand</h3><p>Super easy (no thunk needed):</p><pre>export const useUserStore = create((set) =&gt; ({<br>  users: [],<br>  loading: false,</pre><pre>  fetchUsers: async () =&gt; {<br>    set({ loading: true });<br>    const res = await fetch(&#39;/api/users&#39;);<br>    const data = await res.json();<br>    set({ users: data, loading: false });<br>  }<br>}));</pre><h3>6. Redux Toolkit vs Zustand vs React Query (Clear Comparison)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*fk6-Uz8dFFfSRSZ6Nsuwpw.png" /></figure><p><strong>7.List of libraries you need to install</strong> for <strong>ALL FOUR</strong>: <strong>Redux, Redux Toolkit, Redux Thunk, Zustand, React Query</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*qYNd-4IVzpgRHueOi1a2jQ.png" /></figure><h3>8. Folder Structure for Redux Toolkit</h3><pre>src/<br> ├── store/<br> │   ├── index.js<br> │   └── slices/<br> │       ├── userSlice.js<br> │       └── cartSlice.js<br> │<br> ├── api/<br> │   └── user.api.js<br> │<br> ├── components/<br> │   └── UserList.jsx<br> │<br> └── pages/<br>     └── Home.jsx</pre><h3>9. Folder Structure for Zustand</h3><pre>src/<br> ├── store/<br> │   ├── user.store.js<br> │   └── cart.store.js<br> │<br> ├── api/<br> │   └── user.api.js<br> │<br> ├── components/<br> │   └── CartIcon.jsx<br> │<br> └── pages/<br>     └── Dashboard.jsx</pre><h4>Summary :For API calls → React Query</h4><h4>✔ For UI state → Zustand</h4><h4>✔ For huge enterprise apps → Redux Toolkit</h4><h4>✔ If you need middlewares → Redux Toolkit (RTK)</h4><p><strong>Best Modern Combo (2025 standard):</strong><br> React Query (server state)<br>Zustand (UI state)<br> Optional: Redux Toolkit only for very large apps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10945dbaf491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ultimate CI/CD Guide for MERN Developers (Beginner to Advanced)]]></title>
            <link>https://medium.com/@farihakausar18/ultimate-ci-cd-guide-for-mern-developers-beginner-to-advanced-97c29e0a37f6?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/97c29e0a37f6</guid>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[circleci-orbs]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 08:21:26 GMT</pubDate>
            <atom:updated>2026-01-21T08:21:26.378Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is CI/CD?</h3><p><strong>CI/CD</strong> stands for:</p><ul><li><strong>CI → Continuous Integration</strong></li><li><strong>CD → Continuous Delivery / Deployment</strong></li></ul><p>It’s a <strong>DevOps process</strong> that helps automate testing, building, and deploying your app — so you don’t have to do it manually every time.</p><h3>1. Continuous Integration (CI)</h3><p>This is about <strong>automating testing and building</strong> your code every time someone pushes code to GitHub (or GitLab, Bitbucket, etc.).</p><p><strong>Example steps in CI for a MERN app:</strong></p><ol><li>Developer pushes code to GitHub.</li><li>The CI tool (like <strong>GitHub Actions</strong>, <strong>Jenkins</strong>, or <strong>CircleCI</strong>) automatically:</li></ol><ul><li>Installs dependencies (npm install)</li><li>Runs tests (npm test)</li><li>Builds your React frontend (npm run build)</li><li>Checks for linting and errors.</li></ul><p>✅ Goal: Catch bugs early and ensure code is working before merging.</p><h3>2. Continuous Delivery / Deployment (CD)</h3><p>This part <strong>automatically deploys</strong> your tested app to a server or cloud platform.</p><p><strong>Example steps in CD for MERN:</strong></p><ol><li>Once CI passes successfully, the pipeline deploys code to:</li></ol><ul><li><strong>Staging server</strong> (for testing)</li><li><strong>Production server</strong> (for users)</li></ul><p>Deployment can be done using:</p><ul><li><strong>Docker + Kubernetes</strong></li><li><strong>AWS EC2 / Elastic Beanstalk</strong></li><li><strong>Vercel / Render / Netlify</strong> for frontend</li><li><strong>Railway / MongoDB Atlas / DigitalOcean</strong> for backend and DB.</li></ul><p>✅ Goal: Deploy changes automatically with minimal manual work.</p><h3>⚙️ Common CI/CD Tools</h3><p>Purpose Tools CI/CD Pipelines <strong>GitHub Actions</strong>, GitLab CI/CD, CircleCI, Jenkins Deployment Docker, Kubernetes, AWS, Vercel, Netlify, Render Monitoring PM2, New Relic, Datadog</p><h3>Understanding GitHub Actions (CI/CD Engine)</h3><p><strong>GitHub Actions</strong> is a free automation tool built into GitHub.<br> Whenever you push code, it can <strong>automatically</strong>:</p><p>✅ Clone your repo<br> ✅ Install dependencies<br> ✅ Run tests or build<br> ✅ Deploy your code to your chosen server<br>What Happens Automatically on Platforms Like Vercel / Netlify</p><p>When you connect your <strong>GitHub repo</strong> to:</p><ul><li><strong>Vercel</strong></li><li><strong>Netlify</strong></li><li><strong>Render</strong></li></ul><p>They already do <strong>built-in CI/CD</strong> for you.<br> Here’s what they do automatically:</p><p>Step <br>What Vercel / Netlify does automatically<br>1.Detect your project (React, Next.js, etc.)<br>2.Pull your latest code from GitHub whenever you push<br>3.Run npm install and npm run build<br>4.Deploy the built app to their servers instantly</p><p>✅ You don’t have to write .yml yourself.<br>✅ You just connect GitHub → choose branch → done.</p><p>So yes, <strong>Vercel and Netlify have “auto CI/CD” built-in.<br></strong>Then Why Learn CI/CD Manually?</p><p>Because:</p><ol><li>Not every platform (like AWS, DigitalOcean, EC2, custom VPS) gives you auto-deploy.</li><li>You often want <strong>more control</strong>:</li></ol><ul><li>Run tests before deploying</li><li>Deploy backend &amp; frontend together</li><li>Restart server automatically</li><li>Manage complex environments (staging, production)</li></ul><ol><li>CI/CD YAML files make this <strong>platform-independent</strong> — you can deploy <em>anywhere.</em></li></ol><h3>— When Do You Need a .yml File?</h3><p>Platform Need YAML? Why <strong>Vercel / Netlify</strong> ❌ No They handle builds/deploys automatically <br><strong>Render / Railway</strong> ⚙️ Optional Built-in deploys from GitHub, but custom YAML adds testing steps <br><strong>AWS / EC2 / DigitalOcean / Custom Server</strong> ✅ Yes You must define full CI/CD process manually</p><p>MERN Stack Structure to Prepare for CI/CD</p><p>root/<br>│<br>├── client/ # React frontend<br>│ ├── src/<br>│ ├── package.json<br>│ └── .env<br>│<br>├── server/ # Node.js + Express backend<br>│ ├── src/<br>│ ├── package.json<br>│ └── .env<br>│<br>├── .github/<br>│ └── workflows/ # CI/CD workflow files live here<br>│<br>└── README.md</p><h3>Example: GitHub Actions for MERN</h3><p>A simple .github/workflows/deploy.yml:name: CI/CD Pipeline</p><pre>name: MERN CI/CD Pipeline</pre><pre>on:<br>  push:<br>    branches:<br>      - main   # Runs every time you push to the main branch</pre><pre>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest</pre><pre>steps:<br>      # Step 1: Checkout your code<br>      - name: Checkout code<br>        uses: actions/checkout@v3</pre><pre># Step 2: Install backend dependencies<br>      - name: Install Backend Dependencies<br>        run: |<br>          cd server<br>          npm install</pre><pre># Step 3: Run backend tests (optional)<br>      - name: Run Backend Tests<br>        run: |<br>          cd server<br>          npm test || echo &quot;No backend tests&quot;</pre><pre># Step 4: Install frontend dependencies and build React app<br>      - name: Build Frontend<br>        run: |<br>          cd client<br>          npm install<br>          npm run build</pre><pre># Step 5: Deploy to your server<br>      - name: Deploy to Production Server<br>        env:<br>          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}<br>        run: |<br>          echo &quot;$SSH_PRIVATE_KEY&quot; &gt; private_key.pem<br>          chmod 600 private_key.pem<br>          ssh -o StrictHostKeyChecking=no -i private_key.pem user@yourserver &quot;<br>            cd /path/to/your/app &amp;&amp;<br>            git pull &amp;&amp;<br>            npm install &amp;&amp;<br>            cd client &amp;&amp; npm run build &amp;&amp;<br>            pm2 restart all<br>          &quot;</pre><h3>Secure Your Secrets (Very Important)</h3><p>In GitHub:</p><ol><li>Go to <strong>Repository → Settings → Secrets → Actions</strong></li><li>Add your secrets:</li></ol><ul><li>SSH_PRIVATE_KEY → your server’s private key (for SSH access)</li><li>SERVER_IP → your server IP (optional)</li><li>SERVER_USER → your username (optional)</li><li>Any environment variables (like Mongo URI, API keys)</li></ul><p>This way, your credentials stay safe and aren’t written in the YAML file.</p><h3>Line-by-Line Explanation (Beginner → Advanced)</h3><h3>🔹 name: MERN CI/CD Pipeline</h3><blockquote><em>This is just the display name of your pipeline — you’ll see it in GitHub Actions dashboard ( From Github repo actions tab)<br></em>🔹 on:</blockquote><blockquote><em>Defines when the pipeline should run.<br> For example:</em></blockquote><pre>on:<br>  push:<br>    branches:<br>      - main</pre><p>👉 Means: whenever you push new code to the <strong>main</strong> branch, this workflow runs automatically.<br> You can also use:</p><pre>on:<br>  pull_request:</pre><p>to run it only when a PR is made.<br> jobs:</p><blockquote><em>job = a group of steps that run in a virtual machine.</em></blockquote><p>You can have multiple jobs (like test, build, deploy), but here we have one.<br> build-and-deploy:</p><blockquote><em>This is the </em><strong><em>name of our job</em></strong><em> — you can name it anything.<br> It contains all the steps for building and deploying.<br></em> runs-on: ubuntu-latest</blockquote><blockquote><em>Tells GitHub Actions </em><strong><em>which operating system</em></strong><em> to use inside its runner.<br> Ubuntu is Linux-based and works well for Node.js.<br></em>🔹 steps:</blockquote><blockquote><em>Inside here we define all actions one by one.<br></em>🔹 Step 1: Checkout code</blockquote><pre>- name: Checkout code<br>  uses: actions/checkout@v3</pre><p>✅ This downloads your repo’s code into GitHub’s runner environment.<br> Without this, GitHub doesn’t know what files to work with.<br>Step 2: Install Backend Dependencies</p><pre>- name: Install Backend Dependencies<br>  run: |<br>    cd server<br>    npm install</pre><p>✅ Enters the backend folder → installs all required packages from package.json.</p><h3>Step 3: Run Backend Tests</h3><pre>- name: Run Backend Tests<br>  run: |<br>    cd server<br>    npm test || echo &quot;No backend tests&quot;</pre><p>✅ Runs npm test (if you have tests).<br> If you don’t, it won’t crash the build — it’ll just print “No backend tests.”</p><h3>Step 4: Build Frontend</h3><pre>- name: Build Frontend<br>  run: |<br>    cd client<br>    npm install<br>    npm run build</pre><p>✅ Installs dependencies for React and builds a production-ready version in /client/build.</p><h3>Step 5: Deploy to Production Server</h3><pre>- name: Deploy to Production Server<br>  env:<br>    SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}<br>  run: |<br>    echo &quot;$SSH_PRIVATE_KEY&quot; &gt; private_key.pem<br>    chmod 600 private_key.pem<br>    ssh -o StrictHostKeyChecking=no -i private_key.pem user@yourserver &quot;<br>      cd /path/to/your/app &amp;&amp;<br>      git pull &amp;&amp;<br>      npm install &amp;&amp;<br>      cd client &amp;&amp; npm run build &amp;&amp;<br>      pm2 restart all<br>    &quot;</pre><p>Line Meaning <br>env: Sets environment variables (safe values stored in GitHub Secrets) SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}<br> Reads your saved private key from GitHub Secrets <br> echo &quot;$SSH_PRIVATE_KEY&quot; &gt; private_key.pem Writes the key into a file for SSH connection <br> chmod 600 private_key.pem Restricts permissions to that key file<br> ssh -o StrictHostKeyChecking=no -i private_key.pem user@yourserver Logs into your server securely <br> cd /path/to/your/app &amp;&amp; git pull Pulls the latest code on your server <br> npm install Installs new packages if any cd client &amp;&amp; npm run build Rebuilds frontend for production pm2 restart all Restarts your Node app via PM2</p><h3>Advanced: Environment Variables, SSH Keys, PM2, Docker</h3><p>Now we’ll deploy to a real server (like AWS EC2 / DigitalOcean).<br> To do that safely, we store secrets and automate deployment.</p><h3>3.1 — Create SSH key pair</h3><p>Run this <strong>on your local machine</strong> (not GitHub):</p><pre>ssh-keygen -t rsa -b 4096 -C &quot;github-ci&quot;</pre><p>It creates:</p><ul><li><strong>Private key:</strong> id_rsa</li><li><strong>Public key:</strong> id_rsa.pub</li></ul><h3>🔐 3.2 — Add the Public key to your server</h3><p>Copy the content of id_rsa.pub →<br> On your server (EC2, VPS):</p><pre>mkdir -p ~/.ssh<br>echo &quot;paste_public_key_here&quot; &gt;&gt; ~/.ssh/authorized_keys<br>chmod 600 ~/.ssh/authorized_keys</pre><p>Now GitHub can SSH into your server securely.</p><h3>🔒 3.3 — Add the Private key to GitHub Secrets</h3><h4>👉 Steps:</h4><ol><li>Go to your GitHub repo → <strong>Settings</strong></li><li>Click <strong>Secrets and variables → Actions</strong></li><li>Click <strong>New repository secret</strong></li><li>Name it SSH_PRIVATE_KEY</li><li>Paste entire contents of your local id_rsa (private key)</li></ol><p>You can add more secrets too:</p><p>NameValueSERVER_USERubuntu (or root)SERVER_IP1.2.3.4MONGO_URIyour Mongo connection string<br>3.4 — Use Secrets in YAML</p><pre>      - name: Deploy to server<br>        env:<br>          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}<br>          SERVER_USER: ${{ secrets.SERVER_USER }}<br>          SERVER_IP: ${{ secrets.SERVER_IP }}<br>        run: |<br>          echo &quot;$SSH_PRIVATE_KEY&quot; &gt; key.pem<br>          chmod 600 key.pem<br>          ssh -o StrictHostKeyChecking=no -i key.pem $SERVER_USER@$SERVER_IP &quot;<br>            cd /app &amp;&amp;<br>            git pull &amp;&amp;<br>            npm ci &amp;&amp;<br>            pm2 restart all<br>          &quot;</pre><h3>Expert: Multi-Environment Pipelines, Caching, Parallel Jobs</h3><h3>4.1 — Multi-Environment</h3><p>You might want separate environments:</p><p>EnvBranchExampleDevdev<br>For internal testingStagingstaging<br>Pre-productionProdmainLive</p><pre>on:<br>  push:<br>    branches: [dev, staging, main]</pre><p>Then use if: conditions:</p><pre>- name: Deploy Dev<br>  if: github.ref == &#39;refs/heads/dev&#39;<br>  run: echo &quot;Deploying to dev...&quot;</pre><h3>🔹 4.2 — Caching node_modules</h3><p>Speed up builds:</p><pre>- name: Cache node modules<br>  uses: actions/cache@v3<br>  with:<br>    path: ~/.npm<br>    key: ${{ runner.os }}-node-${{ hashFiles(&#39;**/package-lock.json&#39;) }}</pre><h3>🔹 4.3 — Parallel jobs</h3><p>Split frontend/backend builds:</p><pre>jobs:<br>  backend:<br>    runs-on: ubuntu-latest<br>    steps: ...<br>  frontend:<br>    runs-on: ubuntu-latest<br>    steps: ...</pre><p>Both run at the same time → faster pipeline.</p><h3>5️⃣ — Complete Advanced Example (Summary)</h3><pre>name: MERN CI/CD</pre><pre>on:<br>  push:<br>    branches: [dev, staging, main]</pre><pre>jobs:<br>  build-test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - uses: actions/cache@v3<br>        with:<br>          path: ~/.npm<br>          key: ${{ runner.os }}-${{ hashFiles(&#39;**/package-lock.json&#39;) }}<br>      - run: cd server &amp;&amp; npm ci &amp;&amp; npm test<br>      - run: cd client &amp;&amp; npm ci &amp;&amp; npm run build</pre><pre>  deploy:<br>    needs: build-test<br>    runs-on: ubuntu-latest<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Deploy to Production<br>        env:<br>          SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}<br>          SERVER_USER: ${{ secrets.SERVER_USER }}<br>          SERVER_IP: ${{ secrets.SERVER_IP }}<br>        run: |<br>          echo &quot;$SSH_PRIVATE_KEY&quot; &gt; key.pem<br>          chmod 600 key.pem<br>          ssh -o StrictHostKeyChecking=no -i key.pem $SERVER_USER@$SERVER_IP &quot;<br>            cd /app &amp;&amp; git pull &amp;&amp; npm ci &amp;&amp; pm2 restart all&quot;</pre><h3>CI/CD Tools Explained for MERN Stack Developers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*jgSLCVrBxZrXH7JqHdVMqw.png" /></figure><h3>CircleCI Guide for MERN Developers</h3><h3>What is CircleCI?</h3><p><strong>CircleCI</strong> is a <strong>Continuous Integration and Continuous Deployment (CI/CD)</strong> platform.<br> It automates how you build, test, and deploy your app — every time you push code to GitHub or Bitbucket.</p><p>CircleCI connects directly to your repository.<br> When it sees a new commit or pull request:</p><ol><li>It pulls your code into a <strong>container (like Docker)</strong></li><li>Runs your defined build/test/deploy steps (from a YAML file)</li><li>Reports success/failure instantly on GitHub</li></ol><h3>Why Use CircleCI?</h3><p>Feature Why It’s Useful <br><strong>Speed</strong> CircleCI is optimized for <strong>parallel and cached builds</strong> — super fast. <strong>Docker Support</strong> Every job runs in a Docker container. Great for Node/MERN. <br><strong>Security</strong> Each build runs in an isolated environment — secure by default. <strong>No Setup</strong> Cloud version needs no installation. Just connect GitHub. <br><strong>Cross-platform</strong> Supports Linux, macOS, Windows environments. <br><strong>Scalable</strong> Handles from one app to hundreds of microservices.</p><h3>CircleCI Architecture (How It Works)</h3><p>Here’s how it flows:</p><pre>You push code to GitHub →<br>CircleCI detects the change →<br>Runs your pipeline defined in .circleci/config.yml →<br>Executes jobs (build, test, deploy) inside containers →<br>Reports back results to GitHub (✅ or ❌)</pre><p>You define everything inside a file:<br> <strong>.circleci/config.yml</strong></p><h3>Core Concepts in CircleCI</h3><p>Understanding these 6 building blocks makes everything click</p><p>Term Meaning</p><p><strong>Pipeline</strong> The whole CI/CD process (all jobs + workflows). <br><strong>Workflow</strong> Defines the sequence of jobs (build → test → deploy).<br> <strong>Job</strong> A unit of work (e.g., “build frontend”). Each job runs in its own environment.<br> <strong>Step</strong> A command or action inside a job (e.g., npm install, npm test). <strong>Executor</strong> Defines the environment — like Docker image, machine, or macOS. <br><strong>Context</strong> A way to store environment variables securely (API keys, secrets).</p><h3>Basic CircleCI YAML Example (for MERN Stack)</h3><p>Create a folder in your repo:</p><pre>.circleci/config.yml</pre><p>Then paste this:</p><pre>version: 2.1</pre><pre>jobs:<br>  build:<br>    docker:<br>      - image: circleci/node:18<br>    steps:<br>      - checkout<br>      - run:<br>          name: Install Backend Dependencies<br>          command: |<br>            cd server<br>            npm install<br>      - run:<br>          name: Install Frontend Dependencies<br>          command: |<br>            cd client<br>            npm install<br>      - run:<br>          name: Build Frontend<br>          command: |<br>            cd client<br>            npm run build</pre><pre>workflows:<br>  version: 2<br>  build_and_test:<br>    jobs:<br>      - build</pre><h3>Breakdown</h3><ul><li><strong>version</strong> → CircleCI config version (2.1 = latest)</li><li><strong>jobs</strong> → defines all jobs (like build, deploy)</li><li><strong>docker:</strong> → defines the Node.js environment</li><li><strong>checkout</strong> → pulls your code from GitHub</li><li><strong>run</strong> → executes terminal commands</li><li><strong>workflows</strong> → tells CircleCI which jobs to run and in what order</li></ul><h3>Advanced Example (Build + Test + Deploy)</h3><pre>version: 2.1</pre><pre>jobs:<br>  build:<br>    docker:<br>      - image: circleci/node:18<br>    steps:<br>      - checkout<br>      - run: npm ci<br>      - run: npm run lint<br>      - run: npm test<br>      - persist_to_workspace:<br>          root: .<br>          paths:<br>            - .</pre><pre>  deploy:<br>    docker:<br>      - image: circleci/node:18<br>    steps:<br>      - attach_workspace:<br>          at: .<br>      - run:<br>          name: Deploy to AWS EC2<br>          command: |<br>            ssh -o StrictHostKeyChecking=no -i ~/.ssh/aws_key.pem ubuntu@3.83.45.67 &quot;<br>              cd /var/www/mern-app &amp;&amp;<br>              git pull &amp;&amp;<br>              npm install &amp;&amp;<br>              pm2 restart all<br>            &quot;</pre><pre>workflows:<br>  version: 2<br>  build_and_deploy:<br>    jobs:<br>      - build<br>      - deploy:<br>          requires:<br>            - build</pre><h3>Key Features Here</h3><ul><li><strong>persist_to_workspace</strong> saves data between jobs</li><li><strong>requires</strong> ensures deploy runs only after build succeeds</li><li><strong>ssh</strong> connects to your EC2 server for deployment</li></ul><h3>Secrets &amp; Environment Variables</h3><p>CircleCI lets you securely store secrets like:</p><ul><li>API keys</li><li>Database URLs</li><li>AWS credentials</li></ul><h3>Options:</h3><h4>🧩 a) Project Environment Variables</h4><p>Go to your project in CircleCI dashboard website of circle.ci<br><em>Project → Settings → Environment Variables → Add Variable</em></p><p>Example:</p><pre>MONGO_URI=mongodb+srv://...<br>JWT_SECRET=mysecret<br>AWS_KEY=xxxxxx</pre><p>Then access them in YAML:</p><pre>- run:<br>    name: Use environment variables<br>    command: echo $MONGO_URI</pre><h4>b) Contexts (for teams)</h4><p>Create a <strong>context</strong> and share environment vars across multiple projects.<br> Best for team setups and microservices.</p><h3>Triggers &amp; Branch Filters</h3><p>You can choose when pipelines run:</p><pre>workflows:<br>  build_and_deploy:<br>    jobs:<br>      - build<br>      - deploy:<br>          requires:<br>            - build<br>          filters:<br>            branches:<br>              only: main</pre><p>This means:<br> Run deploy <strong>only</strong> on main branch.<br> Skip for feature branches or PRs.<br>Caching Dependencies (to speed up builds)</p><p>Add caching to reuse installed dependencies.</p><pre>- restore_cache:<br>    keys:<br>      - node-deps-{{ checksum &quot;package-lock.json&quot; }}<br>- run: npm install<br>- save_cache:<br>    paths:<br>      - node_modules<br>    key: node-deps-{{ checksum &quot;package-lock.json&quot; }}</pre><p>This cuts build times drastically after the first run</p><p>Reusable Config with Orbs</p><p><strong>CircleCI Orbs (VERY IMPORTANT)<br>Orbs</strong> are pre-made reusable packages for CircleCI.<br> For example, instead of writing your own deploy steps, use the AWS or Heroku orb.</p><p>Example:</p><pre>orbs:<br>  heroku: circleci/heroku@2.0.0</pre><pre>workflows:<br>  deploy:<br>    jobs:<br>      - heroku/deploy-via-git:<br>          app-name: my-mern-app<br>          requires:<br>            - build</pre><p>CircleCI has hundreds of orbs:<br> 👉 <a href="https://circleci.com/developer/orbs/">https://circleci.com/developer/orbs/</a><br>Few of them listed below</p><h3>What is this block?</h3><pre>orbs:<br>  node: circleci/node@5<br>  docker: circleci/docker@2<br>  aws-ecr: circleci/aws-ecr@9<br>  slack: circleci/slack@4</pre><p>👉 This means:<br><strong>“Import 4 ready-made CI tools so I don’t have to write everything manually.”</strong></p><p>Think of <strong>orbs = npm packages for CI/CD</strong>.</p><h3>Explanation of EACH ORB (SIMPLE + REAL USE)</h3><h3>node: circleci/node@5</h3><h3>🔹 What it does</h3><ul><li>Installs Node.js</li><li>Installs npm/yarn dependencies</li><li>Runs tests easily</li></ul><h3>🔹 Why you need it</h3><p>For:</p><ul><li>Node.js backend</li><li>React / Next.js frontend</li><li>MERN apps</li></ul><h3>🔹 Example usage</h3><pre>- node/install-packages<br>- run: npm test</pre><p>👉 Replaces long npm install logic</p><h3>docker: circleci/docker@2</h3><h3>🔹 What it does</h3><ul><li>Builds Docker images</li><li>Pushes images to registry</li><li>Handles Docker login securely</li></ul><h3>🔹 Why you need it</h3><p>For:</p><ul><li>Containerized apps</li><li>Microservices</li><li>Production deployments</li></ul><h3>🔹 Example usage</h3><pre>- docker/build:<br>    image: myapp<br>- docker/push:<br>    image: myapp</pre><p>👉 No need to write docker build manually</p><h3>aws-ecr: circleci/aws-ecr@9</h3><h3>🔹 What it does</h3><ul><li>Authenticates with AWS</li><li>Pushes Docker images to <strong>AWS ECR</strong></li><li>Handles IAM credentials safely</li></ul><h3>🔹 Why you need it</h3><p>For:</p><ul><li>AWS-based deployments</li><li>ECS / EKS / EC2 containers</li></ul><h3>🔹 Example usage</h3><pre>- aws-ecr/build-and-push-image:<br>    repo: my-ecr-repo</pre><p>👉 One command instead of 10 AWS steps</p><h3>slack: circleci/slack@4</h3><h3>🔹 What it does</h3><ul><li>Sends build notifications to Slack</li><li>Alerts on failures or success</li></ul><h3>🔹 Why you need it</h3><p>For:</p><ul><li>Team visibility</li><li>Fast issue response</li></ul><h3>🔹 Example usage</h3><pre>- slack/notify:<br>    event: fail</pre><p>👉 Team gets instant alerts 🚨</p><h3>🔄 HOW THESE 4 ORBS WORK TOGETHER (REAL FLOW)</h3><h3>🚀 Real-World MERN Pipeline</h3><pre>1️⃣ node orb → install dependencies + test<br>2️⃣ docker orb → build Docker image<br>3️⃣ aws-ecr orb → push image to AWS<br>4️⃣ slack orb → notify team</pre><h3>🧠 FULL REAL EXAMPLE (PRODUCTION-STYLE)</h3><pre>version: 2.1</pre><pre>orbs:<br>  node: circleci/node@5<br>  docker: circleci/docker@2<br>  aws-ecr: circleci/aws-ecr@9<br>  slack: circleci/slack@4</pre><pre>jobs:<br>  build-and-deploy:<br>    docker:<br>      - image: cimg/node:18.19<br>    steps:<br>      - checkout</pre><pre>      # 1️⃣ Node<br>      - node/install-packages<br>      - run: npm test</pre><pre>      # 2️⃣ Docker + AWS ECR<br>      - setup_remote_docker<br>      - aws-ecr/build-and-push-image:<br>          repo: my-ecr-repo<br>          tag: latest</pre><pre>      # 3️⃣ Slack Notification<br>      - slack/notify:<br>          event: pass<br>          template: basic_success_1</pre><pre>workflows:<br>  pipeline:<br>    jobs:<br>      - build-and-deploy</pre><h3>SIMPLE ONE-LINE SUMMARY</h3><blockquote><strong><em>These 4 orbs together automate testing, container building, AWS deployment, and team notifications in CircleCI.</em></strong></blockquote><h3>Jenkins — The Complete Beginner → Advanced Guide for MERN Developers</h3><h3>What is Jenkins?</h3><p><strong>Jenkins</strong> is an <strong>open-source CI/CD automation server</strong>.<br> It automates building, testing, and deploying applications — <strong>you host and control it yourself</strong> (unlike CircleCI or GitHub Actions, which are cloud-based).</p><p>💡 Think of Jenkins as your <strong>own build &amp; deployment manager</strong>, running inside your infrastructure (local, AWS EC2, DigitalOcean, etc.).</p><h3>Example Use Case:</h3><p>Whenever you push code to GitHub:</p><ol><li>Jenkins detects the change (via a webhook)</li><li>Pulls the latest code</li><li>Runs your tests</li><li>Builds the frontend and backend</li><li>Deploys the updated app automatically</li></ol><p>All without you doing anything manually.</p><h3>Why Developers Use Jenkins</h3><p>Benefit Description <br><strong>Fully customizable</strong> You control every part of the build/deploy process. <strong>Integrates with everything</strong> GitHub, GitLab, Bitbucket, Docker, AWS, Kubernetes, etc. <br> <strong>Plugin-based</strong> 1,800+ plugins available to add functionality. <br><strong>Self-hosted</strong> Run on your own server (local or cloud). <br> <strong>Supports any tech stack</strong> Node, React, Java, Python, etc. <br><strong>Perfect for complex enterprise pipelines</strong> Parallel builds, multi-stage workflows.</p><h3>Jenkins Architecture (How It Works)</h3><p>Jenkins follows a <strong>master–agent</strong> architecture.</p><pre>GitHub → Jenkins Master → Jenkins Agent (build machine) → Server/Deployment</pre><ul><li><strong>Master</strong> = Orchestrates the pipelines</li><li><strong>Agents</strong> = Machines that actually run your jobs (can be Linux, Windows, macOS, or Docker containers)</li></ul><h3>Key Concepts in Jenkins</h3><p>Concept Meaning<br> <strong>Job (Build)</strong> A single automation process (like building your React app). <strong>Pipeline</strong> A series of jobs that define your full CI/CD flow.<br><strong>Node/Agent</strong> The system where the job runs. <br><strong>Workspace</strong> The folder where your code is cloned and built. <br><strong>Plugin</strong> Add-ons that extend Jenkins (e.g., Git plugin, NodeJS plugin). <strong>Executor</strong> A slot that runs a job on an agent.<br><strong>Artifact</strong> Output from a build (e.g., your React build folder).</p><h3>Jenkinsfile — The Heart of Jenkins CI/CD</h3><p>Jenkins pipelines are defined in a text file called <strong>Jenkinsfile</strong> (just like .yml in GitHub Actions or CircleCI).</p><p>Example for MERN stack:</p><pre>pipeline {<br>  agent any</pre><pre>  environment {<br>    NODE_ENV = &#39;production&#39;<br>    MONGO_URI = credentials(&#39;mongo-uri&#39;)  // stored securely in Jenkins credentials<br>  }</pre><pre>  stages {<br>    stage(&#39;Checkout Code&#39;) {<br>      steps {<br>        git branch: &#39;main&#39;, url: &#39;https://github.com/username/mern-app.git&#39;<br>      }<br>    }</pre><pre>    stage(&#39;Install Dependencies&#39;) {<br>      steps {<br>        sh &#39;cd server &amp;&amp; npm install&#39;<br>        sh &#39;cd client &amp;&amp; npm install&#39;<br>      }<br>    }</pre><pre>    stage(&#39;Build Frontend&#39;) {<br>      steps {<br>        sh &#39;cd client &amp;&amp; npm run build&#39;<br>      }<br>    }</pre><pre>    stage(&#39;Run Tests&#39;) {<br>      steps {<br>        sh &#39;npm test&#39;<br>      }<br>    }</pre><pre>    stage(&#39;Deploy to Server&#39;) {<br>      steps {<br>        sh &#39;&#39;&#39;<br>          ssh -o StrictHostKeyChecking=no ubuntu@3.89.123.45 &quot;<br>            cd /var/www/mern-app &amp;&amp;<br>            git pull &amp;&amp;<br>            npm install &amp;&amp;<br>            pm2 restart all<br>          &quot;<br>        &#39;&#39;&#39;<br>      }<br>    }<br>  }</pre><pre>  post {<br>    success {<br>      echo &#39;✅ Deployment successful!&#39;<br>    }<br>    failure {<br>      echo &#39;❌ Deployment failed!&#39;<br>    }<br>  }<br>}</pre><h3>Breakdown of Jenkinsfile</h3><p>Part Description<br> pipeline {} Declares the start of a Jenkins pipeline <br> agent any Run this pipeline on any available Jenkins agent <br> environment {} Sets environment variables (or credentials) <br> stages {} Each stage represents a build step (install, test, deploy) <br> steps {} Commands to execute (like shell or npm commands) <br> post {} Actions that run after success/failure (like notifications)</p><h3>Installing Jenkins (Locally or on a Server)</h3><h3>Option 1 — Local Machine</h3><pre>brew install jenkins-lts   # macOS<br>sudo apt install jenkins   # Ubuntu</pre><p>Access Jenkins at:<br> ➡️ <a href="http://localhost:8080/">http://localhost:8080</a></p><h3>Option 2 — Cloud Server (AWS EC2 / DigitalOcean)</h3><p>Sure 👍<br>Here is the <strong>SHORT &amp; CLEAR version</strong>:</p><h3>Launch Server</h3><ul><li>Ubuntu 20.04 / 22.04</li><li>Open ports: <strong>22 (SSH), 8080 (Jenkins)</strong></li></ul><h3>SSH into Server</h3><pre>ssh -i key.pem ubuntu@SERVER_IP</pre><h3>Install Java (Required)</h3><pre>sudo apt update<br>sudo apt install -y openjdk-17-jdk</pre><h3>Add Jenkins Repo &amp; Key</h3><pre>wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -<br>sudo sh -c &#39;echo deb http://pkg.jenkins.io/debian/ stable main &gt; /etc/apt/sources.list.d/jenkins.list&#39;</pre><h3>Install &amp; Start Jenkins</h3><pre>sudo apt update<br>sudo apt install -y jenkins<br>sudo systemctl start jenkins<br>sudo systemctl enable jenkins</pre><h3>Open Jenkins in Browser</h3><pre>http://SERVER_IP:8080</pre><h3>Get Admin Password</h3><pre>sudo cat /var/lib/jenkins/secrets/initialAdminPassword</pre><p>Access Jenkins at:<br> http://&lt;your-server-ip&gt;:8080</p><h3>Managing Credentials (Secrets in Jenkins)</h3><p>Jenkins stores secrets in <strong>Credentials Manager</strong>.</p><h3>Steps:</h3><ol><li>Go to:<br> 🧭 <em>Dashboard → Manage Jenkins → Credentials → Global → Add Credentials</em></li><li>Choose:</li></ol><ul><li><strong>Secret Text</strong> (for API keys, tokens)</li><li><strong>SSH Username with private key</strong> (for server deploys)</li></ul><ol><li>Use it inside Jenkinsfile:</li></ol><ul><li>environment { AWS_KEY = credentials(&#39;aws-key&#39;) }</li></ul><p>Jenkins will inject these securely at runtime.</p><h3>Setting Up a Jenkins Job (with GitHub Integration)</h3><ol><li>Go to Jenkins Dashboard → “New Item”</li><li>Choose <strong>Pipeline</strong></li><li>Enter name → Select <em>Pipeline from SCM</em></li><li>Add your GitHub repo URL</li><li>Point to your <strong>Jenkinsfile</strong></li><li>Save &amp; click <strong>Build Now</strong></li></ol><p>Jenkins will clone your repo and run your pipeline!</p><h3>Deploying MERN Stack from Jenkins to a Server</h3><p>Typical Steps:</p><ol><li>Jenkins clones GitHub code</li><li>Runs backend tests</li><li>Builds frontend React app</li><li>SSH into EC2 or VPS</li><li>Pull latest code</li><li>Restart Node.js via PM2</li></ol><p>Same as CircleCI, but now <em>fully self-managed</em> on your Jenkins server.</p><h3>Jenkins Plugins You’ll Actually Use</h3><p>Plugin Purpose <br> <strong>Git Plugin</strong> Connect to GitHub/GitLab <br><strong>Docker Plugin</strong> Build &amp; run Docker containers <br><strong>SSH Agent Plugin</strong> Deploy via SSH <br><strong>JUnit Plugin</strong> Test report integration <br><strong>NodeJS Plugin</strong> Use Node in your builds <br><strong>Email-ext Plugin</strong> Send build notifications</p><p>You can install plugins from:<br> <strong>Manage Jenkins → Manage Plugins</strong></p><h3>Jenkins vs GitHub Actions vs CircleCI</h3><p>Jenkins = <em>Full control, self-hosted, complex pipelines</em></p><ul><li>GitHub Actions = <em>Beginner friendly, built-in to GitHub</em></li><li>CircleCI = <em>Fast, cloud-native, Docker-friendly</em></li></ul><h3>CI/CD Flow Example for MERN (Jenkins)</h3><pre>GitHub → Jenkins → EC2 Server → PM2 Restart</pre><h3>Flow</h3><ol><li>Developer pushes code</li><li>GitHub sends webhook → Jenkins job triggers</li><li>Jenkins</li></ol><ul><li>Pulls code</li><li>Installs dependencies</li><li>Builds React frontend</li><li>Runs tests</li><li>Deploys code via SSH</li><li>Restarts app</li></ul><ol><li>User sees updated app live 🚀</li></ol><h3>Example Folder Setup for MERN Project</h3><pre>/mern-app<br>  ├── client/       → React app<br>  ├── server/       → Express backend<br>  ├── Jenkinsfile   → CI/CD pipeline definition<br>  ├── package.json</pre><h3>Jenkins Pipeline Visualization</h3><p>Jenkins provides a <strong>Blue Ocean view</strong> plugin for visualizing your pipeline stages as a clean flowchart.</p><p>You’ll see:<br> ✅ Build → Test → Deploy<br> ✅ Each stage’s duration<br> ✅ Logs for each command</p><p>Install plugin:<br> <strong>Manage Jenkins → Plugins → Blue Ocean</strong></p><h3>GitHub Actions vs Jenkins vs CircleCI (Full Guide)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*B3iUoGKNP6nNglsEse3_7Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97c29e0a37f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NGINX Guide]]></title>
            <link>https://medium.com/@farihakausar18/nginx-guide-d61ad95c3bf4?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61ad95c3bf4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[ngnix]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 07:10:12 GMT</pubDate>
            <atom:updated>2026-01-19T07:10:12.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is NGINX? (Beginner)</h3><p><strong>NGINX (Engine-X)</strong> is a <strong>high-performance web server</strong> and <strong>reverse proxy</strong>.</p><h3>In simple words:</h3><blockquote><em>NGINX sits </em><strong><em>in front of your backend servers</em></strong><em> and controls </em><strong><em>traffic, security, and performance</em></strong><em>.</em></blockquote><h3>Common uses:</h3><ul><li>Serve websites</li><li>Forward requests to backend APIs</li><li>Load balancing</li><li>Caching</li><li>Security (SSL, rate-limit)</li></ul><h3>Why NGINX is so popular?</h3><p>✔ Very fast<br>✔ Handles thousands of requests<br>✔ Low memory usage<br>✔ Perfect for <strong>microservices &amp; Node.js</strong><br>✔ Used by Netflix, Uber, Airbnb, Cloudflare</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*8TtkFtyosvktXBYwqrdzCQ.png" /></figure><p>👉 <strong>Rule</strong>:</p><blockquote><em>NGINX = Traffic manager<br>Backend = Business logic</em></blockquote><h3>Where NGINX is used? (Real Architecture)</h3><pre>Client (Browser / Mobile)<br>        ↓<br>     NGINX<br>        ↓<br>Backend APIs (Node.js / Python / Java)<br>        ↓<br>    Database</pre><h3>Install NGINX (Basic)</h3><h3>Ubuntu</h3><pre>sudo apt update<br>sudo apt install nginx</pre><h3>Start / Stop</h3><pre>sudo systemctl start nginx<br>sudo systemctl stop nginx<br>sudo systemctl restart nginx</pre><h3>Check status</h3><pre>sudo systemctl status nginx</pre><h3>6️⃣ NGINX Important Files</h3><p>FilePurpose/etc/nginx/nginx.confMain config/etc/nginx/sites-available/Virtual hosts/etc/nginx/sites-enabled/Active sites/var/log/nginx/access.logRequests log/var/log/nginx/error.logErrors</p><h3>7️⃣ Serve a Static Website (Beginner)</h3><pre>server {<br>    listen 80;<br>    server_name example.com;</pre><pre>    root /var/www/html;<br>    index index.html;<br>}</pre><p>✔ Used for HTML / CSS / JS websites</p><h3>Reverse Proxy (MOST IMPORTANT)</h3><h3>Node.js API running on localhost:4000</h3><pre>server {<br>    listen 80;</pre><pre>    location / {<br>        proxy_pass <a href="http://localhost:4000;">http://localhost:4000;</a><br>    }<br>}</pre><h3>What happens?</h3><pre>Client → NGINX → Node.js API</pre><p>👉 Backend port is <strong>hidden</strong> (security)</p><h3>Microservices Routing (Very Common)</h3><h3>Example:</h3><ul><li>Auth service → 4001</li><li>Product service → 4003</li><li>Order service → 4004</li></ul><pre>server {<br>    listen 80;</pre><pre>    location /auth/ {<br>        proxy_pass <a href="http://localhost:4001/;">http://localhost:4001/;</a><br>    }</pre><pre>    location /products/ {<br>        proxy_pass <a href="http://localhost:4003/;">http://localhost:4003/;</a><br>    }</pre><pre>    location /orders/ {<br>        proxy_pass <a href="http://localhost:4004/;">http://localhost:4004/;</a><br>    }<br>}</pre><h3>API calls:</h3><pre>/auth/login<br>/products/list<br>/orders/create</pre><h3>Load Balancing (Intermediate)</h3><h3>Multiple backend servers</h3><pre>upstream product_service {<br>    server 10.0.0.1:4003;<br>    server 10.0.0.2:4003;<br>}</pre><pre>server {<br>    listen 80;</pre><pre>    location /products/ {<br>        proxy_pass <a href="http://product_service;/">http://product_service;</a><br>    }<br>}</pre><p>✔ Auto distributes traffic<br>✔ High availability</p><h3>SSL / HTTPS (Very Important)</h3><pre>server {<br>    listen 443 ssl;<br>    server_name example.com;</pre><pre>    ssl_certificate /etc/ssl/cert.pem;<br>    ssl_certificate_key /etc/ssl/key.pem;</pre><pre>    location / {<br>        proxy_pass <a href="http://localhost:4000;">http://localhost:4000;</a><br>    }<br>}</pre><p>👉 HTTPS is handled by <strong>NGINX</strong>, not Node.js</p><h3>Redirect HTTP → HTTPS</h3><pre>server {<br>    listen 80;<br>    return 301 https://$host$request_uri;<br>}</pre><h3>Rate Limiting (Security)</h3><pre>limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;</pre><pre>server {<br>    location /api/ {<br>        limit_req zone=api burst=10;<br>        proxy_pass <a href="http://localhost:4000;">http://localhost:4000;</a><br>    }<br>}</pre><p>✔ Prevents <strong>DDoS &amp; brute-force attacks</strong></p><h3>Caching (Performance Boost)</h3><pre>proxy_cache_path /tmp/cache levels=1:2 keys_zone=my_cache:10m;</pre><pre>server {<br>    location / {<br>        proxy_cache my_cache;<br>        proxy_pass <a href="http://localhost:4000;">http://localhost:4000;</a><br>    }<br>}</pre><p>✔ Faster responses<br>✔ Less backend load</p><h3>WebSockets Support</h3><pre>location /socket/ {<br>    proxy_pass http://localhost:4000;<br>    proxy_http_version 1.1;<br>    proxy_set_header Upgrade $http_upgrade;<br>    proxy_set_header Connection &quot;upgrade&quot;;<br>}</pre><p>✔ Used in <strong>chat apps, real-time dashboards</strong></p><h3>Docker + NGINX (Advanced)</h3><pre>FROM nginx:alpine<br>COPY nginx.conf /etc/nginx/nginx.conf</pre><p>✔ Very common in <strong>Kubernetes &amp; Microservices</strong></p><h3>NGINX in Production (Real Use)</h3><p>✔ API Gateway<br>✔ Reverse Proxy<br>✔ Load Balancer<br>✔ SSL Manager<br>✔ DDoS Protection<br>✔ Static content server</p><h3>NGINX vs API Gateway</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*Kr9GsabT-Ieh_UHuz-1ZUA.png" /></figure><h3>Common Interview Questions</h3><p>✔ Difference between reverse proxy &amp; forward proxy<br>✔ How NGINX load balancing works<br>✔ How to secure APIs using NGINX<br>✔ Why NGINX is better than Apache<br>✔ NGINX in microservices architecture</p><h3>Final Summary</h3><p><strong>Beginner</strong>: Static site, reverse proxy<br><strong>Intermediate</strong>: Load balancing, SSL, routing<br> <strong>Advanced</strong>: Rate limiting, caching, WebSockets, Docker, Kubernetes</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61ad95c3bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices Architecture]]></title>
            <link>https://medium.com/@farihakausar18/microservices-architecture-8fdd59652b8f?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fdd59652b8f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[miscroservices]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[fastify]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Fri, 16 Jan 2026 07:15:09 GMT</pubDate>
            <atom:updated>2026-01-16T07:15:09.980Z</atom:updated>
            <content:encoded><![CDATA[<h3>First: The Basic Idea (Very Simple)</h3><h3>Think of a Restaurant</h3><p>Instead of <strong>one person</strong> doing everything:</p><ul><li>cooking</li><li>taking orders</li><li>billing</li></ul><p>You have <strong>different people</strong>, each with <strong>one job</strong>.</p><p>👉 <strong>Microservices = Same idea for software</strong></p><h3>🧱 Monolithic vs Microservices (Plain English)</h3><h3>❌ Monolithic (Old Way)</h3><pre>ONE BIG BACKEND</pre><ul><li>Login</li><li>Users</li><li>Orders</li><li>Payments</li><li>Emails</li></ul><p>👉 All inside <strong>one single app</strong></p><h3>Problem:</h3><ul><li>If <strong>one thing breaks</strong>, whole app can break</li><li>Hard to change</li><li>Hard to scale</li></ul><h3>✅ Microservices (New Way)</h3><pre>SMALL APPS WORKING TOGETHER</pre><p>Each small app does <strong>one job only</strong></p><h3>VERY IMPORTANT RULE</h3><h3>One Service = One Responsibility</h3><ul><li>Auth service ❌ should NOT handle orders</li><li>Order service ❌ should NOT handle login</li></ul><h3>How Users Talk to Services (API Gateway)</h3><p>User <strong>never talks directly</strong> to services.</p><pre>User<br> ↓<br>API Gateway (Gatekeeper)<br> ↓<br>Correct Service</pre><p>I’ll explain <strong>API Gateway</strong> and <strong>How services talk to each other</strong> in the <strong>most beginner-friendly way</strong>, using <strong>real-life examples</strong>, <strong>simple words</strong>, and <strong>step-by-step flow</strong>.</p><h3>What is an API Gateway? (Very Simple)</h3><h3>Think of a Security Gate at a Society / Office</h3><ul><li>Visitors ❌ don’t go directly to each house</li><li>They first stop at <strong>ONE gate</strong></li><li>The gate:</li><li>Checks identity</li><li>Decides where to send them</li></ul><p>👉 <strong>API Gateway = ONE entry point for your backend</strong></p><h3>🧠 Without API Gateway (Bad)</h3><pre>Frontend → Auth Service<br>Frontend → User Service<br>Frontend → Order Service<br>Frontend → Payment Service</pre><p>❌ Too many URLs<br>❌ Security risk<br>❌ Hard to manage</p><h3>✅ With API Gateway (Good)</h3><pre>Frontend<br>   ↓<br>API Gateway<br>   ↓<br>Auth / User / Order / Payment Services</pre><p>✔ Clean<br>✔ Secure<br>✔ Easy to manage</p><h3>🧩 What Does API Gateway Do?</h3><h3>1️⃣ Authentication &amp; Security 🔐</h3><ul><li>Checks <strong>JWT token</strong></li><li>Blocks unauthorized users</li></ul><h3>2️⃣ Routing 🧭</h3><ul><li>Decides <strong>which service</strong> should handle request</li></ul><p>Example:</p><pre>/login  → Auth Service<br>/orders → Order Service<br>/users  → User Service</pre><h3>3️⃣ Rate Limiting 🚦</h3><ul><li>Stops too many requests</li><li>Prevents hacking</li></ul><h3>4️⃣ Logging &amp; Monitoring 📊</h3><ul><li>Logs all requests</li><li>Tracks errors</li></ul><h3>Simple Example (API Gateway)</h3><p>User hits:</p><pre>POST /orders</pre><p>API Gateway:</p><ol><li>Checks token</li><li>Sends request → Order Service</li><li>Returns response to user</li></ol><p>User never knows <strong>which service handled it</strong></p><h3>Real-Life Example (Complete Flow)</h3><h3>User Places Order</h3><p>1️⃣ User → API Gateway<br>2️⃣ Gateway → Order Service<br>3️⃣ Order created<br>4️⃣ Order Service publishes event → “ORDER_CREATED”<br>5️⃣ Payment Service receives event<br>6️⃣ Notification Service sends email</p><h3>🧠 When to Use Which?</h3><p>Situation UseSimple app REST<br>Large system Event-driven<br>Payments Event-driven User login REST</p><h3>🟢 One-Line Summary</h3><h3>API Gateway:</h3><blockquote><strong><em>One door for all users</em></strong></blockquote><h3>Service Communication:</h3><blockquote><strong><em>Services talk via calls or messages</em></strong></blockquote><h3>🔚 Super Simple Diagram</h3><pre>User<br> ↓<br>API Gateway<br> ↓<br>Order Service → Message Broker → Payment Service<br>                           → Notification Service</pre><h3>🔄 How Services Talk to Each Other</h3><h3>Two Ways (Simple)</h3><h3>1️⃣ Direct Talking (REST API)</h3><p>Like calling someone on phone 📞</p><pre>Order Service → Payment Service</pre><p>✔ Simple<br>❌ Tight connection (bad for big systems)</p><h3>2️⃣ Event Messaging (Recommended) ⭐</h3><p>Like sending a <strong>WhatsApp message</strong> 📩</p><pre>Order Created → Message Broker → Payment Service</pre><p>Order service says:</p><blockquote><em>“Order created!”</em></blockquote><p>Other services listen and react.</p><h3>📬 Message Broker (Middle Man)</h3><p>This is like a <strong>Post Office</strong></p><p>Tool</p><p>Kafka , Rabbit, MQAWS, SQS</p><p>Services:</p><ul><li><strong>Send message</strong></li><li><strong>Receive message</strong></li><li>Don’t know each other directly</li></ul><p>✔ More reliable<br>✔ Better scaling</p><h3>🗄️ Database Rule (VERY IMPORTANT)</h3><p>❌ <strong>NO SHARED DATABASE</strong></p><p>Each service has its <strong>own database</strong></p><p>👉 Why?</p><ul><li>Safe</li><li>Independent</li><li>No breaking others</li><li>Great question 👍<br>I’ll teach you <strong>Kafka, RabbitMQ, AWS SQS, and Fastify</strong> from <strong>ZERO → ADVANCED</strong>, in a <strong>learning-friendly way</strong>, with <strong>theory + mental models + code</strong>, exactly how a beginner should learn.</li></ul><h3>PART 1: FIRST UNDERSTAND THE BIG PICTURE</h3><h3>Why do we need Kafka / RabbitMQ / SQS?</h3><p>In microservices:</p><ul><li>Services should <strong>not depend directly</strong> on each other</li><li>If one service is down, the system should <strong>still work</strong></li></ul><p>👉 Solution: <strong>Message Queues / Event Streaming</strong></p><h3>WHAT IS A MESSAGE QUEUE? (VERY SIMPLE)</h3><p>Think of <strong>Courier Service 📦</strong></p><ul><li>Sender drops parcel</li><li>Receiver picks it later</li><li>Sender &amp; receiver don’t need to meet</li></ul><pre>Service A → Queue → Service B</pre><p>✔ Reliable<br>✔ Scalable<br>✔ Decoupled</p><h3>🔄 TYPES OF COMMUNICATION</h3><p>Type<br>REST API Phone call 📞<br>Message QueueLetter / WhatsApp 📩</p><h3>PART 2: KAFKA (BIG DATA / HIGH SCALE)</h3><h3>🔹 What is Kafka?</h3><p>Kafka is an <strong>event streaming platform</strong></p><blockquote><em>Kafka is used when you have </em><strong><em>millions of events per second</em></strong></blockquote><h3>Real-Life Example</h3><p>Like <strong>YouTube Activity Log</strong></p><ul><li>Video watched</li><li>Video liked</li><li>Video shared</li></ul><p>These events are <strong>never deleted</strong></p><h3>Mental Model</h3><p>Kafka is like a <strong>permanent activity log</strong></p><ul><li>Nothing is deleted</li><li>You can replay history</li><li>Kafka Core Concepts</li></ul><h3>1️⃣ Producer</h3><ul><li>Sends messages</li></ul><h3>2️⃣ Consumer</h3><ul><li>Reads messages</li></ul><h3>3️⃣ Topic</h3><ul><li>Category of messages</li></ul><pre>order-created-topic</pre><h3>4️⃣ Partition</h3><ul><li>Splits data for speed</li></ul><h3>5️⃣ Broker</h3><ul><li>Kafka server</li></ul><h3>Kafka Architecture</h3><pre>Producer → Topic → Partition → Consumer</pre><p>✔ Super fast<br>✔ Durable<br>✔ Replay messages</p><h3>Kafka is NOT for:</h3><ul><li>Simple apps</li><li>Small systems</li><li>Easy setup</li></ul><h3>Kafka Use Cases</h3><ul><li>Analytics</li><li>Logs</li><li>Real-time dashboards</li><li>Event sourcing</li></ul><h3>Kafka Node.js Example (Basic)</h3><pre>import { Kafka } from &quot;kafkajs&quot;;</pre><pre>const kafka = new Kafka({<br>  clientId: &quot;order-service&quot;,<br>  brokers: [&quot;localhost:9092&quot;],<br>});</pre><pre>const producer = kafka.producer();</pre><pre>await producer.connect();<br>await producer.send({<br>  topic: &quot;order-created&quot;,<br>  messages: [{ value: JSON.stringify({ orderId: 1 }) }],<br>});</pre><h3>PART 3: RABBITMQ (RELIABLE TASK QUEUE)</h3><h3>🔹 What is RabbitMQ?</h3><p>RabbitMQ is a <strong>message broker</strong></p><blockquote><em>Best for </em><strong><em>background jobs &amp; task processing</em></strong></blockquote><h3>Real-Life Example</h3><p>Like <strong>Customer Support Tickets</strong></p><ul><li>Ticket enters system</li><li>Agents pick one-by-one</li></ul><h3>RabbitMQ Concepts</h3><h3>1️⃣ Producer</h3><p>Sends message</p><h3>2️⃣ Queue</h3><p>Stores messages</p><h3>3️⃣ Consumer</h3><p>Processes message</p><h3>4️⃣ Exchange</h3><p>Decides where message goes</p><h3>🔁 RabbitMQ Flow</h3><pre>Producer → Exchange → Queue → Consumer</pre><p>✔ Reliable<br>✔ Acknowledgment support<br>✔ Retry &amp; Dead-letter queues</p><h3>🟢 RabbitMQ Use Cases</h3><ul><li>Email sending</li><li>Payment processing</li><li>Background jobs</li><li>Image processing</li></ul><h3>RabbitMQ Flow</h3><pre>Producer → Exchange → Queue → Consumer</pre><h3>RabbitMQ Node.js Example</h3><h3>Producer</h3><pre>import amqp from &#39;amqplib&#39;;</pre><pre>const conn = await amqp.connect(&#39;amqp://localhost&#39;);<br>const channel = await conn.createChannel();</pre><pre>await channel.assertQueue(&#39;email_queue&#39;);</pre><pre>channel.sendToQueue(<br>  &#39;email_queue&#39;,<br>  Buffer.from(&#39;Send welcome email&#39;)<br>);</pre><h3>Explanation</h3><ul><li>Connect to RabbitMQ</li><li>Create channel</li><li>Create queue</li><li>Send message</li></ul><h3>Consumer</h3><pre>channel.consume(&#39;email_queue&#39;, msg =&gt; {<br>  console.log(msg.content.toString());<br>  channel.ack(msg);<br>});</pre><p>👉 ack means “task done”</p><h3>RabbitMQ Use Cases</h3><ul><li>Emails</li><li>Payments</li><li>Image processing</li><li>Background jobs</li></ul><h3>PART 4: AWS SQS (CLOUD MANAGED QUEUE)</h3><h3>🔹 What is AWS SQS?</h3><p>SQS is <strong>Amazon’s fully managed queue</strong></p><blockquote><em>You don’t manage servers</em></blockquote><h3>Real-Life Example</h3><p>Like <strong>Uber Ride Requests</strong></p><ul><li>Requests stored safely</li><li>Drivers pick them</li></ul><h3>SQS Types</h3><h3>1️⃣ Standard Queue</h3><ul><li>Very fast</li><li>Messages may be duplicated</li></ul><h3>2️⃣ FIFO Queue</h3><ul><li>Exact order</li><li>No duplicates</li></ul><h3>SQS Use Cases</h3><ul><li>Serverless apps</li><li>AWS-based systems</li><li>Simple queues</li></ul><h3>AWS SQS Node.js Example</h3><pre>import { SQSClient, SendMessageCommand } from &quot;@aws-sdk/client-sqs&quot;;</pre><pre>const client = new SQSClient({ region: &quot;us-east-1&quot; });</pre><pre>await client.send(<br>  new SendMessageCommand({<br>    QueueUrl: &quot;QUEUE_URL&quot;,<br>    MessageBody: JSON.stringify({ task: &quot;process_order&quot; }),<br>  })<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*yxd5v9V1NPT_L97p2NYk2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vzldGNmUja9A7j9Q0VxKQ.png" /></figure><h3>PART 5: FASTIFY (Node.js Framework)</h3><h3>🔹 What is Fastify?</h3><p>Fastify is a <strong>high-performance Node.js backend framework</strong></p><blockquote><em>Faster &amp; safer than Express</em></blockquote><h3>Why Fastify?</h3><p>✔ Very fast<br>✔ Built-in validation<br>✔ Plugin system<br>✔ Async-friendly</p><h3>Fastify vs Express</h3><p>FeatureFastifyExpressSpeedFasterSlowerValidationBuilt-inManualPluginsStrongWeakTypeScriptExcellentOK</p><h3>Fastify Basic Structure</h3><pre>src/<br> ├── routes/<br> ├── plugins/<br> ├── services/<br> └── server.js</pre><h3>Fastify Beginner Example</h3><pre>import Fastify from &quot;fastify&quot;;</pre><pre>const app = Fastify();</pre><pre>app.get(&quot;/ping&quot;, async () =&gt; {<br>  return { message: &quot;pong&quot; };<br>});</pre><pre>app.listen({ port: 3000 });</pre><h3>Request Validation (Fastify Superpower)</h3><pre>app.post(&quot;/user&quot;, {<br>  schema: {<br>    body: {<br>      type: &quot;object&quot;,<br>      required: [&quot;name&quot;],<br>      properties: {<br>        name: { type: &quot;string&quot; },<br>      },<br>    },<br>  },<br>}, async (req) =&gt; {<br>  return { success: true };<br>});</pre><h3>Advanced Fastify Topics</h3><ul><li>Plugins</li><li>Hooks</li><li>Decorators</li><li>JWT Auth</li><li>API Gateway usage</li><li>Microservices integration</li></ul><h3>HOW EVERYTHING CONNECTS (FINAL VIEW)</h3><pre>Client<br> ↓<br>Fastify API Gateway<br> ↓<br>Order Service (Fastify)<br> ↓<br>RabbitMQ / Kafka / SQS<br> ↓<br>Payment Service</pre><h3>NGINX (Reverse Proxy &amp; Load Balancer)</h3><h3>What is NGINX?</h3><p>NGINX is <strong>NOT Node.js</strong></p><p>NGINX is:</p><ul><li>Reverse Proxy</li><li>Load Balancer</li><li>Web Server</li></ul><blockquote><em>Think of NGINX as a </em><strong><em>traffic police officer</em></strong><em> 🚦</em></blockquote><h3>Mental Model</h3><pre>Client → NGINX → Backend Services</pre><p>NGINX:</p><ul><li>Controls traffic</li><li>Protects services</li><li>Improves performance</li></ul><h3>Why Use NGINX?</h3><ul><li>High performance</li><li>Handles thousands of requests</li><li>SSL / HTTPS</li><li>Load balancing</li><li>API Gateway alternative</li></ul><h3>NGINX as Reverse Proxy</h3><h3>NGINX Config</h3><pre>server {<br>  listen 80;</pre><pre>  location /api/ {<br>    proxy_pass <a href="http://localhost:3000;">http://localhost:3000;</a><br>  }<br>}</pre><h3>Explanation</h3><pre>listen 80;</pre><p>👉 Listen on port 80 (HTTP)</p><pre>location /api/ {</pre><p>👉 Match /api requests</p><pre>proxy_pass http://localhost:3000;</pre><p>👉 Forward to Fastify backend</p><h3>🔹 NGINX Load Balancing</h3><pre>upstream backend {<br>  server localhost:3001;<br>  server localhost:3002;<br>}</pre><pre>server {<br>  location / {<br>    proxy_pass <a href="http://backend;/">http://backend;</a><br>  }<br>}</pre><p>👉 Distributes traffic across services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*23iiW5XeiZeoRZt4WNT_vA.png" /></figure><p>👉 <strong>Use both together</strong></p><h3>HOW ALL FIT TOGETHER (FINAL)</h3><pre>Client<br> ↓<br>NGINX (Traffic / SSL)<br> ↓<br>Fastify API Gateway<br> ↓<br>Microservices<br> ↓<br>RabbitMQ / Kafka</pre><p>FIRST BIG CONFUSION TO CLEAR</p><p><em>axios.get(&#39;http://product-service:4003/products&#39;)<br>Is this a deployment endpoint?<br>How does this work after deployment?</em></p><h3>Short answer (important):</h3><p>❌ <strong>NO — this is NOT a public deployment URL</strong><br>✅ This is an <strong>internal service-to-service address</strong></p><p>Now let’s explain <strong>properly</strong>.</p><h3>PART 1: INTERNAL vs EXTERNAL URLs (VERY IMPORTANT CONCEPT)</h3><h3>🔹 External URL (Client-facing)</h3><p>This is what:</p><ul><li>Browser</li><li>Mobile app</li><li>Postman<br>uses</li></ul><p>Example:</p><pre>https://api.myshop.com/products</pre><p>Client <strong>ONLY talks to this</strong>.</p><h3>Internal URL (Service-to-service)</h3><p>This is what:</p><ul><li>API Gateway</li><li>Other microservices<br>use <strong>inside the backend network</strong></li></ul><p>Example:</p><pre>http://product-service:4003/products</pre><p>🚫 Client can NEVER access this.</p><h3>WHAT HAPPENS IN REAL DEPLOYMENT?</h3><p>Let’s say you deploy on AWS / DigitalOcean.</p><h3>🌐 PUBLIC FLOW (REAL LIFE)</h3><pre>Browser / Mobile<br>   ↓<br>https://api.myshop.com<br>   ↓<br>NGINX<br>   ↓<br>API Gateway<br>   ↓<br>Product Service (internal)</pre><h3>📌 VERY IMPORTANT RULE</h3><p>🚫 <strong>NEVER expose microservices directly</strong><br>✅ <strong>ONLY API Gateway is public</strong></p><h3>SO WHAT SHOULD AXIOS URL BE?</h3><h3>✅ INSIDE API GATEWAY (INTERNAL)</h3><pre>axios.get(&#39;http://product-service:4003/products&#39;)</pre><h3>✅ FROM CLIENT (PUBLIC)</h3><pre>fetch(&#39;https://api.myshop.com/products&#39;)</pre><p>They are <strong>NOT the same</strong>.</p><h3>WHERE NGINX FITS (BEGINNER VIEW)</h3><p>Think of NGINX as:</p><p>🚓 <strong>Traffic Police + Security Guard</strong></p><p>NGINX sits <strong>before</strong> API Gateway.</p><h3>ARCHITECTURE WITH NGINX</h3><pre>Internet<br>   ↓<br>NGINX (SSL, security, rate-limit)<br>   ↓<br>API Gateway (routing, auth)<br>   ↓<br>Microservices</pre><h3>NGINX — BEGINNER LEVEL</h3><h3>What NGINX does (basic):</h3><ul><li>Accepts HTTP requests</li><li>Forwards requests</li><li>Serves as entry point</li></ul><h3>Example beginner config:</h3><pre>server {<br>  listen 80;<br><br>  location / {<br>    proxy_pass http://api-gateway:3000;<br>  }<br>}</pre><p>Meaning:</p><ul><li>All traffic → API Gateway</li></ul><h3>TERM: Reverse Proxy</h3><p>NGINX receives request and forwards it to backend.</p><h3>NGINX — INTERMEDIATE LEVEL</h3><h3>HTTPS (SSL)</h3><p>NGINX handles SSL so backend stays simple.</p><pre>server {<br>  listen 443 ssl;<br>  ssl_certificate cert.pem;<br>  ssl_certificate_key key.pem;<br>}</pre><h3>Rate Limiting</h3><p>Protect from abuse.</p><pre>limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;</pre><h3>TERM: Rate Limiting</h3><p>Limit how many requests a user can make.</p><h3>NGINX — ADVANCED LEVEL (MICROSERVICES)</h3><h3>Path-based Routing</h3><p>NGINX routes to different gateways/services.</p><pre>location /api/ {<br>  proxy_pass http://api-gateway:3000;<br>}<br><br>location /admin/ {<br>  proxy_pass http://admin-gateway:3001;<br>}</pre><h3>Load Balancing</h3><p>Multiple API Gateways.</p><pre>upstream gateway {<br>  server api-gateway-1:3000;<br>  server api-gateway-2:3000;<br>}<br><br>server {<br>  location / {<br>    proxy_pass http://gateway;<br>  }<br>}</pre><p>NGINX spreads traffic.</p><h3>TERM: Load Balancer</h3><p>Distributes traffic to multiple servers.</p><h3>NGINX IN MICROSERVICES (REAL USE CASES)</h3><p>NGINX is used for:</p><p>✅ SSL termination<br>✅ Load balancing<br>✅ Rate limiting<br>✅ IP blocking<br>✅ Static file serving<br>✅ API version routing</p><h3>FINAL CLARITY (VERY IMPORTANT)</h3><h3>Why not call services directly?</h3><p>Because:</p><ul><li>Security risk</li><li>Hard to change</li><li>No control</li><li>No auth</li></ul><h3>✅ Correct Practice</h3><ul><li>Client → NGINX → API Gateway</li><li>Gateway → Services (internal URLs)</li></ul><h3>ONE-LINE SUMMARY</h3><blockquote><strong><em>product-service:4003 is an internal address only visible inside Docker/Kubernetes, while NGINX + API Gateway expose a single public URL to the outside world.</em></strong></blockquote><h3>COMPLETE E‑COMMERCE BACKEND (NODE.JS MICROservices)</h3><p>This is a <strong>FULL BACKEND BLUEPRINT + REAL CODE STARTER</strong> for an <strong>E‑commerce system</strong>, designed <strong>from ZERO → PRODUCTION‑READY thinking</strong>.</p><p>⚠️ Important honesty (mentor note):<br>A <em>100% enterprise‑scale ecommerce</em> takes <strong>thousands of lines</strong> and weeks. What you get here is:</p><p>✅ Correct architecture<br>✅ All core services<br>✅ Real models, APIs, flows<br>✅ Clean, extendable code<br>✅ Industry‑approved patterns</p><p>You can <strong>build on this safely</strong>.</p><h3>ARCHITECTURE OVERVIEW</h3><pre>Client (Web / Mobile)<br>   ↓<br>NGINX<br>   ↓<br>API Gateway (Fastify)<br>   ↓<br>------------------------------------------------<br>| Auth | User | Product | Order | Payment |<br>------------------------------------------------<br>   ↓                     ↓<br> Kafka (Events)       RabbitMQ (Jobs)<br>   ↓                     ↓<br> Notification Service (Email / SMS)</pre><h3>ROOT FOLDER STRUCTURE</h3><pre>ecommerce-backend/<br> ├── api-gateway/<br> ├── auth-service/<br> ├── user-service/<br> ├── product-service/<br> ├── order-service/<br> ├── payment-service/<br> ├── notification-service/<br> ├── docker-compose.yml<br> └── README.md</pre><p>Each folder = <strong>independent backend</strong></p><h3>API GATEWAY (FASTIFY)</h3><h3>Purpose</h3><ul><li>Single entry point</li><li>JWT validation</li><li>Route requests</li></ul><h3>api-gateway/src</h3><pre>server.js<br>routes.js<br>jwt.js</pre><h3>server.js</h3><pre>import Fastify from &#39;fastify&#39;;<br>import routes from &#39;./routes.js&#39;;</pre><pre>const app = Fastify();<br>app.register(routes);</pre><pre>app.listen({ port: 3000 });</pre><h3>routes.js</h3><pre>import axios from &#39;axios&#39;;</pre><pre>export default async function (app) {<br>  app.post(&#39;/auth/login&#39;, req =&gt; axios.post(&#39;http://auth-service:4001/login&#39;, req.body).then(r =&gt; r.data));<br>  app.post(&#39;/users&#39;, req =&gt; axios.post(&#39;http://user-service:4002/users&#39;, req.body).then(r =&gt; r.data));<br>  app.get(&#39;/products&#39;, () =&gt; axios.get(&#39;http://product-service:4003/products&#39;).then(r =&gt; r.data));<br>  app.post(&#39;/orders&#39;, req =&gt; axios.post(&#39;http://order-service:4004/orders&#39;, req.body).then(r =&gt; r.data));<br>}</pre><h3><strong>Axios</strong><br> Used to call <strong>other services</strong> (internal phone calls).</h3><p>app.get(‘/products’, () =&gt;<br> axios.get(‘<a href="http://product-service:4003/products&#39;">http://product-service:4003/products&#39;</a>)<br>);<br>Meaning:</p><ul><li>User calls /products</li><li>Gateway forwards request to <strong>Product Service</strong></li><li>Gateway returns response</li></ul><p>👉 Client never knows Product Service exists.</p><h3>AUTH SERVICE (JWT + KAFKA EVENT)</h3><h3>auth-service/src</h3><pre>server.js<br>kafka.js<br>user.model.js</pre><h3>user.model.js (Mongoose)</h3><pre>import mongoose from &#39;mongoose&#39;;</pre><pre>export default mongoose.model(&#39;AuthUser&#39;, new mongoose.Schema({<br>  email: String,<br>  password: String<br>}));</pre><h3>kafka.js</h3><pre>import { Kafka } from &#39;kafkajs&#39;;<br>export const kafka = new Kafka({ clientId: &#39;auth&#39;, brokers: [&#39;kafka:9092&#39;] });<br>export const producer = kafka.producer();</pre><p><strong>Producer</strong><br> A service that <strong>sends events</strong>.</p><h3>TERM: Event</h3><p>An <strong>event</strong> = “Something happened”</p><p>Example:</p><ul><li>USER_CREATED</li><li>ORDER_PLACED</li></ul><h3>server.js</h3><pre>import Fastify from &#39;fastify&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import User from &#39;./user.model.js&#39;;<br>import { producer } from &#39;./kafka.js&#39;;</pre><pre>const app = Fastify();<br>await mongoose.connect(&#39;mongodb://mongo/auth&#39;);<br>await producer.connect();</pre><pre>app.post(&#39;/login&#39;, async req =&gt; {<br>  const user = await User.create(req.body);<br>  await producer.send({ topic: &#39;USER_CREATED&#39;, messages: [{ value: JSON.stringify(user) }] });<br>  return { token: &#39;jwt-token&#39;, user };<br>});</pre><pre>app.listen({ port: 4001 });</pre><p>Story:<br> Auth Service shouts:<br> 📣 “A USER WAS CREATED!”</p><p>Kafka remembers it.</p><h3>USER SERVICE</h3><h3>user-service/src</h3><pre>server.js<br>user.model.js<br>kafka.consumer.js</pre><h3>user.model.js</h3><pre>import mongoose from &#39;mongoose&#39;;<br>export default mongoose.model(&#39;User&#39;, new mongoose.Schema({<br>  email: String,<br>  name: String<br>}));</pre><h3>kafka.consumer.js</h3><pre>import { Kafka } from &#39;kafkajs&#39;;<br>const kafka = new Kafka({ clientId: &#39;user&#39;, brokers: [&#39;kafka:9092&#39;] });<br>const consumer = kafka.consumer({ groupId: &#39;user-group&#39; });<br><br>Consumer<br>A service that listens to events.</pre><pre>export async function start() {<br>  await consumer.connect();<br>  await consumer.subscribe({ topic: &#39;USER_CREATED&#39; });<br>  await consumer.run({ eachMessage: async ({ message }) =&gt; console.log(message.value.toString()) });<br>}</pre><blockquote>consumer.subscribe({ topic: ‘USER_CREATED’ });</blockquote><blockquote><em>“I want to hear USER_CREATED events”</em></blockquote><h3>PRODUCT SERVICE</h3><h3>product-service/src</h3><pre>server.js<br>product.model.js</pre><h3>product.model.js</h3><pre>import mongoose from &#39;mongoose&#39;;<br>export default mongoose.model(&#39;Product&#39;, new mongoose.Schema({<br>  name: String,<br>  price: Number,<br>  stock: Number<br>}));</pre><h3>server.js</h3><pre>import Fastify from &#39;fastify&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import Product from &#39;./product.model.js&#39;;</pre><pre>const app = Fastify();<br>await mongoose.connect(&#39;mongodb://mongo/products&#39;);</pre><pre>app.get(&#39;/products&#39;, async () =&gt; Product.find());<br>app.post(&#39;/products&#39;, req =&gt; Product.create(req.body));</pre><pre>app.listen({ port: 4003 });</pre><h3>ORDER SERVICE (KAFKA + RABBITMQ)</h3><h3>order-service/src</h3><pre>server.js<br>order.model.js<br>rabbit.js</pre><h3>order.model.js</h3><pre>import mongoose from &#39;mongoose&#39;;<br>export default mongoose.model(&#39;Order&#39;, new mongoose.Schema({<br>  userId: String,<br>  products: Array,<br>  total: Number<br>}));</pre><h3>rabbit.js</h3><pre>import amqp from &#39;amqplib&#39;;<br>export async function sendEmail(msg) {<br>  const conn = await amqp.connect(&#39;amqp://rabbitmq&#39;);<br>  const ch = await conn.createChannel();<br>  await ch.assertQueue(&#39;emails&#39;);<br>  ch.sendToQueue(&#39;emails&#39;, Buffer.from(msg));<br>}</pre><h3>server.js</h3><pre>import Fastify from &#39;fastify&#39;;<br>import mongoose from &#39;mongoose&#39;;<br>import Order from &#39;./order.model.js&#39;;<br>import { sendEmail } from &#39;./rabbit.js&#39;;</pre><pre>const app = Fastify();<br>await mongoose.connect(&#39;mongodb://mongo/orders&#39;);</pre><pre>app.post(&#39;/orders&#39;, async req =&gt; {<br>  const order = await Order.create(req.body);<br>  await sendEmail(&#39;Order placed&#39;);<br>  return order;<br>});</pre><pre>app.listen({ port: 4004 });</pre><h3>NOTIFICATION SERVICE (RABBITMQ)</h3><h3>notification-service/src/worker.js</h3><pre>import amqp from &#39;amqplib&#39;;<br>const conn = await amqp.connect(&#39;amqp://rabbitmq&#39;);<br>const ch = await conn.createChannel();<br>await ch.assertQueue(&#39;emails&#39;);<br>ch.consume(&#39;emails&#39;, msg =&gt; {<br>  console.log(&#39;EMAIL:&#39;, msg.content.toString());<br>  ch.ack(msg);<br>});</pre><h3>docker-compose.yml (SIMPLIFIED)</h3><pre>version: &#39;3&#39;<br>services:<br>  api-gateway:<br>    build: ./api-gateway<br>    ports: [&quot;3000:3000&quot;]</pre><pre>  auth-service: { build: ./auth-service }<br>  user-service: { build: ./user-service }<br>  product-service: { build: ./product-service }<br>  order-service: { build: ./order-service }<br>  notification-service: { build: ./notification-service }</pre><pre>  mongo: { image: mongo }<br>  rabbitmq: { image: rabbitmq:3-management }<br>  kafka: { image: bitnami/kafka }</pre><h3>Perfect 👍<br>I’ll explain the <strong>entire microservices e-commerce backend</strong> as a <strong>simple story</strong>, like a movie 🎬<br>No code stress, no buzzwords — just <strong>clear understanding</strong>.</h3><h3>THE STORY OF AN E-COMMERCE SYSTEM</h3><p><em>(Microservices explained like real life)</em></p><h3>Chapter 1: The Online Mall Is Born</h3><p>Imagine you are building a <strong>huge online mall</strong>.</p><p>Customers come to:</p><ul><li>Browse products</li><li>Create accounts</li><li>Place orders</li><li>Pay money</li><li>Get emails &amp; notifications</li></ul><p>At first, you think:</p><blockquote><em>“Let’s put everything in ONE big backend.</em></blockquote><p>But soon…</p><ul><li>Code becomes messy 😵</li><li>One bug breaks everything 💥</li><li>Scaling is impossible 📉</li></ul><p>So you decide to build <strong>a city instead of one building</strong>.</p><p>That city is called <strong>Microservices Architecture</strong> 🏙️</p><h3>Chapter 2: The Main Gate (API Gateway)</h3><p>Your mall has <strong>ONE main gate</strong>.</p><p>No one can enter directly.</p><p>This gate is called:</p><h3>👉 API Gateway</h3><p><strong>What does it do?</strong></p><ul><li>Checks who you are (JWT later)</li><li>Decides <em>where</em> to send you</li><li>Protects internal services</li></ul><p>🧠 Think of it as:</p><blockquote><em>“Reception desk of the mall”</em></blockquote><p>📌 Example:</p><ul><li>Customer says: “I want products”</li><li>Gate sends them to <strong>Product Service</strong></li><li>Customer says: “I want to place order”</li><li>Gate sends them to <strong>Order Service</strong></li></ul><p>The customer never sees internal services.</p><h3>Chapter 3: The Security Office (Auth Service)</h3><p>Before shopping, customers must <strong>log in</strong>.</p><p>This is handled by:</p><h3>👉 Auth Service</h3><p>Auth Service only cares about:</p><ul><li>Email</li><li>Password</li><li>Token (JWT)</li></ul><p>It does <strong>NOT</strong> care about:</p><ul><li>Orders</li><li>Products</li><li>Payments</li></ul><p>When a user signs up:</p><ul><li>Auth Service creates the account</li><li>Auth Service <strong>announces an event</strong></li></ul><p>📣 It shouts:</p><blockquote><em>“HEY! A USER WAS CREATED!”</em></blockquote><p>This announcement goes to <strong>Kafka</strong>.</p><h3>Chapter 4: The Town Loudspeaker (Kafka)</h3><p>Kafka is like a <strong>city-wide announcement system</strong> 📢</p><p>Everyone who is interested can listen.</p><p>Auth Service shouts:</p><pre>USER_CREATED</pre><p>Who listens?</p><ul><li>User Service</li><li>Notification Service</li><li>Analytics (later)</li></ul><p>💡 Important:</p><ul><li>Auth Service doesn’t know <em>who</em> listens</li><li>It just announces</li></ul><p>This is called:</p><h3>Event-driven architecture</h3><p>Loose coupling = strong system 💪</p><h3>Chapter 5: The Citizen Registry (User Service)</h3><p>User Service hears the announcement:</p><blockquote><em>“USER CREATED”</em></blockquote><p>It says:</p><blockquote><em>“Okay, I’ll save profile info.”</em></blockquote><p>User Service stores:</p><ul><li>Name</li><li>Email</li><li>Address (later)</li></ul><p>Auth Service and User Service <strong>never talk directly</strong>.</p><p>They communicate via <strong>events</strong> (Kafka).</p><h3>Chapter 6: The Warehouse (Product Service)</h3><p>This is the <strong>warehouse of the mall</strong> 🏭</p><p>Product Service manages:</p><ul><li>Product name</li><li>Price</li><li>Stock</li></ul><p>It doesn’t care:</p><ul><li>Who is buying</li><li>Who is logged in</li></ul><p>Customer asks:</p><blockquote><em>“Show me products</em></blockquote><p>API Gateway sends request to Product Service.</p><p>Simple. Clean. Fast ⚡</p><h3>Chapter 7: The Order Desk (Order Service)</h3><p>Customer adds products to cart and says:</p><blockquote><em>“I want to place an order!</em></blockquote><p>Order Service does:</p><ul><li>Creates order</li><li>Calculates total</li><li>Saves order</li></ul><p>But now something else must happen…</p><h3>Chapter 8: The Background Workers (RabbitMQ)</h3><p>After an order:</p><ul><li>Send email</li><li>Send SMS</li><li>Generate invoice</li></ul><p>These tasks are <strong>slow</strong> ⏳<br>So Order Service says:</p><blockquote><em>“I’m done. Someone else handle emails.</em></blockquote><p>It drops a <strong>job</strong> into RabbitMQ 🐰</p><p>RabbitMQ is like:</p><blockquote><em>A to-do list for workers</em></blockquote><h3>Chapter 9: The Post Office (Notification Service)</h3><p>Notification Service is a worker 🧑‍💼</p><p>It keeps checking RabbitMQ:</p><blockquote><em>“Any new jobs?</em></blockquote><p>RabbitMQ says:</p><blockquote><em>“Send order email!</em></blockquote><p>Notification Service:</p><ul><li>Sends email</li><li>Marks job as done ✅</li></ul><p>Order Service never waits.</p><p>Fast response. Happy customer 😊</p><h3>Chapter 10: Why Two Systems? Kafka vs RabbitMQ</h3><h3>Kafka = Announcements 📢</h3><ul><li>Events</li><li>History</li><li>Many listeners</li><li>“Something happened”</li></ul><h3>RabbitMQ = Tasks 🧾</h3><ul><li>One job</li><li>One worker</li><li>“Do this work”</li></ul><p>Both are needed in real systems.</p><h3>Chapter 11: Containers (Docker)</h3><p>Each shop in the city is:</p><ul><li>Separate</li><li>Independent</li><li>Replaceable</li></ul><p>Docker puts each service into a <strong>box</strong> 📦</p><p>Now you can:</p><ul><li>Start services independently</li><li>Scale only what you need</li><li>Deploy anywhere</li></ul><h3>Chapter 12: NGINX (The Traffic Police)</h3><p>NGINX stands in front of API Gateway.</p><p>It:</p><ul><li>Handles HTTPS</li><li>Rate limits users</li><li>Protects from attacks</li><li>Routes traffic</li></ul><h3>🧠 THE BIG PICTURE (ONE LINE)</h3><blockquote><strong><em>API Gateway handles traffic, services do one job well, Kafka announces events, RabbitMQ handles background work, and everything scales independently.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fdd59652b8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js ORMs & ODMs CRUD Operations Cheat Sheet]]></title>
            <link>https://medium.com/@farihakausar18/node-js-orms-odms-crud-operations-cheat-sheet-135e5d48c3d1?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/135e5d48c3d1</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[odm]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 11:30:33 GMT</pubDate>
            <atom:updated>2026-01-13T11:30:33.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is ORM and ODM? (Very Simple)</h3><h3>🔹 ORM (Object Relational Mapper)</h3><ul><li>Used with <strong>SQL databases</strong></li><li>Examples: MySQL, PostgreSQL, SQLite</li><li>Converts <strong>JS objects ↔ SQL tables</strong></li></ul><p>👉 Example: Sequelize, Prisma, TypeORM</p><h3>🔹 ODM (Object Document Mapper)</h3><ul><li>Used with <strong>NoSQL databases</strong></li><li>Mainly <strong>MongoDB</strong></li><li>Converts <strong>JS objects ↔ MongoDB documents</strong></li></ul><p>👉 Example: Mongoose</p><h3>2️⃣ All ORMs for Node.js (SQL Databases)</h3><h3>✅ Popular ORMs</h3><p>ORM NameDatabase Support<strong>Prisma</strong> ⭐MySQL, PostgreSQL, MongoDB<strong>Sequelize</strong>MySQL, PostgreSQL, MSSQL<strong>TypeORM</strong>MySQL, PostgreSQL, SQLite<strong>Knex.js</strong>SQL Query Builder<strong>Objection.js</strong>Built on Knex<strong>MikroORM</strong>PostgreSQL, MySQL</p><p>👉 <strong>Best choice today:</strong><br><strong>Prisma</strong> (modern, fast, very clean syntax)</p><h3>3️⃣ All ODMs for MongoDB (Node.js)</h3><p>ODM NameNotes<strong>Mongoose</strong> ⭐⭐⭐Most popularTypegooseBuilt on MongooseMongoDB Native DriverNo ORM/ODM (raw queries)</p><p>👉 <strong>Best choice:</strong> <strong>Mongoose</strong></p><h3>CRUD Operations (Common for ALL ORMs &amp; ODMs)</h3><p>CRUD means:</p><p>OperationMeaning<strong>C</strong>Create<strong>R</strong>Read<strong>U</strong>Update<strong>D</strong>Delete</p><h3>CRUD with Mongoose (MongoDB ODM)</h3><h3>🔹 Model Example</h3><pre>const User = mongoose.model(&quot;User&quot;, {<br>  name: String,<br>  email: String,<br>  age: Number<br>});</pre><h3>✅ CREATE</h3><pre>await User.create({<br>  name: &quot;Ali&quot;,<br>  email: &quot;ali@gmail.com&quot;,<br>  age: 25<br>});</pre><h3>✅ READ</h3><pre>// Get all users<br>await User.find();</pre><pre>// Get one user<br>await User.findOne({ email: &quot;ali@gmail.com&quot; });</pre><pre>// Get by ID<br>await User.findById(id);</pre><h3>✅ UPDATE</h3><pre>// Update one<br>await User.updateOne(<br>  { email: &quot;ali@gmail.com&quot; },<br>  { age: 26 }<br>);</pre><pre>// Find &amp; update<br>await User.findByIdAndUpdate(id, { age: 27 });</pre><h3>✅ DELETE</h3><pre>// Delete one<br>await User.deleteOne({ email: &quot;ali@gmail.com&quot; });</pre><pre>// Delete by ID<br>await User.findByIdAndDelete(id);</pre><h3>6️⃣ CRUD with Prisma (ORM)</h3><h3>🔹 Model</h3><pre>model User {<br>  id    Int @id @default(autoincrement())<br>  name  String<br>  email String<br>  age   Int<br>}</pre><h3>✅ CREATE</h3><pre>await prisma.user.create({<br>  data: {<br>    name: &quot;Ali&quot;,<br>    email: &quot;ali@gmail.com&quot;,<br>    age: 25<br>  }<br>});</pre><h3>✅ READ</h3><pre>// All users<br>await prisma.user.findMany();</pre><pre>// One user<br>await prisma.user.findUnique({<br>  where: { email: &quot;ali@gmail.com&quot; }<br>});</pre><h3>✅ UPDATE</h3><pre>await prisma.user.update({<br>  where: { email: &quot;ali@gmail.com&quot; },<br>  data: { age: 26 }<br>});</pre><h3>✅ DELETE</h3><pre>await prisma.user.delete({<br>  where: { email: &quot;ali@gmail.com&quot; }<br>});</pre><h3>7️⃣ CRUD with Sequelize (ORM)</h3><h3>🔹 Model</h3><pre>const User = sequelize.define(&quot;User&quot;, {<br>  name: DataTypes.STRING,<br>  email: DataTypes.STRING,<br>  age: DataTypes.INTEGER<br>});</pre><h3>✅ CREATE</h3><pre>await User.create({<br>  name: &quot;Ali&quot;,<br>  email: &quot;ali@gmail.com&quot;,<br>  age: 25<br>});</pre><h3>✅ READ</h3><pre>await User.findAll();<br>await User.findOne({ where: { email: &quot;ali@gmail.com&quot; }});</pre><h3>✅ UPDATE</h3><pre>await User.update(<br>  { age: 26 },<br>  { where: { email: &quot;ali@gmail.com&quot; } }<br>);</pre><h3>✅ DELETE</h3><pre>await User.destroy({<br>  where: { email: &quot;ali@gmail.com&quot; }<br>});</pre><h3>8️⃣ MongoDB Native Driver CRUD (No ODM)</h3><h3>✅ CREATE</h3><pre>db.collection(&quot;users&quot;).insertOne({ name: &quot;Ali&quot; });</pre><h3>✅ READ</h3><pre>db.collection(&quot;users&quot;).find({}).toArray();</pre><h3>✅ UPDATE</h3><pre>db.collection(&quot;users&quot;).updateOne(<br>  { name: &quot;Ali&quot; },<br>  { $set: { age: 26 } }<br>);</pre><h3>✅ DELETE</h3><pre>db.collection(&quot;users&quot;).deleteOne({ name: &quot;Ali&quot; });</pre><p><strong>TypeORM<br></strong>This is a TypeScript-first ORM for Node.js.</p><ul><li>Works with <strong>MySQL, PostgreSQL, SQLite, SQL Server</strong>, and more.</li><li>Supports <strong>Active Record</strong> and <strong>Data Mapper</strong> patterns.</li><li>Often used in <strong>NestJS</strong> or plain <strong>Node.js + Express</strong> backends.</li></ul><h3>2️⃣ Defining an Entity (Table) in TypeORM</h3><pre>import { Entity, PrimaryGeneratedColumn, Column } from &quot;typeorm&quot;;</pre><pre>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;</pre><pre>  @Column()<br>  name: string;</pre><pre>  @Column()<br>  email: string;</pre><pre>  @Column()<br>  age: number;<br>}</pre><h3>3️⃣ CRUD Operations in TypeORM</h3><h3>🔹 CREATE</h3><pre>import { AppDataSource } from &quot;./data-source&quot;;<br>import { User } from &quot;./entity/User&quot;;</pre><pre>const userRepo = AppDataSource.getRepository(User);</pre><pre>const user = userRepo.create({<br>  name: &quot;Ali&quot;,<br>  email: &quot;ali@gmail.com&quot;,<br>  age: 25<br>});</pre><pre>await userRepo.save(user);</pre><h3>🔹 READ</h3><pre>// Get all users<br>const allUsers = await userRepo.find();</pre><pre>// Get one user by email<br>const user = await userRepo.findOneBy({ email: &quot;ali@gmail.com&quot; });</pre><pre>// Get one user by ID<br>const userById = await userRepo.findOneBy({ id: 1 });</pre><h3>🔹 UPDATE</h3><pre>// Method 1: Load, modify, save<br>const user = await userRepo.findOneBy({ id: 1 });<br>if (user) {<br>  user.age = 26;<br>  await userRepo.save(user);<br>}</pre><pre>// Method 2: Direct update<br>await userRepo.update({ id: 1 }, { age: 27 });</pre><h3>🔹 DELETE</h3><pre>// Delete by ID<br>await userRepo.delete({ id: 1 });</pre><pre>// Delete by condition<br>await userRepo.delete({ email: &quot;ali@gmail.com&quot; });</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*916kM7e_UfgTg5EIACgU6g.png" /></figure><h3>Summary</h3><ul><li><strong>If MongoDB:</strong> Use <strong>Mongoose</strong> (most used)</li><li><strong>If SQL:</strong> Use <strong>Prisma</strong> or <strong>TypeORM</strong></li><li>TypeORM is very popular with TypeScript developers</li><li>Sequelize is also widely used</li><li><strong>CRUD operations are basically the same</strong>: Create → Read → Update → Delete, just the method names differ.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=135e5d48c3d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query — Full Guide (Beginner to Advanced)]]></title>
            <link>https://medium.com/@farihakausar18/react-query-full-guide-beginner-to-advanced-495afce46a4c?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/495afce46a4c</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react-query-v3]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 07:56:30 GMT</pubDate>
            <atom:updated>2025-12-18T07:56:30.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Query — Full Guide (Beginner to Advanced)</h3><h3>React Query — Full Guide (Beginner to Advanced)</h3><p>React Query (now called <strong>TanStack Query</strong>) is a data-fetching &amp; caching library for React.<br> It solves API calls, caching, re-fetching, loading states, and synchronization automatically.</p><h3>✅ 1. What Problem Does React Query Solve?</h3><p>Normally when using React:</p><p>Problems:</p><ul><li>No caching</li><li>No loading/error handling</li><li>No refetching</li><li>Manual state management</li></ul><p>✅ React Query handles:</p><ul><li>Fetching</li><li>Caching</li><li>Background refetch</li><li>Loading &amp; error states</li><li>Synchronization</li></ul><h3>🧱 2. Core Concepts</h3><h3>2.1 Query</h3><p>Used for GET requests (fetching data)</p><pre>const { data, isLoading, error } = useQuery({<br>  queryKey: [&#39;todos&#39;],<br>  queryFn: () =&gt; fetch(&#39;/api/todos&#39;).then(r =&gt; r.json()),<br>});</pre><h3>2.2 Mutation</h3><p>Used for POST/PUT/PATCH/DELETE</p><pre>const mutation = useMutation({<br>  mutationFn: (newTodo) =&gt;<br>    fetch(&#39;/api/todos&#39;, { method: &#39;POST&#39;, body: JSON.stringify(newTodo) })<br>});</pre><h3>2.3 Query Key</h3><h3>Query Keys (Dynamic Queries)</h3><pre>useQuery({<br>  queryKey: [&#39;user&#39;, userId],<br>  queryFn: () =&gt; fetchUser(userId),<br>});</pre><p>Unique identifier for cached data.</p><p>Examples:</p><ul><li>[&#39;todos&#39;]</li><li>[&#39;todo&#39;, id]</li><li>[&#39;products&#39;, category, sort]</li></ul><h3>2.4 Query Client</h3><p>Controls refetch, invalidate, reset, update.</p><pre>const queryClient = useQueryClient();</pre><pre>queryClient.invalidateQueries([&#39;todos&#39;]);</pre><h3>🔧 3. Setup</h3><p>Install:</p><pre>npm install @tanstack/react-query</pre><p>Wrap your app in &lt;QueryClientProvider /&gt;:</p><pre>const queryClient = new QueryClient();</pre><pre>root.render(<br>  &lt;QueryClientProvider client={queryClient}&gt;<br>    &lt;App /&gt;<br>  &lt;/QueryClientProvider&gt;<br>);</pre><h3>📦 4. Fetching Data with useQuery</h3><h3>Basic:</h3><pre>const { data, isLoading, error } = useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: () =&gt; fetch(&#39;/api/users&#39;).then(res =&gt; res.json()),<br>});</pre><h3>Return values React Query gives you:</h3><ul><li>data</li><li>isLoading</li><li>isFetching</li><li>error</li><li>refetch()</li><li>status</li><li>isSuccess</li><li>isError</li></ul><h3>5. Mutations (Create/Update/Delete)</h3><h3>Example: Create a todo</h3><pre>const queryClient = useQueryClient();</pre><pre>const { mutate, isPending } = useMutation({<br>  mutationFn: (todo) =&gt;<br>    fetch(&#39;/api/todos&#39;, {<br>      method: &#39;POST&#39;,<br>      body: JSON.stringify(todo)<br>    }),</pre><pre>  onSuccess: () =&gt; {<br>    queryClient.invalidateQueries([&#39;todos&#39;]);<br>  }<br>});</pre><p>Call it:</p><pre>mutate({ title: &quot;Hello React Query&quot; });</pre><h3>🎯 6. Query States</h3><p>State Meaning isLoading First time loading isFetching Background fetching isPending Mutation in progress isError Something failed isSuccess Query fetched successfully</p><h3>🧠 7. Cache Behavior</h3><p>React Query automatically:</p><p>✔ Caches data<br> ✔ Reuses stale data<br> ✔ Refetches in background<br> ✔ Cleans unused cache</p><h3>Important settings:</h3><h3>staleTime (how long data is “fresh”)</h3><h3>Behavior:</h3><ul><li>Within 1 min → ❌ no refetch</li><li>After 1 min → ✅ background refetch</li></ul><pre>useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: getUsers,<br>  staleTime: 10000, // 10 seconds<br>});</pre><h3>Why staleTime exists</h3><p>Without it:</p><ul><li>Every screen focus = API call</li><li>Poor performance</li></ul><h3>🟡 Default behavior (if you do nothing)</h3><pre>staleTime = 0</pre><p>Meaning:</p><ul><li>Data becomes stale immediately</li><li>Refetch on:</li><li>window focus</li><li>component remount</li><li>network reconnect</li></ul><h3>cacheTime (how long unused cache stays)</h3><pre>cacheTime: 60000 // 1 minute</pre><h3>🔄 8. Refetching Features</h3><p>React Query automatically refetches:</p><p>✔ On window focus<br> ✔ On network reconnection<br> ✔ On mount<br> ✔ On interval</p><p>You can control this:</p><pre>refetchOnWindowFocus: false,<br>refetchOnReconnect: false,<br>refetchInterval: false,</pre><h3>Manual refetch</h3><pre>const { refetch } = useQuery({...});</pre><pre>&lt;button onClick={() =&gt; refetch()}&gt;Reload&lt;/button&gt;</pre><h3>Auto refetch on:</h3><ul><li>Window focus</li><li>Network reconnect</li><li>Interval</li></ul><pre>useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: fetchUsers,<br>  refetchInterval: 5000,<br>});</pre><h3>9. Parallel Queries</h3><pre>const usersQuery = useQuery({ queryKey: [&#39;users&#39;], queryFn: getUsers });<br>const postsQuery = useQuery({ queryKey: [&#39;posts&#39;], queryFn: getPosts });</pre><h3>🔗 10. Dependent Queries</h3><p>Run second query only when first one is ready:</p><pre>const user = useQuery({ queryKey: [&#39;user&#39;], queryFn: getUser });</pre><pre>const todos = useQuery({<br>  queryKey: [&#39;todos&#39;, user.data?.id],<br>  queryFn: () =&gt; getTodos(user.data.id),<br>  enabled: !!user.data<br>});</pre><h3>🧰 11. Query Invalidation</h3><p>Used after mutation to reload data:</p><pre>import { useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br>const queryClient = useQueryClient();<br><br>useMutation({<br>  mutationFn: addUser,<br>  onSuccess: () =&gt; {<br>    queryClient.invalidateQueries([&#39;users&#39;]);<br>  },<br>});</pre><h3>⚙ 12. Prefetching(Performance boost ⚡)</h3><p>Load data before user navigates:</p><pre>queryClient.prefetchQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: fetchUsers,<br>});</pre><h3>🚀 13. Optimistic Updates</h3><p>Super powerful UX improvement.</p><h3>Example: Delete instantly before server confirms:</h3><pre>const mutation = useMutation({<br>  mutationFn: deleteTodo,</pre><pre>  onMutate: async (id) =&gt; {<br>    await queryClient.cancelQueries([&#39;todos&#39;]);</pre><pre>    const previous = queryClient.getQueryData([&#39;todos&#39;]);</pre><pre>    queryClient.setQueryData([&#39;todos&#39;], old =&gt;<br>      old.filter(todo =&gt; todo.id !== id)<br>    );</pre><pre>    return { previous };<br>  },</pre><pre>  onError: (_, __, context) =&gt; {<br>    queryClient.setQueryData([&#39;todos&#39;], context.previous);<br>  },</pre><pre>  onSettled: () =&gt; {<br>    queryClient.invalidateQueries([&#39;todos&#39;]);<br>  }<br>});</pre><h3>🏗 14. Infinite Queries (Pagination)</h3><pre>const {<br>  data,<br>  fetchNextPage,<br>  hasNextPage,<br>} = useInfiniteQuery({<br>  queryKey: [&#39;products&#39;],<br>  queryFn: ({ pageParam = 1 }) =&gt; fetchProducts(pageParam),<br>  getNextPageParam: (lastPage) =&gt; lastPage.nextPage,<br>});<br><br><br><br>useQuery({<br>  queryKey: [&#39;users&#39;, page],<br>  queryFn: () =&gt; fetchUsers(page),<br>  keepPreviousData: true,<br>});</pre><h3>🧩 15. Devtools (must use)</h3><pre>npm install @tanstack/react-query-devtools</pre><pre>&lt;QueryClientProvider client={queryClient}&gt;<br>  &lt;App /&gt;<br>  &lt;ReactQueryDevtools /&gt;<br>&lt;/QueryClientProvider&gt;</pre><p>Gives visual debugging!</p><h3>Error handling</h3><pre>useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: fetchUsers,<br>  retry: 3,<br>});</pre><p>Or globally:</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      retry: 2,<br>    },<br>  },<br>});</pre><h3>2. Project Folder Structure (Best Practice)</h3><pre>src/<br> ├── api/<br> │    ├── axios.js<br> │    ├── users.js<br> │    └── products.js<br> │<br> ├── hooks/<br> │    ├── useUsers.js<br> │    ├── useProducts.js<br> │<br> ├── components/<br> │    ├── UserList.jsx<br> │    ├── ProductCard.jsx<br> │<br> ├── query/<br> │    ├── queryClient.js<br> │    └── queryKeys.js<br> │<br> ├── pages/<br> │    ├── Users.jsx<br> │    └── Products.jsx<br> │<br> └── App.jsx</pre><h3>✅ 3. Axios + React Query Setup</h3><h3>api/axios.js</h3><pre>import axios from &quot;axios&quot;;</pre><pre>const api = axios.create({<br>  baseURL: &quot;https://api.example.com&quot;,<br>});</pre><pre>export default api;</pre><h3>Basic GET using Axios</h3><pre>const { data } = useQuery({<br>  queryKey: [&#39;users&#39;],<br>  queryFn: () =&gt; api.get(&#39;/users&#39;).then(res =&gt; res.data)<br>});</pre><h3>Mutations with Axios</h3><pre>const mutation = useMutation({<br>  mutationFn: (user) =&gt; api.post(&#39;/users&#39;, user),<br>  onSuccess: () =&gt; queryClient.invalidateQueries([&#39;users&#39;]),<br>});</pre><h3>✅ 4. Full CRUD Boilerplate (Copy-Paste)</h3><h3>➤ GET</h3><pre>export const useUsers = () =&gt;<br>  useQuery({<br>    queryKey: [&#39;users&#39;],<br>    queryFn: () =&gt; api.get(&#39;/users&#39;).then(res =&gt; res.data),<br>  });</pre><h3>➤ CREATE</h3><pre>export const useCreateUser = () =&gt; {<br>  const queryClient = useQueryClient();</pre><pre>  return useMutation({<br>    mutationFn: (data) =&gt; api.post(&#39;/users&#39;, data),<br>    onSuccess: () =&gt; queryClient.invalidateQueries([&#39;users&#39;]),<br>  });<br>};</pre><h3>➤ UPDATE</h3><pre>export const useUpdateUser = () =&gt; {<br>  const queryClient = useQueryClient();</pre><pre>  return useMutation({<br>    mutationFn: ({ id, ...data }) =&gt; api.put(`/users/${id}`, data),<br>    onSuccess: () =&gt; queryClient.invalidateQueries([&#39;users&#39;]),<br>  });<br>};</pre><h3>➤ DELETE</h3><pre>export const useDeleteUser = () =&gt; {<br>  const queryClient = useQueryClient();</pre><pre>  return useMutation({<br>    mutationFn: (id) =&gt; api.delete(`/users/${id}`),<br>    onSuccess: () =&gt; queryClient.invalidateQueries([&#39;users&#39;]),<br>  });<br>};</pre><h3>✅ 5. React Query + Zustand + Redux Toolkit</h3><h3>React Query + Zustand Example</h3><p>Use Zustand for local UI state, React Query for server data.</p><pre>import { create } from &#39;zustand&#39;;</pre><pre>export const useUserStore = create((set) =&gt; ({<br>  selectedUser: null,<br>  setSelectedUser: (user) =&gt; set({ selectedUser: user }),<br>}));</pre><p>Use with React Query:</p><pre>const { selectedUser } = useUserStore();<br>const { data } = useQuery({<br>  queryKey: [&#39;user&#39;, selectedUser],<br>  queryFn: () =&gt; api.get(`/users/${selectedUser}`),<br>  enabled: !!selectedUser<br>});</pre><h3>React Query + Redux Toolkit</h3><p>Redux for UI state, theme, filters<br> React Query for API calls.</p><p>Example using Redux filter:</p><pre>const filter = useSelector(s =&gt; s.users.filter);</pre><pre>useQuery({<br>  queryKey: [&#39;users&#39;, filter],<br>  queryFn: () =&gt; api.get(`/users?filter=${filter}`),<br>});</pre><h3>✅ 6. React Query + Next.js App Router (2024 Updated)</h3><h3>Install</h3><pre>npm i @tanstack/react-query</pre><h3>app/providers.jsx</h3><pre>&quot;use client&quot;;</pre><pre>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;;</pre><pre>const client = new QueryClient();</pre><pre>export default function Providers({ children }) {<br>  return (<br>    &lt;QueryClientProvider client={client}&gt;<br>      {children}<br>      &lt;ReactQueryDevtools /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><h3>app/layout.jsx</h3><pre>import Providers from &quot;./providers&quot;;</pre><pre>export default function RootLayout({ children }) {<br>  return (<br>    &lt;html&gt;<br>      &lt;body&gt;<br>        &lt;Providers&gt;{children}&lt;/Providers&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><h3>Example GET in Next.js</h3><pre>&quot;use client&quot;;</pre><pre>import { useQuery } from &quot;@tanstack/react-query&quot;;<br>import api from &quot;@/api/axios&quot;;</pre><pre>export default function Page() {<br>  const { data, isLoading } = useQuery({<br>    queryKey: [&#39;users&#39;],<br>    queryFn: () =&gt; api.get(&#39;/users&#39;).then(r =&gt; r.data)<br>  });</pre><pre>  return &lt;div&gt;{isLoading ? &quot;Loading...&quot; : JSON.stringify(data)}&lt;/div&gt;;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=495afce46a4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Complete Guide (Beginner → Advanced)]]></title>
            <link>https://medium.com/@farihakausar18/typescript-complete-guide-beginner-advanced-ad0f36b7ed27?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad0f36b7ed27</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 07:20:40 GMT</pubDate>
            <atom:updated>2025-12-17T07:20:40.355Z</atom:updated>
            <content:encoded><![CDATA[<p>1. What is TypeScript?</p><p>TypeScript = <strong>JavaScript + Types</strong>.</p><p>✔ Catches errors before running<br> ✔ Autocomplete support<br> ✔ Cleaner code in big projects<br> ✔ Used in React, Next.js, Node.js, Express, NestJS</p><p><strong>Example</strong></p><pre>let age: number = 25;<br>let name: string = &quot;Fariha&quot;;</pre><h3>2. Basic Types</h3><h3>✔ Primitive Types</h3><pre>let username: string = &quot;Ali&quot;;<br>let age: number = 20;<br>let isActive: boolean = true;</pre><h3>✔ Any (avoid using)</h3><pre>let data: any = &quot;hello&quot;;  // ❌ avoid</pre><h3>✔ Unknown (safer)</h3><pre>let value: unknown = &quot;hi&quot;;</pre><h3>✔ Arrays</h3><pre>let numbers: number[] = [1, 2, 3];<br>let names: string[] = [&quot;Ali&quot;, &quot;Sara&quot;];</pre><h3>✔ Tuples</h3><pre>let person: [string, number] = [&quot;Ali&quot;, 20];</pre><h3>3. Objects</h3><pre>let user: { name: string; age: number } = {<br>  name: &quot;Ali&quot;,<br>  age: 22,<br>};</pre><h3>4. Type Aliases</h3><p>Clean way to reuse types.</p><pre>type User = {<br>  id: number;<br>  name: string;<br>  email?: string; // optional<br>};<br><br>let u1: User = {<br>  id: 1,<br>  name: &quot;Fariha&quot;,<br>};</pre><h3>5. Interfaces</h3><p>Interfaces are similar to type aliases but better for OOP/Classes.</p><pre>interface Product {<br>  id: number;<br>  name: string;<br>  price: number;<br>}<br><br>const p: Product = {<br>  id: 1,<br>  name: &quot;Laptop&quot;,<br>  price: 1000,<br>};</pre><h3>6. Functions</h3><p>Basic:</p><pre>function add(a: number, b: number): number {<br>  return a + b;<br>}</pre><h3>Optional Parameter</h3><p>function greet(name?: string) {}</p><h3>Default Parameter</h3><pre>function greet(name: string = &quot;Guest&quot;) {}</pre><pre>Arrow function:</pre><pre>const multiply = (a: number, b: number): number =&gt; a * b;</pre><p>Optional parameter:</p><pre>function greet(name: string, title?: string) {<br>  return `Hello ${title ? title + &#39; &#39; : &#39;&#39;}${name}`;<br>}</pre><h3>7. Union Types</h3><p>Allows multiple types.</p><pre>let id: number | string;<br>id = 100;<br>id = &quot;ABC&quot;;</pre><h3>8. Literal Types</h3><pre>let status: &quot;success&quot; | &quot;error&quot; | &quot;pending&quot;;<br>status = &quot;success&quot;;</pre><h3>9. Enums</h3><pre>enum Role {<br>  ADMIN,<br>  USER,<br>  GUEST,<br>}<br><br>let r: Role = Role.ADMIN;</pre><h3>10. Generics (Advanced Beginner → Intermediate)</h3><p>Generics make code flexible.</p><pre>function wrap&lt;T&gt;(value: T): T {<br>  return value;<br>}<br><br>const a = wrap&lt;number&gt;(10);<br>const b = wrap&lt;string&gt;(&quot;hello&quot;);</pre><p>Generic Array:</p><pre>let arr: Array&lt;number&gt; = [1, 2, 3];</pre><h3>11. Classes (OOP in TS)</h3><pre>class Person {<br>  name: string;<br>  age: number;</pre><pre>  constructor(name: string, age: number) {<br>    this.name = name;<br>    this.age = age;<br>  }</pre><pre>  speak() {<br>    return `${this.name} says hi!`;<br>  }<br>}</pre><pre>const p = new Person(&quot;Ali&quot;, 20);</pre><h3>12. Access Modifiers</h3><p>Modifier Meaningpublicaccessible anywhereprivateclass onlyprotectedclass + child class</p><pre>class Bank {<br>  private balance: number = 0;</pre><pre>  deposit(amount: number) {<br>    this.balance += amount;<br>  }<br>}</pre><h3>13. Readonly</h3><pre>class Car {<br>  readonly model: string = &quot;Honda&quot;;<br>}</pre><h3>14. Type Narrowing (Advanced)</h3><p>TS detects possible types.</p><pre>function printId(id: string | number) {<br>  if (typeof id === &quot;string&quot;) {<br>    console.log(id.toUpperCase());<br>  } else {<br>    console.log(id.toFixed(2));<br>  }<br>}</pre><h3>15. Utility Types (Very Advanced)</h3><p>Common ones:</p><h3>✔ Partial — makes all fields optional</h3><pre>type User = { name: string; age: number };<br>let u: Partial&lt;User&gt; = {};</pre><h3>Required — all fields must exist</h3><pre>let u2: Required&lt;User&gt; = { name: &quot;Ali&quot;, age: 20 };</pre><h3>Pick — choose only specific fields</h3><pre>type UserShort = Pick&lt;User, &quot;name&quot;&gt;;</pre><h3>Omit — remove fields</h3><pre>type WithoutAge = Omit&lt;User, &quot;age&quot;&gt;;</pre><h3>16. Type Assertion</h3><p>Use carefully.</p><pre>let input = document.getElementById(&quot;name&quot;) as HTMLInputElement;<br>console.log(input.value);</pre><h3>17. Modules / Imports</h3><pre>// user.ts<br>export const name = &quot;Ali&quot;;</pre><pre>// main.ts<br>import { name } from &quot;./user&quot;;</pre><h3>18. TypeScript in React</h3><h3>✔ Props</h3><pre>interface Props {<br>  title: string;<br>}</pre><pre>function Button({ title }: Props) {<br>  return &lt;button&gt;{title}&lt;/button&gt;;<br>}</pre><h3>✔ useState</h3><pre>const [count, setCount] = useState&lt;number&gt;(0);</pre><h3>19. TypeScript in Express.js (Backend)</h3><pre>import express, { Request, Response } from &quot;express&quot;;</pre><pre>const app = express();</pre><pre>app.get(&quot;/user/:id&quot;, (req: Request, res: Response) =&gt; {<br>  const id = Number(req.params.id);<br>  res.json({ id });<br>});</pre><h3>20. Real Project Structure</h3><pre>src/<br>  controllers/<br>  services/<br>  routes/<br>  types/<br>  utils/<br>tsconfig.json</pre><h3>1️⃣ What are type and interface?</h3><p>Both are used to <strong>define the shape of data</strong> in TypeScript.</p><p>They help:</p><ul><li>Catch errors at compile time</li><li>Make code readable</li><li>Enforce structure</li></ul><h3>Example (basic)</h3><h3>interface</h3><pre>interface User {<br>  id: number<br>  name: string<br>  email: string<br>}</pre><h3>type</h3><pre>type User = {<br>  id: number<br>  name: string<br>  email: string<br>}</pre><p>➡️ <strong>At this level: THEY LOOK THE SAME</strong></p><h3>2️⃣ Key Differences (IMPORTANT)</h3><h3>🔹 1. Declaration Merging (BIG DIFFERENCE)</h3><h3>interface ✅ supports merging</h3><pre>interface User {<br>  id: number<br>}</pre><pre>interface User {<br>  name: string<br>}</pre><p>✔️ Final result:</p><pre>interface User {<br>  id: number<br>  name: string<br>}</pre><h3>type ❌ does NOT support merging</h3><pre>type User = {<br>  id: number<br>}</pre><pre>type User = {<br>  name: string<br>}<br>// ❌ Error: Duplicate identifier</pre><p>📌 <strong>Use interface when you want extendable / mergeable types</strong></p><h3>🔹 2. Extending / Inheritance</h3><h3>Interface extends interface</h3><pre>interface Person {<br>  name: string<br>}</pre><pre>interface User extends Person {<br>  id: number<br>}</pre><h3>Type extends using intersection &amp;</h3><pre>type Person = {<br>  name: string<br>}</pre><pre>type User = Person &amp; {<br>  id: number<br>}</pre><p>✔️ Both work<br>✔️ Interface syntax is <strong>cleaner</strong></p><h3>🔹 3. Union Types (ONLY type)</h3><h3>type ✅ supports unions</h3><pre>type Status = &quot;loading&quot; | &quot;success&quot; | &quot;error&quot;</pre><p>❌ interface cannot do this</p><p>📌 <strong>Use </strong><strong>type for unions</strong></p><h3>🔹 4. Primitive, Tuple, Function Types</h3><h3>type ✅ can define primitives</h3><pre>type ID = string | number</pre><h3>type ✅ tuple</h3><pre>type Point = [number, number]</pre><h3>type ✅ function</h3><pre>type Login = (email: string, password: string) =&gt; boolean</pre><p>❌ interface cannot define primitives or unions</p><h3>🔹 5. Objects &amp; Classes</h3><h3>Interface with class (very common)</h3><pre>interface Auth {<br>  login(): void<br>}</pre><pre>class AuthService implements Auth {<br>  login() {<br>    console.log(&quot;Logged in&quot;)<br>  }<br>}</pre><p>✔️ Interface is <strong>best for OOP &amp; classes</strong></p><h3>🔹 6. Readability &amp; Best Practice</h3><p>Use CasePreferObject shapesinterfaceClass contractsinterfaceLibrary / public APIsinterfaceUnion / intersectiontypePrimitivestypeFunction signaturestype</p><h3>When to Use WHAT? (Simple Rule)</h3><h3>✅ Use interface when:</h3><ul><li>You define <strong>object structure</strong></li><li>You work with <strong>classes</strong></li><li>You want <strong>extensibility</strong></li><li>You’re building <strong>APIs / libraries</strong></li></ul><h3>✅ Use type when:</h3><ul><li>You need <strong>union types</strong></li><li>You need <strong>tuples</strong></li><li>You define <strong>function types</strong></li><li>You combine multiple types (&amp; |)</li></ul><h3>4️⃣ Real Project Example (React / Node)</h3><h3>API Response</h3><pre>interface User {<br>  id: number<br>  name: string<br>  role: &quot;admin&quot; | &quot;user&quot;<br>}</pre><h3>Role Type</h3><pre>type Role = &quot;admin&quot; | &quot;user&quot; | &quot;super-admin&quot;</pre><h3>API Function</h3><pre>type GetUser = () =&gt; Promise&lt;User&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0f36b7ed27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering GraphQL from Beginner to Advanced (Complete Developer Guide)]]></title>
            <link>https://medium.com/@farihakausar18/mastering-graphql-from-beginner-to-advanced-complete-developer-guide-acb69ade03fd?source=rss-2c82f59b43db------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb69ade03fd</guid>
            <category><![CDATA[grapql]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Fariha kausar |  Web Developer & Tech Blogger]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 06:14:39 GMT</pubDate>
            <atom:updated>2025-11-12T06:14:39.236Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>The ultimate step-by-step guide to understanding, building, and scaling GraphQL APIs — from fundamentals to real-world, production-ready techniques.</em></blockquote><h3>What is GraphQL?</h3><p>GraphQL (<strong>Graph Query Language</strong>) is a modern API technology developed by <strong>Facebook</strong>, designed to make data fetching more <strong>efficient</strong>, <strong>flexible</strong>, and <strong>precise</strong> than traditional REST APIs.</p><p>Instead of calling multiple REST endpoints like /users, /posts, and /comments, you send <strong>one GraphQL request</strong> and get <strong>exactly what you need</strong>.</p><h3>🔍 Example</h3><pre>query {<br>  user(id: &quot;1&quot;) {<br>    name<br>    email<br>    posts {<br>      title<br>    }<br>  }<br>}</pre><p>👉 Returns only the name, email, and title fields — no over-fetching or under-fetching.</p><h3>⚙️ Core Concepts</h3><p>Concept Purpose Example <strong>Schema</strong> Blueprint defining your data and operations type User { id: ID! name: String! } <br> <strong>Query</strong> For reading data (like GET) query { users { id name } } <br> <strong>Mutation</strong> For writing data (like POST/PUT/DELETE) mutation { createUser(name:&quot;Ali&quot;){id} }<br> <strong>Resolver</strong> Function that executes a query or mutation Fetch data from DB or API <br><strong>Subscription</strong> Real-time updates over WebSockets Live data updates (chat, notifications) <br> <strong>Variable</strong> Dynamic query parameters $id: ID! <br> <strong>Directive</strong> Conditional field inclusion/exclusion @include(if: $showEmail)</p><h3>🧩 GraphQL vs REST</h3><p>Feature GraphQL REST Endpoint Single /graphql Multiple endpoints Data fetching Ask for what you need Often over-fetch/under-fetch Versioning Not needed /v1, /v2, etc. Real-time data Built-in subscriptions Extra setup (WebSockets) Schema typing Strongly typed JSON, loosely typed</p><h3>🏗️ Building a GraphQL API (MERN Example)</h3><h3>1️⃣ Backend — Apollo Server + Express + MongoDB</h3><h4>Install dependencies</h4><pre>npm install express apollo-server-express graphql mongoose</pre><h4>server.js</h4><pre>import express from &quot;express&quot;;<br>import { ApolloServer } from &quot;apollo-server-express&quot;;<br>import mongoose from &quot;mongoose&quot;;<br>import { typeDefs } from &quot;./schema.js&quot;;<br>import { resolvers } from &quot;./resolvers.js&quot;;</pre><pre>const app = express();</pre><pre>const server = new ApolloServer({ typeDefs, resolvers });<br>await server.start();<br>server.applyMiddleware({ app });</pre><pre>mongoose.connect(&quot;mongodb://localhost:27017/graphqlApp&quot;);</pre><pre>app.listen(4000, () =&gt;<br>  console.log(`🚀 Server ready at <a href="http://localhost:4000${server.graphqlPath}`)">http://localhost:4000${server.graphqlPath}`)</a><br>);</pre><h4>schema.js</h4><pre>import { gql } from &quot;apollo-server-express&quot;;</pre><pre>export const typeDefs = gql`<br>  scalar Date</pre><pre>  type User {<br>    id: ID!<br>    name: String!<br>    email: String!<br>    createdAt: Date<br>  }</pre><pre>  type Query {<br>    users: [User]<br>    user(id: ID!): User<br>  }</pre><pre>  type Mutation {<br>    createUser(name: String!, email: String!): User<br>  }</pre><pre>  type Subscription {<br>    userAdded: User<br>  }<br>`;</pre><h4>resolvers.js</h4><pre>import { PubSub } from &quot;graphql-subscriptions&quot;;<br>import { GraphQLScalarType, Kind } from &quot;graphql&quot;;<br>import User from &quot;./models/User.js&quot;;</pre><pre>const pubsub = new PubSub();</pre><pre>export const resolvers = {<br>  Date: new GraphQLScalarType({<br>    name: &quot;Date&quot;,<br>    parseValue(value) {<br>      return new Date(value);<br>    },<br>    serialize(value) {<br>      return value.toISOString();<br>    },<br>  }),</pre><pre>  Query: {<br>    users: () =&gt; User.find(),<br>    user: (_, { id }) =&gt; User.findById(id),<br>  },</pre><pre>  Mutation: {<br>    createUser: async (_, { name, email }) =&gt; {<br>      const user = await User.create({ name, email, createdAt: new Date() });<br>      pubsub.publish(&quot;USER_ADDED&quot;, { userAdded: user });<br>      return user;<br>    },<br>  },</pre><pre>  Subscription: {<br>    userAdded: {<br>      subscribe: () =&gt; pubsub.asyncIterator(&quot;USER_ADDED&quot;),<br>    },<br>  },<br>};</pre><h4>models/User.js</h4><pre>import mongoose from &quot;mongoose&quot;;<br>const userSchema = new mongoose.Schema({<br>  name: String,<br>  email: String,<br>  createdAt: Date,<br>});<br>export default mongoose.model(&quot;User&quot;, userSchema);</pre><h3>2️⃣ Frontend — React + Apollo Client</h3><h4>Install client packages</h4><pre>npm install @apollo/client graphql</pre><h4>App.js</h4><pre>import React from &quot;react&quot;;<br>import {<br>  ApolloClient,<br>  InMemoryCache,<br>  ApolloProvider,<br>  useQuery,<br>  gql,<br>} from &quot;@apollo/client&quot;;</pre><pre>const client = new ApolloClient({<br>  uri: &quot;http://localhost:4000/graphql&quot;,<br>  cache: new InMemoryCache(),<br>});</pre><pre>const GET_USERS = gql`<br>  query {<br>    users {<br>      id<br>      name<br>      email<br>    }<br>  }<br>`;</pre><pre>function Users() {<br>  const { loading, error, data } = useQuery(GET_USERS);<br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error!&lt;/p&gt;;<br>  return (<br>    &lt;div&gt;<br>      {data.users.map((user) =&gt; (<br>        &lt;p key={user.id}&gt;{user.name} — {user.email}&lt;/p&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default function App() {<br>  return (<br>    &lt;ApolloProvider client={client}&gt;<br>      &lt;Users /&gt;<br>    &lt;/ApolloProvider&gt;<br>  );<br>}</pre><h3>🧠 Advanced GraphQL Features</h3><h3>🔸 Fragments</h3><p>Avoid repeating field selections.</p><pre>fragment userFields on User {<br>  id<br>  name<br>  email<br>}</pre><pre>query {<br>  users {<br>    ...userFields<br>  }<br>}</pre><h3>🔸 Directives</h3><p>Conditionally fetch data.<br><em>Add </em><strong><em>conditions or transformations</em></strong><em> to queries.<br></em>Built-in directives:</p><ul><li>@include(if: Boolean) → include a field conditionally.</li><li>@skip(if: Boolean) → skip a field conditionally.</li></ul><pre>query GetUser($showEmail: Boolean!) {<br>  user {<br>    name<br>    email @include(if: $showEmail)<br>  }<br>}</pre><h3>🔸 Custom Scalars</h3><p>Custom types like Date, JSON, etc.</p><p>Handled in resolvers via GraphQLScalarType.</p><p>scalar Date</p><p>type Event {<br> id: ID!<br> title: String!<br> date: Date!<br>}<br>Then handle parsing/serializing in resolvers:<br>import { GraphQLScalarType, Kind } from “graphql”;</p><p>export const resolvers = {<br> Date: new GraphQLScalarType({<br> name: “Date”,<br> parseValue(value) {<br> return new Date(value); // client → server<br> },<br> serialize(value) {<br> return value.toISOString(); // server → client<br> },<br> }),<br>};</p><h3>🔸 Authentication via Context</h3><pre>const server = new ApolloServer({<br>  typeDefs,<br>  resolvers,<br>  context: ({ req }) =&gt; {<br>    const token = req.headers.authorization;<br>    const user = verifyToken(token);<br>    return { user };<br>  },<br>});</pre><p>Then in resolver:</p><pre>Query: {<br>  me: (_, __, { user }) =&gt; {<br>    if (!user) throw new Error(&quot;Unauthorized&quot;);<br>    return user;<br>  },<br>}</pre><h3>🔸 DataLoader (Avoid N+1 Problem)</h3><p>Batch similar DB requests.</p><pre>import DataLoader from &quot;dataloader&quot;;</pre><pre>const userLoader = new DataLoader(async (userIds) =&gt; {<br>  const users = await User.find({ _id: { $in: userIds } });<br>  return userIds.map((id) =&gt; users.find((u) =&gt; u.id === id));<br>});</pre><p>Then:</p><pre>Post: {<br>  author: (post, _, { loaders }) =&gt; loaders.userLoader.load(post.authorId),<br>}</pre><h3>🔸 Subscriptions (Real-time Updates)</h3><p>Enable live updates with WebSockets.</p><pre>subscription {<br>  userAdded {<br>    id<br>    name<br>    email<br>  }<br>}</pre><p>Whenever createUser runs, all connected clients get updates instantly.</p><h3>🔸 Federation (Microservices)</h3><p>Combine multiple GraphQL services into one unified graph (common in large apps like Shopify, Netflix).</p><pre>type User @key(fields: &quot;id&quot;) {<br>  id: ID!<br>  name: String!<br>}</pre><pre>type Product @key(fields: &quot;id&quot;) {<br>  id: ID!<br>  name: String!<br>  creator: User<br>}</pre><h3>Real-World Example: Shopify GraphQL</h3><p>Shopify uses GraphQL extensively. Example query:</p><pre>query shopInfo {<br>  shop {<br>    name<br>    url<br>    myshopifyDomain<br>    plan {<br>      displayName<br>      partnerDevelopment<br>      shopifyPlus<br>    }<br>  }<br>}</pre><p>Another:</p><pre>query {<br>  themes(first: 5) {<br>    edges {<br>      node {<br>        id<br>        name<br>        role<br>      }<br>    }<br>  }<br>}</pre><p>You can query <strong>webhooks</strong>, <strong>products</strong>, or <strong>orders</strong> — all from one endpoint.</p><h3>🏁 Conclusion</h3><p>GraphQL transforms how developers <strong>design, query, and scale APIs</strong>.<br> It provides a <strong>single source of truth</strong>, <strong>strong typing</strong>, and <strong>real-time capabilities</strong> — ideal for modern applications, from <strong>MERN stacks</strong> to <strong>Shopify apps</strong> and <strong>enterprise systems</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb69ade03fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>