<?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 Dipika_gandash on Medium]]></title>
        <description><![CDATA[Stories by Dipika_gandash on Medium]]></description>
        <link>https://medium.com/@dipikagandash411?source=rss-550151d94051------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m2i6T1ti8rSa2IHtra_FZg.jpeg</url>
            <title>Stories by Dipika_gandash on Medium</title>
            <link>https://medium.com/@dipikagandash411?source=rss-550151d94051------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 02:56:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dipikagandash411/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[Debouncing in React: Optimize API Calls in Search Inputs]]></title>
            <link>https://medium.com/@dipikagandash411/debouncing-in-react-optimize-api-calls-in-search-inputs-efaec561c31a?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/efaec561c31a</guid>
            <category><![CDATA[debouncing]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 08:53:36 GMT</pubDate>
            <atom:updated>2026-03-11T08:53:36.834Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXsyrnLSWIzEWCAY2tO-Sg.jpeg" /></figure><p>When I was building a job search feature in my React application, I added a simple search bar where users could type keywords to find jobs.</p><p>Everything looked fine at first. But when I opened the browser’s Network tab, I noticed something strange.</p><p>Every single keystroke triggered an API request.</p><p>If a user typed <strong>“react developer”</strong>, the application made requests for:</p><ul><li>r</li><li>re</li><li>rea</li><li>reac</li><li>react</li><li>react developer</li></ul><p>That meant <strong>multiple unnecessary API calls</strong> were being sent to the server in just a few seconds.</p><p>This not only wastes server resources but can also slow down the application and create a poor user experience.</p><p>So the question became:</p><p><strong>How can we wait until the user finishes typing before making the API request?</strong></p><p>This is exactly where <strong>Debouncing</strong> comes in.</p><p>In this article, we’ll understand what debouncing is, why it’s useful, and how to implement it in a React application.</p><h3>What Problem Does Debouncing Solve?</h3><h4>The Problem: Too Many Function Calls</h4><p>In many web applications, certain events can fire repeatedly within a very short period of time. A common example is a <strong>search input field</strong>.</p><p>Every time a user presses a key, the onChange event is triggered. If we directly call an API inside this event, the application will send a request for <strong>every single keystroke</strong>.</p><p>For example, if a user types <strong>“react developer”</strong>, the application may trigger API calls like this:</p><ul><li>r</li><li>re</li><li>rea</li><li>reac</li><li>react</li><li>react developer</li></ul><p>This means multiple API requests are sent even though the user is still typing.</p><p>This can cause several problems:</p><ul><li>Unnecessary API requests to the server</li><li>Increased server load</li><li>Slower application performance</li><li>Poor user experience</li></ul><p>Instead of calling the API on every keystroke, it would be much better if the application <strong>waited for the user to stop typing</strong> before making the request.</p><p>This is where <strong>Debouncing</strong> becomes useful.</p><h3>What is Debouncing?</h3><p>Debouncing is a technique used to control how often a function is executed when an event occurs repeatedly in a short period of time.</p><p>Instead of running the function immediately every time the event is triggered, debouncing <strong>delays the execution</strong> until a certain amount of time has passed without the event being triggered again.</p><p>In simple terms, debouncing means:</p><p><strong>“Wait for the user to stop performing an action before running the function.”</strong></p><p>Let’s take a search bar as an example.</p><p>When a user types in a search input, many events fire quickly as each key is pressed. If we call the API immediately for each keystroke, it will result in multiple unnecessary requests.</p><p>With debouncing, the application waits for a short delay (for example, 500 milliseconds). If the user keeps typing during that time, the previous timer resets. The function only executes once the user stops typing for the specified delay.</p><p>This helps ensure that the function runs <strong>only once after the user finishes typing</strong>, instead of running many times.</p><h3>How Debouncing Works</h3><p>To understand debouncing better, let’s compare what happens <strong>with and without debouncing</strong> when a user types in a search bar.</p><h4>Without Debouncing</h4><p>Every keystroke immediately triggers the function (for example, an API request).</p><pre>User types: r<br>→ API Call<br>User types: re<br>→ API Call<br>User types: rea<br>→ API Call<br>User types: react<br>→ API Call</pre><p>In this case, the server receives <strong>multiple unnecessary requests</strong>, even though the user is still typing.</p><h4>With Debouncing</h4><p>With debouncing, the function waits for a short delay (for example, <strong>500 milliseconds</strong>) after the user stops typing.</p><pre>User types: r → wait<br>User types: re → reset timer<br>User types: rea → reset timer<br>User types: react → reset timer<br>User stops typing for 500ms<br>→ API Call</pre><p>Now the API request is triggered <strong>only once</strong>, after the user finishes typing.</p><p>This significantly reduces unnecessary function calls and improves application performance.</p><h3>Implementing Debouncing in React</h3><p>Now that we understand the concept, let’s implement it step by step.</p><h4>Step 1: Write the Debounce Function</h4><pre>function debounce(func, delay) {<br>  let timer;<br>  return function (...args) {<br>    clearTimeout(timer);<br>    timer = setTimeout(() =&gt; {<br>      func(...args);<br>    }, delay);<br>  };<br>}</pre><p>Think of it like this:</p><p>Every time the user types, we set a countdown of 500ms. If the user types again before the countdown finishes, we reset it. Only when the user stops typing and the countdown actually finishes — we make the API call.</p><p>That’s it. That’s all debounce is doing.</p><h4>Step 2: Use It in a React Component</h4><pre>import React, { useState } from &quot;react&quot;;<br>  function debounce(func, delay) {<br>  let timer;<br>  return (...args) =&gt; {<br>    clearTimeout(timer);<br>    timer = setTimeout(() =&gt; func(...args), delay);<br>  };<br>}<br>export default function SearchBar() {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const searchJob = (value) =&gt; {<br>    console.log(&quot;API Call with:&quot;, value);<br>  };<br>  const debouncedSearch = debounce(searchJob, 500);<br>  const handleChange = (e) =&gt; {<br>    const value = e.target.value;<br>    setQuery(value);<br>    debouncedSearch(value);<br>  };<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      value={query}<br>      onChange={handleChange}<br>      placeholder=&quot;Search jobs...&quot;<br>    /&gt;<br>  );<br>}</pre><p>This looks correct, but there’s actually a hidden bug here. Let’s talk about it.</p><h4>Step 3: The Hidden Bug</h4><p>Here’s the problem.</p><p>Every time the user types, setQuery causes a <strong>re-render</strong>. And on every re-render, debounce(searchJob, 500) runs again — creating a <strong>brand new function</strong> with a <strong>brand new timer</strong>.</p><p>So the old timer never gets cancelled. The debounce is basically doing nothing.</p><p><strong>The fix is simple — wrap it in </strong><strong>useCallback:</strong></p><pre>import React, { useState, useCallback } from &quot;react&quot;;<br>export default function SearchBar() {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const searchJob = (value) =&gt; {<br>    console.log(&quot;API Call with:&quot;, value);<br>  };<br>  // ✅ This is now created only ONCE, not on every re-render<br>  const debouncedSearch = useCallback(debounce(searchJob, 500), []);<br>  const handleChange = (e) =&gt; {<br>    const value = e.target.value;<br>    setQuery(value);<br>    debouncedSearch(value);<br>  };<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      value={query}<br>      onChange={handleChange}<br>      placeholder=&quot;Search jobs...&quot;<br>    /&gt;<br>  );<br>}</pre><p>useCallback tells React: &quot;don&#39;t recreate this function on every render, keep the same one.&quot;</p><p>Now the timer persists correctly, and debounce works as expected.</p><h3>Bonus: Use Lodash Instead of Writing It Yourself</h3><p>In real projects, you don’t need to write the debounce function from scratch. Lodash has a reliable, well-tested version.</p><pre>npm install lodash</pre><pre>import { debounce } from &quot;lodash&quot;;<br>import React, { useState, useCallback } from &quot;react&quot;;<br>export default function SearchBar() {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const debouncedSearch = useCallback(<br>    debounce((value) =&gt; {<br>      console.log(&quot;API Call with:&quot;, value);<br>    }, 500),<br>    []<br>  );<br>  const handleChange = (e) =&gt; {<br>    const value = e.target.value;<br>    setQuery(value);<br>    debouncedSearch(value);<br>  };<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      value={query}<br>      onChange={handleChange}<br>      placeholder=&quot;Search jobs...&quot;<br>    /&gt;<br>  );<br>}<br>Same result, less code, more reliable. Use this in production.</pre><h3>Quick Recap</h3><ul><li>Debounce = wait for the user to stop typing, then fire the function</li><li>Always wrap the debounced function in useCallback so React doesn&#39;t recreate it on every render</li><li>In real projects, just use Lodash — no need to write debounce yourself</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efaec561c31a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle File Uploads in Node.js (Beginner Guide to Multer)]]></title>
            <link>https://medium.com/@dipikagandash411/how-to-handle-file-uploads-in-node-js-beginner-guide-to-multer-c3810de38b81?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3810de38b81</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[file-upload]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 07:51:30 GMT</pubDate>
            <atom:updated>2026-02-28T07:51:30.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*RDSrbLfFDfPadysmUH3hEA.jpeg" /></figure><h4>1️⃣ First, Let’s Understand Normal Data</h4><p>When we build a backend using Node.js and Express, we usually handle normal data like:</p><ul><li>name</li><li>email</li><li>password</li><li>age</li></ul><p>This data is sent from frontend to backend in <strong>JSON format</strong>.</p><p>Example:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><p>In Express, we handle this using:</p><pre>app.use(express.json())</pre><p>Now Express can read this data using:</p><pre>req.body</pre><h4>2️⃣ But What If We Want to Upload Files?</h4><p>Now imagine we want users to upload:</p><ul><li>Profile image</li><li>Resume (PDF)</li><li>Blog thumbnail</li><li>Product image</li></ul><p>Can we send files in JSON format?</p><p>❌ No.</p><p>Because JSON is made for text data, not files.</p><p>Files like images and PDFs are binary data, not simple text.</p><p>So JSON cannot properly send them.</p><h4>3️⃣ Then How Does the Browser Send Files?</h4><p>When we upload a file using a form like this:</p><pre>&lt;form enctype=&quot;multipart/form-data&quot;&gt;<br>  &lt;input type=&quot;file&quot; name=&quot;image&quot; /&gt;<br>&lt;/form&gt;</pre><p>The browser automatically changes the request format to:</p><p>👉 <strong>multipart/form-data</strong></p><p>This is a special format designed for:</p><ul><li>Sending files</li><li>Sending form data + files together</li></ul><h3>Understanding multipart/form-data</h3><h4>1. How Data Is Usually Sent in HTTP Requests</h4><p>When the browser sends data to the server, it sends it using HTTP.</p><p>Every HTTP request has:</p><ul><li>Headers</li><li>Body</li></ul><p>The <strong>Content-Type header</strong> tells the server what kind of data is inside the body.</p><p>Example:</p><p>If we send JSON:</p><pre>Content-Type: application/json</pre><p>If we send simple form data (text only):</p><pre>Content-Type: application/x-www-form-urlencoded</pre><p>But when we upload files…</p><p>We use:</p><pre>Content-Type: multipart/form-data</pre><h4>2. Why JSON Cannot Send Files Properly</h4><p>JSON works great for text:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;age&quot;: 21<br>}</pre><p>But files like images or PDFs are not simple text.</p><p>They are <strong>binary data</strong> (raw bytes).</p><p>If we try to send files inside JSON:</p><ul><li>The file would need to be converted to base64</li><li>That increases size</li><li>It becomes inefficient</li><li>Not practical for large files</li></ul><p>So instead of converting the file into text…</p><p>The browser sends it in parts.</p><p>That’s where multipart/form-data comes in.</p><h4>3. What Does “Multipart” Mean?</h4><p>The word <strong>multipart</strong> means:</p><p>👉 The request body is divided into multiple parts.</p><p>Each part represents:</p><ul><li>A text field<br> OR</li><li>A file</li></ul><p>So instead of one big JSON object…</p><p>The body looks like multiple sections separated by boundaries.</p><h4>4. What Actually Happens When You Upload a File?</h4><p>Suppose we have this form:</p><pre>&lt;form method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt;<br>  &lt;input type=&quot;text&quot; name=&quot;username&quot; /&gt;<br>  &lt;input type=&quot;file&quot; name=&quot;profile&quot; /&gt;<br>&lt;/form&gt;</pre><p>When you submit this form:</p><h4>Step 1:</h4><p>The browser automatically:</p><ul><li>Sets the header:</li></ul><pre>Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryXYZ</pre><blockquote>⚠️ IMPORTANT:<br> You should NOT manually set this header when using frontend tools like:</blockquote><ul><li>fetch()</li><li>axios()</li><li>FormData()</li></ul><p>Because the browser automatically generates the correct boundary.</p><p>If you manually set:</p><pre>Content-Type: multipart/form-data</pre><p>Without boundary ❌</p><p>The server cannot understand how parts are separated.</p><h4>5. What Is Boundary?</h4><p>This is very important.</p><p>A <strong>boundary</strong> is a unique string used to separate each part of the form data.</p><p>Example header:</p><pre>Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryABC123</pre><p>Inside the request body, it looks like:</p><pre>------WebKitFormBoundaryABC123<br>Content-Disposition: form-data; name=&quot;username&quot;<br><br>Dipika<br>------WebKitFormBoundaryABC123<br>Content-Disposition: form-data; name=&quot;profile&quot;; filename=&quot;photo.png&quot;<br>Content-Type: image/png<br><br>(binary data of image here)<br>------WebKitFormBoundaryABC123--</pre><p>See what happened?</p><p>Each section is separated by:</p><pre>------WebKitFormBoundaryABC123</pre><p>That is the boundary.</p><p>The server reads:</p><ul><li>Start boundary</li><li>Headers of that part</li><li>Data of that part</li><li>Next boundary</li><li>Repeat</li></ul><p>That’s how it understands different parts.</p><blockquote><strong>👉 NEVER manually set </strong><strong>Content-Type when sending FormData.</strong></blockquote><h4>6. How Server Receives Multipart Data</h4><p>Now comes the backend part.</p><p>When Express receives:</p><pre>multipart/form-data</pre><p>It cannot parse it automatically.</p><p>Why?</p><p>Because:</p><ul><li>The body contains binary streams</li><li>It contains boundaries</li><li>It contains multiple headers inside body</li></ul><p>Parsing this manually is complex.</p><p>That’s why we use:</p><h4>👉 Multer</h4><p>Multer:</p><ul><li>Reads the stream</li><li>Detects boundaries</li><li>Extracts each part</li><li>Saves files</li><li>Puts text fields inside req.body</li><li>Puts file info inside req.file or req.files</li></ul><h3>🔬 How Multer Parses multipart/form-data Internally</h3><h4>1. First Important Thing: Multer Does NOT Parse Everything Alone</h4><p>Many beginners think Multer does everything itself.</p><p>Actually ❌</p><p>Multer is built on top of a package called:</p><p>👉 <strong>Busboy</strong></p><p>Busboy is the real engine that parses multipart/form-data.</p><p>Multer is like a wrapper around Busboy that makes it easy to use with:</p><p>👉 <strong>Express</strong></p><p>So internally:</p><p>Express → Multer → Busboy → Parses multipart stream</p><h4>2. What Happens When a File Upload Request Comes?</h4><p>When client sends:</p><pre>Content-Type: multipart/form-data; boundary=----XYZ</pre><p>The request body is not normal text.</p><p>It is a <strong>stream</strong>.</p><p>Important concept:</p><p>👉 Files are sent as streams, not as full data at once.</p><p>That means:</p><ul><li>Data comes in small chunks</li><li>Not all at once in memory</li></ul><p>This is very important for performance.</p><h4>3. How Multer Intercepts the Request</h4><p>When you write:</p><pre>app.post(&quot;/upload&quot;, upload.single(&quot;profile&quot;), (req, res) =&gt; {<br>   // your code<br>});</pre><p>upload.single(&quot;profile&quot;) is middleware.</p><p>So flow becomes:</p><ol><li>Request comes</li><li>Multer middleware runs FIRST</li><li>Multer reads request stream</li><li>Parses multipart data</li><li>Then passes control to your route</li></ol><h4>4. How Parsing Actually Works Internally</h4><p>Let’s understand the internal process step by step.</p><p><strong>Step A: Read Headers</strong></p><p>Busboy first reads:</p><pre>Content-Type: multipart/form-data; boundary=----XYZ</pre><p>It extracts the boundary:</p><pre>----XYZ</pre><p>This boundary tells Busboy:</p><p>👉 Where each part starts and ends.</p><p><strong>Step B: Start Reading Stream</strong></p><p>The request body is a readable stream.</p><p>Busboy listens to it like:</p><ul><li>“data” events</li><li>“file” events</li><li>“field” events</li></ul><p>As soon as it detects a boundary:</p><p>It knows a new part has started.</p><p><strong>Step C: Detect Whether It’s a File or Text Field</strong></p><p>Each part has something like:</p><pre>Content-Disposition: form-data; name=&quot;username&quot;</pre><p>OR</p><pre>Content-Disposition: form-data; name=&quot;profile&quot;; filename=&quot;photo.png&quot;<br>Content-Type: image/png</pre><p>If filename exists → it’s a file<br> If no filename → it’s a text field</p><p>Busboy checks this internally.</p><h4><strong>5. What Happens For Text Fields?</strong></h4><p>If it’s text:</p><p>Busboy collects the data.</p><p>Multer then stores it in:</p><pre>req.body</pre><p>So:</p><pre>req.body.username</pre><p>works normally.</p><h4>6. What Happens For Files?</h4><p>If it’s a file:</p><p>Busboy creates a <strong>file stream</strong>.</p><p>Now Multer decides what to do with it.</p><p>There are two main storage types:</p><ol><li>Disk Storage</li><li>Memory Storage</li></ol><h4>📦 What Is Storage in Multer?</h4><p>When a user uploads a file, Multer must decide:</p><p>👉 <strong>Where should I put this file?</strong></p><p>That decision is called <strong>Storage</strong>.</p><p>So storage means:</p><blockquote><em>How and where the uploaded file will be stored.</em></blockquote><p>Multer gives us two main storage options:</p><ol><li>Disk Storage</li><li>Memory Storage</li></ol><p><strong>1️⃣ Disk Storage (Save File in a Folder)</strong></p><p>This is the most common one.</p><p>In this case:</p><ul><li>The file is saved in your project folder</li><li>Example: /uploads folder</li></ul><p>So if user uploads:</p><pre>photo.png</pre><p>It gets saved like:</p><pre>project/<br> ├── uploads/<br>      └── abc123.png</pre><blockquote><strong>What happens internally?</strong></blockquote><p>Remember earlier we said files come as streams?</p><p>Multer:</p><ul><li>Receives file stream</li><li>Creates a write stream</li><li>Saves file chunk by chunk into a folder</li></ul><p>You don’t see this happening, but internally it’s like:</p><pre>fileStream → write into file on disk</pre><p>After saving, Multer gives you file info in:</p><pre>req.file</pre><p>So you can store the file path in database.</p><blockquote><strong>Disk Storage = User uploads file → Multer saves it physically in your computer/server → You get file path</strong></blockquote><p><strong>2️⃣ Memory Storage (Store File in RAM)</strong></p><p>In this case:</p><ul><li>The file is NOT saved in any folder</li><li>It is stored temporarily in RAM (server memory)</li></ul><p>Multer keeps the file as a <strong>Buffer</strong> inside:</p><pre>req.file.buffer</pre><p>That means:</p><p>The file exists only in memory while request is running.</p><p>After response finishes:</p><p>❌ It disappears</p><blockquote><strong>Memory Storage = User uploads file → Multer keeps it in memory → You process it → It is gone after request</strong></blockquote><h4>🚨 Important Question</h4><p>Why not always use Memory Storage?</p><p>Because:</p><p>If someone uploads:</p><ul><li>100MB file</li><li>Many users upload at same time</li></ul><p>All files will stay in RAM.</p><p>Server may crash ❌</p><p>So memory storage is used only when:</p><ul><li>File is small</li><li>You immediately send it to cloud (like S3)</li><li>You process it quickly</li></ul><h4>Internal Flow Summary</h4><pre>Client uploads file<br>↓<br>Browser creates multipart/form-data with boundary<br>↓<br>Express receives request<br>↓<br>Multer middleware intercepts<br>↓<br>Busboy reads stream<br>↓<br>Boundary separates parts<br>↓<br>Detects file or text<br>↓<br>Text → req.body<br>File → saved (disk/memory)<br>↓<br>next() called<br>↓<br>Your route runs</pre><h3>Create a file picker on the frontend</h3><p>A <strong>file picker</strong> is an input element that lets the user choose a file from their device.</p><p>In HTML, this is done using:</p><pre>&lt;input type=&quot;file&quot;&gt;</pre><p>This input opens:</p><ul><li>File explorer (Windows / Mac)</li><li>Gallery (mobile)</li></ul><p>User selects a file → browser now has access to that file.</p><h4>Important Attributes of File Input</h4><p><strong>🔹 </strong><strong>name (VERY IMPORTANT)</strong></p><p>The name attribute is the key used by backend.</p><p>Example:</p><pre>&lt;input type=&quot;file&quot; name=&quot;profileImage&quot; /&gt;</pre><p><strong>🔹 </strong><strong>accept (Optional)</strong></p><p>This restricts file type on frontend.</p><p>Example:</p><pre>&lt;input type=&quot;file&quot; accept=&quot;image/*&quot; /&gt;</pre><p>This means:</p><ul><li>User can select only images</li></ul><p>⚠️ This is NOT security.<br> It’s just for user experience.</p><p>Backend validation is still required.</p><p>✅ Only PDF</p><pre>&lt;input type=&quot;file&quot; accept=&quot;application/pdf&quot;&gt;</pre><p>✅ Only DOC &amp; DOCX</p><pre>&lt;input type=&quot;file&quot; accept=&quot;.doc,.docx&quot;&gt;</pre><p>✅ Images + PDF</p><pre>&lt;input type=&quot;file&quot; accept=&quot;image/*,application/pdf&quot;&gt;</pre><p><strong><em>⚠️ IMPORTANT:</em></strong></p><ul><li>accept is <strong>NOT security</strong></li><li>Users can still upload other files (by typing *.* or drag-drop)</li><li>Backend validation is mandatory (Multer fileFilter)</li></ul><p><strong>🔹 </strong><strong>multiple (Optional)</strong></p><p>To allow multiple files:</p><pre>&lt;input type=&quot;file&quot; name=&quot;images&quot; multiple /&gt;</pre><h3>How Files Are Sent Over Network ?</h3><p>Files are sent as:</p><ul><li>Streams of binary data</li><li>Chunk by chunk</li><li>Not as normal strings</li></ul><p>To send such data, HTTP uses:</p><p>👉 <strong>multipart/form-data</strong></p><p>And JSON does NOT support this format.</p><h4>✅ Solution: FormData</h4><p>To send files correctly, browsers provide a special object called:</p><p>👉 <strong>FormData</strong></p><p>FormData is designed to:</p><ul><li>Send text data</li><li>Send file data</li><li>Automatically use multipart/form-data</li></ul><h4><strong>What Is FormData?</strong></h4><p>FormData is like a <strong>virtual form</strong> created using JavaScript.</p><p>It works exactly like an HTML form with file inputs.</p><p>Example:</p><pre>const formData = new FormData();</pre><p>Now you can add data to it.</p><p><strong>➕ Adding Normal Text to FormData</strong></p><pre>formData.append(&quot;name&quot;, &quot;Google&quot;);<br>formData.append(&quot;location&quot;, &quot;Bangalore&quot;);</pre><p>This is similar to:</p><pre>&lt;input name=&quot;name&quot; value=&quot;Google&quot; /&gt;<br>&lt;input name=&quot;location&quot; value=&quot;Bangalore&quot; /&gt;</pre><p><strong>➕ Adding File to FormData</strong></p><pre>formData.append(&quot;companyLogo&quot;, companyFormData.companyLogo);</pre><p>Here:</p><ul><li>companyFormData.companyLogo is a File object</li><li>Browser knows it is a file</li><li>Browser sends it as binary data</li></ul><h4>What FormData Looks Like Internally</h4><p>Internally, the browser converts FormData into:</p><pre>multipart/form-data</pre><p>With:</p><ul><li>Boundaries</li><li>Separate parts</li><li>File metadata</li><li>Binary file content</li></ul><p>You don’t have to do anything manually.</p><h3>Installing and Setting Up Multer</h3><p>Before we upload files, we need a tool that can <strong>understand </strong><strong>multipart/form-data</strong> and handle files.</p><p>That tool is <strong>Multer</strong>.</p><p>Multer works with:</p><ul><li>Node.js</li><li>Express</li></ul><h4>1. What Is Multer</h4><p>Multer is a <strong>middleware</strong>.</p><p>Middleware means:</p><blockquote><em>Code that runs </em><strong><em>before</em></strong><em> your API logic.</em></blockquote><p>Multer’s job is to:</p><ul><li>Read multipart/form-data</li><li>Extract files</li><li>Save files (or keep them in memory)</li><li>Make files available as req.file or req.files</li></ul><p>Without Multer:<br> ❌ Express cannot read uploaded files.</p><h4>2. Installing Multer</h4><p>Inside your backend project folder, run:</p><pre>npm install multer</pre><p>That’s it.</p><h4>3. Basic Folder Structure</h4><p>Before writing code, create a folder to store uploaded files.</p><pre>project/<br> ├── uploads/<br> ├── routes/<br> ├── controllers/<br> ├── server.js</pre><p>👉 uploads/ is where Multer will save files (disk storage).</p><h4>4. Create a Separate Multer Config File</h4><pre>backend/<br> ├── config/<br> │    └── multer.js<br> ├── uploads/<br> ├── routes/<br> ├── controllers/<br> └── server.js</pre><p>👉 We will write <strong>all Multer logic</strong> inside config/multer.js.</p><h4>5. Open config/multer.js</h4><pre>import multer from &quot;multer&quot;</pre><p>Before writing code, understand this sentence 👇</p><blockquote><strong><em>diskStorage means: save uploaded files inside a folder on the server</em></strong></blockquote><p>So Multer needs answers to <strong>two questions</strong>:</p><ol><li>❓ WHERE should I save the file?</li><li>❓ WHAT should be the file name?</li></ol><p>That’s all.</p><h4>6. Create Storage</h4><pre>const storage = multer.diskStorage({<br>  destination: function (req, file, cb) {<br>    cb(null, &quot;uploads/&quot;);<br>  },<br>  filename: function (req, file, cb) {<br>    cb(null, Date.now() + &quot;-&quot; + file.originalname);<br>  },<br>});</pre><p>🔹<strong>multer.diskStorage({})</strong></p><pre>multer.diskStorag({ .... })</pre><p>🧠 Meaning:</p><blockquote><em>“Multer, I want to store files on disk (folder), not in memory.”</em></blockquote><p><strong>🔹 </strong><strong>destination (WHERE to save file)</strong></p><pre>destination: function (req, file, cb) {<br>  cb(null, &quot;uploads/&quot;);<br>}</pre><p>It tells Multer <strong>which folder</strong> to save the file in.</p><p><strong>❓ What is </strong><strong>file?</strong></p><p>It contains file info like:</p><ul><li>original name</li><li>type (image/png)</li><li>size</li></ul><p><strong>❓ What is </strong><strong>cb?</strong></p><p>cb = <strong>callback function</strong></p><p><strong>❗ MOST IMPORTANT LINE</strong></p><pre>cb(null, &quot;uploads/&quot;);</pre><blockquote><em>“There is NO error, and save file inside </em><em>uploads/ folder.”</em></blockquote><ul><li>null → no error</li><li>&quot;uploads/&quot; → folder name</li></ul><p><strong>🔹 </strong><strong>filename (WHAT name to give file)</strong></p><pre>filename: function (req, file, cb) {<br>  cb(null, Date.now() + &quot;-&quot; + file.originalname);<br>}</pre><p><strong>❓ Why do we need this?</strong></p><p>If two users upload:</p><pre>logo.png<br>logo.png</pre><p>One file will overwrite the other ❌</p><p>So we make name <strong>unique</strong>.</p><p><strong>❓ </strong><strong>file.originalname?</strong></p><p>This is the <strong>original file name from user’s computer</strong>.</p><p>Example:</p><pre>logo.png</pre><p><strong>❓ </strong><strong>Date.now()?</strong></p><p>It gives current timestamp:</p><pre>1697049123456</pre><p><strong>❗ Final filename becomes:</strong></p><pre>1697049123456-logo.png</pre><p>And this is what gets saved.</p><h4>7. Create Multer Upload Middleware</h4><p>Now connect storage to Multer.</p><pre>const upload = multer({ storage })<br>export default upload</pre><p>🧠 Meaning:</p><blockquote><em>“Multer, use THIS storage rule when handling files.”</em></blockquote><p>This upload is what we will use in routes.</p><h4>8. Use This in Route</h4><p>In your route file:</p><pre>import upload from &quot;../config/multer.js&quot;;</pre><p>Then :</p><pre>router.post(<br>  &quot;/create&quot;,<br>  upload.single(&quot;companyLogo&quot;),<br>  createCompany<br>);</pre><p>🧠 Meaning of upload.single(&quot;companyLogo&quot;):</p><blockquote><em>“Accept ONLY ONE file with name </em><em>companyLogo.”</em></blockquote><p>This must match frontend:</p><pre>formData.append(&quot;companyLogo&quot;, file);</pre><h3>Upload Files to Cloudinary using Multer</h3><h4>WHY Cloudinary?</h4><p>Problems with local uploads/ folder:</p><ul><li>Files deleted if server restarts</li><li>Not scalable</li><li>Not CDN optimized</li></ul><p>Cloudinary gives:</p><ul><li>✅ Permanent storage</li><li>✅ Image optimization</li><li>✅ CDN URLs</li><li>✅ Free tier</li></ul><h4>STEP 1: Create Cloudinary Account</h4><ol><li>Go to cloudinary.com</li><li>Sign up (free)</li><li>Open <strong>Dashboard</strong></li><li>Copy these 3 values:</li></ol><pre>Cloud name<br>API Key<br>API Secret</pre><h4>STEP 2: Install Cloudinary SDK ( backend)</h4><pre>npm install cloudinary</pre><h4>STEP 3: Setup Cloudinary Config</h4><p>Create file:</p><pre>backend/<br> ├── config/<br> │    ├── multer.js<br> │    └── cloudinary.js</pre><p>config/cloudinary.js</p><pre>import { v2 as cloudinary } from &quot;cloudinary&quot;;<br><br>cloudinary.config({<br>  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,<br>  api_key: process.env.CLOUDINARY_API_KEY,<br>  api_secret: process.env.CLOUDINARY_API_SECRET,<br>});<br><br>export default cloudinary;</pre><h4>STEP 4: Add Environment Variables</h4><p>In .env:</p><pre>CLOUDINARY_CLOUD_NAME=xxxx<br>CLOUDINARY_API_KEY=xxxx<br>CLOUDINARY_API_SECRET=xxxx</pre><p><strong>⚠️ Never push </strong><strong>.env to GitHub</strong></p><h4>STEP 5: Upload File to Cloudinary (Controller)</h4><p>Now Multer already gives you:</p><pre>req.file.path</pre><p>That path is the <strong>local file</strong>, which we send to Cloudinary.</p><p>Example: controllers/companyController.js</p><pre>import cloudinary from &quot;../config/cloudinary.js&quot;;<br><br>export const createCompany = async (req, res) =&gt; {<br>  try {<br>    if (!req.file) {<br>      return res.status(400).json({ message: &quot;Logo is required&quot; });<br>    }<br><br>    // Upload to Cloudinary<br>    const result = await cloudinary.uploader.upload(req.file.path, {<br>      folder: &quot;company_logos&quot;,<br>    });<br><br>    // Cloudinary image URL<br>    const logoUrl = result.secure_url;<br><br>    res.status(201).json({<br>      message: &quot;Company created&quot;,<br>      logo: logoUrl,<br>    });<br>  } catch (error) {<br>    res.status(500).json({ error: error.message });<br>  }<br>};</pre><h4>STEP 6: Route</h4><pre>router.post(<br>  &quot;/create&quot;,<br>  upload.single(&quot;companyLogo&quot;),<br>  createCompany<br>);</pre><h4>STEP 7: Frontend Must Match</h4><pre>const formData = new FormData();<br>formData.append(&quot;companyLogo&quot;, file);</pre><h4>🔁 FULL FLOW</h4><pre>Frontend FormData<br>        ↓<br>Multer → saves file temporarily (uploads/)<br>        ↓<br>Controller → uploads file to Cloudinary<br>        ↓<br>Cloudinary → returns image URL<br>        ↓<br>Save URL in database</pre><h3>Deleting Local files</h3><p>When using Multer + Cloudinary, the flow is:</p><pre>Upload → Save temporarily → Upload to Cloudinary → DONE</pre><p>After Cloudinary upload:</p><ul><li>Keeping files locally wastes disk space</li><li>Server storage fills quickly</li></ul><p>So we <strong>delete the local file after successful Cloudinary upload</strong>.</p><h4><strong>Delete Local File After Cloudinary Upload</strong></h4><p>Node.js provides a built-in module called fs (file system).</p><ol><li><strong>Import fs</strong></li></ol><pre>import fs from &quot;fs&quot;;</pre><p>2. Update Controller example</p><pre>import cloudinary from &quot;../config/cloudinary.js&quot;;<br>import fs from &quot;fs&quot;;<br><br>export const createCompany = async (req, res) =&gt; {<br>  try {<br>    if (!req.file) {<br>      return res.status(400).json({ message: &quot;Logo is required&quot; });<br>    }<br><br>    // Upload to Cloudinary<br>    const result = await cloudinary.uploader.upload(req.file.path, {<br>      folder: &quot;company_logos&quot;,<br>    });<br><br>    // Delete local file after upload<br>    fs.unlinkSync(req.file.path);<br><br>    res.status(201).json({<br>      message: &quot;Company created&quot;,<br>      logo: result.secure_url,<br>    });<br>  } catch (error) {<br>    res.status(500).json({ error: error.message });<br>  }<br>};</pre><p><strong>What </strong><strong>fs.unlinkSync() Does</strong></p><p>Meaning:</p><ul><li>❌ Remove file from uploads/ folder</li><li>✅ File still exists safely on Cloudinary</li></ul><h3>Deleting Files From Cloudinary</h3><p>Cloudinary does <strong>NOT delete by URL</strong>.<br> It deletes using <strong>public_id</strong>.</p><p>Example public_id:</p><pre>company_logos/1697049123456-logo</pre><p><strong>Save public_id in Database</strong></p><p>When uploading:</p><pre>const result = await cloudinary.uploader.upload(req.file.path, {<br>  folder: &quot;company_logos&quot;,<br>});<br><br>const logoData = {<br>  url: result.secure_url,<br>  public_id: result.public_id,<br>};</pre><p>👉 <strong>Always store both</strong>:</p><ul><li>secure_url</li><li>public_id</li></ul><h4>Delete Image From Cloudinary</h4><pre>await cloudinary.uploader.destroy(public_id);</pre><p>Example: Delete Company Logo</p><pre>export const deleteCompanyLogo = async (req, res) =&gt; {<br>  try {<br>    const { public_id } = req.body;<br><br>    await cloudinary.uploader.destroy(public_id);<br><br>    res.status(200).json({ message: &quot;Image deleted from Cloudinary&quot; });<br>  } catch (error) {<br>    res.status(500).json({ error: error.message });<br>  }<br>};</pre><h3>Adding File Size Limits</h3><p>Without limits:</p><ul><li>Users can upload 500MB files</li><li>Server can crash</li></ul><h4>Add Size Limit in Multer Config</h4><p><strong>config/multer.js</strong></p><pre>import multer from &quot;multer&quot;;<br><br>const storage = multer.diskStorage({<br>  destination: (req, file, cb) =&gt; {<br>    cb(null, &quot;uploads/&quot;);<br>  },<br>  filename: (req, file, cb) =&gt; {<br>    cb(null, Date.now() + &quot;-&quot; + file.originalname);<br>  },<br>});<br><br>const upload = multer({<br>  storage,<br>  limits: {<br>    fileSize: 2 * 1024 * 1024, // 2 MB<br>  },<br>});<br><br>export default upload;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3810de38b81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Server and Client Components in Next.js]]></title>
            <link>https://medium.com/@dipikagandash411/understanding-server-and-client-components-in-next-js-7866c957218c?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/7866c957218c</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 10:10:11 GMT</pubDate>
            <atom:updated>2026-02-10T10:10:11.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*EkFFJxooUDOELc-uSTWh-A.jpeg" /></figure><p>Imagine opening a website on a slow network.<br> At first, the screen is completely blank. You wait. After a few seconds, the layout appears. A moment later, buttons start working. Until then, clicking does nothing.</p><p>From the user’s point of view, the site feels slow — even though technically nothing is broken.</p><p>This is the core problem modern web frameworks try to solve: <strong>show something as early as possible, and make it interactive as soon as possible</strong>.</p><p>For a long time, web apps relied heavily on the browser to do everything. The server sent JavaScript, the browser executed it, and only then did the page appear. This approach worked, but it delayed the first visible content and pushed a lot of work onto the client.</p><p>Next.js approaches this differently. Instead of choosing between server rendering and client rendering, it splits the responsibility. Some components render on the server to deliver content quickly, while others run in the browser to handle interaction. These are known as <strong>Server Components</strong> and <strong>Client Components</strong>.</p><p>Understanding how these two types of components work together is key to understanding modern Next.js rendering.</p><h3>Why Server and Client Components Exist</h3><p>Modern web applications have two very different requirements.</p><p>First, they need to <strong>show content as fast as possible</strong>. Users should not stare at a blank screen while JavaScript downloads and executes. Search engines also need readable HTML to index pages correctly.</p><p>Second, applications need to be <strong>interactive</strong>. Buttons must respond to clicks, forms must update in real time, and UI state must change without reloading the page.</p><p>Trying to solve both problems using only client-side rendering creates trade-offs. When everything runs in the browser, the page cannot display meaningful content until JavaScript is fully loaded. This delays the First Contentful Paint and makes the application feel slow, especially on low-end devices or poor networks.</p><p>Server rendering improves this by generating HTML on the server and sending it directly to the browser. The page becomes visible quickly, but interactivity still requires JavaScript to load and attach event handlers later.</p><p>Next.js formalizes this split by introducing <strong>Server Components</strong> and <strong>Client Components</strong>.</p><p>Server Components focus on <strong>rendering content early</strong>. They run on the server, fetch data securely, and stream HTML to the client. This improves performance and reduces the amount of JavaScript sent to the browser.</p><p>Client Components focus on <strong>interaction</strong>. They run in the browser, manage state, respond to user actions, and make the UI dynamic.</p><p>By separating these responsibilities, Next.js allows applications to be both fast and interactive without forcing everything to run on the client.</p><h3>What is a Server Component?</h3><p>A <strong>Server Component</strong> is a React component that runs <strong>only on the server</strong>.</p><p>It does not run in the browser.<br> It does not send its JavaScript to the client.<br> It only sends <strong>rendered HTML</strong>.</p><p>In Next.js (App Router), <strong>every component is a Server Component by default</strong> unless you explicitly mark it as a Client Component.</p><h4>What happens when a Server Component renders?</h4><p>Imagine you open this URL:</p><pre>/blog</pre><p>You press Enter in the browser.</p><p><strong>🧠 What you THINK happens (but doesn’t)</strong></p><p>You might think:</p><blockquote><em>“The browser runs my React code and creates the page.”</em></blockquote><p>That is <strong>NOT</strong> what happens with <strong>Server Components</strong>.</p><h4>What ACTUALLY happens:</h4><p><strong>Step 1: Request reaches the server</strong></p><p>Your browser sends:</p><pre>GET /blog</pre><p>Nothing React-related happens in the browser yet.</p><p><strong>Step 2: Server Component executes</strong></p><p>On the <strong>server machine</strong>:</p><pre>export default async function Page() {<br>  const posts = await getPostsFromDB();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Blog&lt;/h1&gt;<br>      {posts.map(p =&gt; &lt;p key={p.id}&gt;{p.title}&lt;/p&gt;)}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Here’s what this means:</p><ul><li>This function runs <strong>like normal Node.js code</strong></li><li>getPostsFromDB() runs on the server</li><li>Database credentials stay on the server</li><li>No browser involved yet</li></ul><p>Think of it like:</p><blockquote><em>The server is “pre-building” the page.</em></blockquote><p><strong>Step 3: HTML is created</strong></p><p>React on the server turns your JSX into HTML:</p><pre>&lt;div&gt;<br>  &lt;h1&gt;Blog&lt;/h1&gt;<br>  &lt;p&gt;Post one&lt;/p&gt;<br>  &lt;p&gt;Post two&lt;/p&gt;<br>&lt;/div&gt;</pre><p><strong>Step 4: HTML is streamed (not sent all at once)</strong></p><p>This is important.</p><p>Instead of:</p><blockquote><em>“Wait until everything is ready, then send the page”</em></blockquote><p>The server does:</p><blockquote><em>“Send what’s ready right now.”</em></blockquote><p>So:</p><ul><li>&lt;h1&gt;Blog&lt;/h1&gt; may arrive first</li><li>Posts may arrive slightly later</li></ul><p>The browser <strong>does not wait</strong>.</p><p><strong>Step 5: Browser paints immediately</strong></p><p>The moment the browser receives HTML:</p><ul><li>It renders it</li><li>Text appears on screen</li><li>Layout becomes visible</li></ul><p>This is <strong>First Contentful Paint (FCP)</strong>.</p><p>At this moment:</p><ul><li>You can <strong>see</strong> the page</li><li>But you <strong>cannot interact</strong> yet</li></ul><h4>❓ Why is it “not interactive”?</h4><p>Because:</p><ul><li>No JavaScript has run in the browser yet</li><li>No event listeners exist</li><li>Buttons are just HTML</li></ul><pre>&lt;button&gt;Like&lt;/button&gt;</pre><p>It <em>looks</em> clickable<br> But clicking does nothing.</p><blockquote><strong><em>Server Components finish their job once HTML is sent. They never run again in the browser.</em></strong></blockquote><p>That’s why:</p><ul><li>No onClick</li><li>No state</li><li>No effects</li></ul><h4>What Server Components are good at</h4><p>Server Components are ideal for:</p><ul><li>Rendering static content</li><li>Fetching data from databases</li><li>Calling internal APIs</li><li>Accessing environment variables and secrets</li><li>Improving performance and SEO</li></ul><p>Because everything runs on the server, sensitive logic never reaches the browser.</p><h4>What Server Components cannot do</h4><p>Server Components <strong>cannot</strong>:</p><ul><li>Use useState, useEffect, or other client-side hooks</li><li>Handle browser events like onClick or onChange</li><li>Access browser APIs like window, document, or localStorage</li><li>Store UI state or react to user interaction</li></ul><p>Once the HTML is sent, the server component’s job is finished.</p><h4>Why Server Components matter</h4><p>Server Components help Next.js apps:</p><ul><li>Load faster</li><li>Send less JavaScript</li><li>Improve SEO</li><li>Scale better</li><li>Keep secrets safe</li></ul><p>They shift work away from the browser and onto the server.</p><h3>What is a Client Component?</h3><p>A <strong>Client Component</strong> is a React component that:</p><ul><li>Runs <strong>in the browser</strong></li><li>Can handle <strong>clicks, input, state, effects</strong></li><li>Can use <strong>hooks</strong> like useState, useEffect</li><li>Makes the page <strong>interactive</strong></li></ul><p>👉 If a component needs <strong>user interaction</strong>, it <strong>must</strong> be a Client Component.</p><h4>Why do Client Components exist in Next.js?</h4><p>Next.js (App Router) has <strong>Server Components by default</strong>.</p><p>Server Components are:</p><ul><li>Fast</li><li>Secure</li><li>Good for data + HTML</li></ul><p>But…</p><p>❌ Server Components <strong>cannot</strong>:</p><ul><li>Handle onClick</li><li>Use useState</li><li>Use useEffect</li><li>Access window, document</li><li>Respond to user actions</li></ul><p>So Next.js said:</p><blockquote><em>“Okay, for interaction — let’s send some React to the browser.”</em></blockquote><p>That React-in-the-browser part is a <strong>Client Component</strong>.</p><h4>How do you tell Next.js: “This is a Client Component”?</h4><p>With <strong>one line</strong> at the top:</p><pre>&quot;use client&quot;;</pre><h4>What &#39;use client&#39; REALLY does</h4><p>This line:</p><pre>&#39;use client&#39;;</pre><p>Means:</p><blockquote><em>“Hey Next.js, send this component’s JavaScript to the browser and keep it alive there.”</em></blockquote><p>Without it:</p><ul><li>No JS in browser</li><li>No interactivity</li></ul><p>With it:</p><ul><li>JS is downloaded</li><li>React attaches event listeners</li><li>Component becomes interactive</li></ul><h4>What actually happens when a Client Component renders?</h4><p><strong>Step 1: Request comes in</strong></p><pre>http://localhost:3000</pre><p><strong>Step 2: Server runs first</strong></p><p>Even <strong>Client Components</strong> are <strong>first rendered on the server</strong>.</p><p>So initially:</p><ul><li>Server runs the component</li><li>Creates HTML</li><li>Sends HTML to browser</li></ul><p>This is why the page appears fast.</p><p><strong>Step 3: Browser shows the HTML</strong></p><p>At this point:</p><ul><li>You can <strong>see the page</strong></li><li>But buttons <strong>do nothing</strong></li><li>Inputs don’t respond yet</li></ul><blockquote><em>“page is visible but not interactive”</em></blockquote><p><strong>Step 4: JavaScript loads in the browser</strong></p><p>Now the browser downloads:</p><ul><li>React</li><li>Client Component JS</li></ul><p>Then React does <strong>hydration</strong></p><p><strong>Step 5: Hydration happens</strong></p><p>Hydration means:</p><blockquote><em>“React connects JavaScript logic to the existing HTML.”</em></blockquote><p>After hydration:</p><ul><li>onClick works</li><li>useState works</li><li>Inputs respond</li><li>Page becomes interactive</li></ul><p>✅ <strong>NOW it feels like a real React app</strong></p><blockquote>Server Component = HTML only</blockquote><blockquote>Client Component = HTML + JavaScript logic</blockquote><h3>Import Rules in Next.js (Server vs Client Components)</h3><h4>Can a Server Component import a Client Component?</h4><p>YES — this is allowed (and very common)</p><pre>// page.js (Server Component by default)<br>import Header from &quot;./Header&quot;;<br><br>export default function Page() {<br>  return (<br>    &lt;&gt;<br>      &lt;Header /&gt;<br>      &lt;main&gt;Content&lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>// Header.js<br>&quot;use client&quot;;<br><br>export default function Header() {<br>  return &lt;button&gt;Menu&lt;/button&gt;;<br>}</pre><p><strong>What actually happens?</strong></p><ul><li>The <strong>Server Component</strong> renders first</li><li>It outputs HTML</li><li>When it reaches a <strong>Client Component</strong>, Next.js:</li><li>Marks that part as interactive</li><li>Sends its JavaScript to the browser</li><li>The browser hydrates <strong>only that part</strong></li></ul><p>👉 This is the <strong>recommended pattern</strong>.</p><h4>Can a Client Component import a Server Component?</h4><p>❌ NO — this is not allowed</p><pre>// ClientComponent.js<br>&quot;use client&quot;;<br>import ServerComponent from &quot;./ServerComponent&quot;; ❌</pre><h4>Why is this forbidden?</h4><p>Because:</p><ul><li>Client Components run in the <strong>browser</strong></li><li>Server Components run <strong>only on the server</strong></li><li>Browser <strong>cannot execute server-only code</strong></li><li>Server Components may: Access databases, Use secrets, Fetch private data</li></ul><p>👉 Letting client import server would be a <strong>security risk</strong>.</p><h4>Why layout.js should NOT use &quot;use client&quot;</h4><p>This is <strong>very important</strong> and commonly misunderstood.</p><p><strong>layout.js is special</strong></p><p>It:</p><ul><li>Wraps your entire app</li><li>Controls:</li><li>&lt;html&gt;</li><li>&lt;body&gt;</li><li>metadata</li><li>SEO</li><li>fonts</li></ul><p>If you add &quot;use client&quot; to layout.js:</p><p>❌ Metadata breaks<br> ❌ Whole app becomes client-rendered<br> ❌ JavaScript bundle explodes<br> ❌ SEO benefits reduce</p><p>That’s why Next.js <strong>does not allow metadata in Client Components</strong>.</p><h4>Why metadata works only in Server Components</h4><p>Metadata:</p><ul><li>Runs on the server</li><li>Is used to generate &lt;head&gt;</li><li>Needs to be available <strong>before</strong> HTML is sent</li></ul><p>Client Components:</p><ul><li>Run after page loads</li><li>Too late for SEO</li></ul><h3>Hydration: How HTML Becomes Interactive</h3><p>When a page is loaded in Next.js, the HTML is rendered on the server and sent to the browser. This allows the browser to display content immediately.</p><p>However, at this stage, the page is <strong>not interactive</strong>.</p><p>Hydration is the process where React attaches JavaScript behavior to this already-rendered HTML in the browser.</p><h4>What happens during hydration?</h4><ol><li>The server renders the page and sends HTML to the browser</li><li>The browser paints the HTML immediately</li><li>JavaScript for Client Components is downloaded</li><li>React connects event handlers and state to the existing HTML</li><li>The page becomes fully interactive</li></ol><p>Before hydration:</p><ul><li>Buttons are visible but do nothing</li><li>Forms appear but don’t respond</li></ul><p>After hydration:</p><ul><li>onClick, onChange work</li><li>State updates trigger re-renders</li><li>The app behaves like a normal React app</li></ul><p>Important to note:</p><blockquote><em>Hydration does not recreate the HTML.</em></blockquote><blockquote>It reuses the existing HTML and attaches logic to it.</blockquote><h3>What is FCP (First Contentful Paint)?</h3><p>First Contentful Paint (FCP) is the moment when the browser displays the first meaningful content on the screen.</p><p>This can be:</p><ul><li>Text</li><li>Images</li><li>Layout elements</li><li>Any visible UI that tells the user the page is loading</li></ul><p>FCP is a performance metric that focuses on <strong>how fast users see content</strong>, not how fast JavaScript finishes loading.</p><p>A page that shows content quickly feels faster, even if interactivity comes slightly later.</p><h4>How Server Components Improve FCP</h4><p>Server Components render HTML on the server and send it directly to the browser.</p><p>Because of this:</p><ul><li>The browser does not wait for JavaScript</li><li>Content is painted immediately</li><li>FCP happens very early</li></ul><p>This is one of the biggest advantages of Server Components.</p><blockquote><em>Server Components improve FCP by allowing the browser to paint HTML immediately without waiting for JavaScript execution.</em></blockquote><h4>Hydration Does Not Block FCP</h4><p>Hydration happens <strong>after</strong> the content is already visible.</p><p>This means:</p><ul><li>FCP occurs first</li><li>Hydration runs later</li><li>Interactivity is added progressively</li></ul><p>Next.js prioritizes:</p><ol><li>Showing content as fast as possible</li><li>Adding interactivity afterward</li></ol><p>This results in a faster perceived experience for users.</p><h3>Conclusion</h3><p>Next.js splits components into <strong>Server</strong> and <strong>Client Components</strong>.</p><ul><li><strong>Server Components</strong> render HTML on the server, fetch data securely, and improve performance and SEO.</li><li><strong>Client Components</strong> run in the browser, handle interactivity, and hydrate after the server-rendered HTML.</li></ul><p>Use Server Components for static content and data fetching, and Client Components only where interactivity is needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7866c957218c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js for Beginners: How App Router, layout.js and page.js Work]]></title>
            <link>https://medium.com/@dipikagandash411/next-js-for-beginners-how-app-router-layout-js-and-page-js-work-fc39cf05992a?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc39cf05992a</guid>
            <category><![CDATA[file-based-routing]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 16:52:16 GMT</pubDate>
            <atom:updated>2026-02-01T16:52:16.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*-W0ZsrupDbp5hfl5G__XhA.jpeg" /></figure><p>I recently started learning Next.js and got confused about App Router, layout.js, page.js, and server rendering. In this blog, I’ll explain these concepts in very simple terms — exactly how I understood them as a beginner. If you know basic React and are starting with Next.js, this blog is for you.</p><h3>React vs Next.js (quick difference)</h3><p>In a normal React app:</p><ul><li>We have index.html</li><li>We have main.jsx</li><li>main.jsx renders everything into index.html</li><li>Routing is handled using React Router</li><li>Everything mostly runs in the browser</li></ul><p>In Next.js (App Router):</p><ul><li>There is no index.html</li><li>There is no main.jsx</li><li>Routing is based on folders inside the app directory</li><li>page.js becomes a route automatically</li><li>layout.js works like a wrapper (similar to main file)</li><li>Next.js also renders pages on the server</li></ul><p>At first this feels confusing, but once you understand App Router, it becomes simple.</p><h3>What is Next.js App Router?</h3><p>In Next.js, routing is controlled by the app folder.</p><p>Whatever folders you create inside app automatically become URLs.</p><p>Example:</p><pre>app/page.js        →  /<br>app/about/page.js →  /about</pre><p>So instead of using React Router, Next.js uses folder-based routing.</p><p>Important files:</p><ul><li>page.js → this is the actual page UI</li><li>layout.js → this wraps pages</li><li>app folder → controls routing</li></ul><p>So simply:</p><ul><li>Folder = route</li><li>page.js = content of that route</li><li>layout.js = common wrapper</li></ul><p>That’s App Router.</p><h3>page.js in Next.js (App Router)</h3><p>In Next.js (App Router), <strong>page.js is the most important file</strong>.</p><p>👉 Without page.js, a route <strong>does not exist</strong>.</p><p>Next.js uses <strong>file-based routing</strong>, which means:</p><ul><li>Folders = URL paths</li><li>page.js = actual page shown in browser</li></ul><p>So whenever you create a new page in your app, you <strong>must</strong> create a file named:</p><pre>page.js</pre><p>⚠️ The name must be exactly page.js (lowercase).</p><p>Not Page.js<br> Not pages.js<br> Not home.js</p><p>If the name is wrong → Next.js will ignore it.</p><h4>What is page.js?</h4><p>page.js is a <strong>React Server Component</strong> by default.</p><p>It represents a <strong>single route/page</strong> in your application.</p><p>Whatever JSX you return from page.js becomes the UI for that URL.</p><p>Example:</p><pre>export default function Home() {<br>  return &lt;h1&gt;Hello World&lt;/h1&gt;;<br>}</pre><p>This automatically becomes:</p><pre>http://localhost:3000/</pre><p>No routing config needed.<br> No React Router.<br> No extra setup.</p><h3>📁 How Routing Works with page.js</h3><p>Next.js creates routes based on folders.</p><p><strong>Example structure:</strong></p><pre>app/<br> ├── page.js<br> ├── about/<br> │    └── page.js<br> └── blog/<br>      └── page.js</pre><p>Result:</p><pre>Folder Path               URL<br>app/page.js                /<br>app/about/page.js          /about<br>app/blog/page.js           /blog</pre><p>So:</p><p>👉 Each folder becomes a route<br> 👉 Each route must contain page.js</p><h4>🧠 Important Rule</h4><p>A folder is NOT a route unless it has page.js.</p><p>Example:</p><pre>app/contact/</pre><p>This alone does NOTHING.</p><p>But:</p><pre>app/contact/page.js</pre><p>Now /contact works.</p><h3>✨ Creating Nested Routes</h3><p>You can go deep.</p><pre>app/dashboard/settings/page.js</pre><p>URL becomes:</p><pre>/dashboard/settings</pre><p>No extra configuration.</p><p>Just folders + page.js.</p><h4>Example: Creating a Profile Page</h4><p><strong>Step 1: Create folder</strong></p><pre>app/profile/</pre><p><strong>Step 2: Create page.js</strong></p><pre>app/profile/page.js</pre><p><strong>Step 3: Add component</strong></p><pre>export default function Profile() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Profile Page&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now visit:</p><pre>localhost:3000/profile</pre><p>done.</p><blockquote><strong>⚡ page.js Must Export Default Component</strong></blockquote><p>This is required:</p><pre>export default function Page() {}</pre><p>If you don’t export default → Next.js throws error.</p><h3>What is layout.js ?</h3><p>When we come from React, we usually have two important files:</p><ul><li>index.html</li><li>main.jsx</li></ul><p>main.jsx is where everything starts.<br> We wrap our &lt;App /&gt; there and render it into index.html.</p><p>So basically:</p><p>👉 main.jsx is the root of the app.</p><p>In Next.js (App Router), there is NO index.html and NO main.jsx.</p><p>Instead, Next.js uses layout.js.</p><p>So you can think of:</p><p>👉 layout.js = root file of your app.</p><p>But there is one difference:</p><p>In Next.js, layouts can exist at multiple levels (not just one root).</p><p>That’s why it is called <strong>layout</strong> and not main.</p><h4>Why it must be named layout.js</h4><p>In Next.js <strong>App Router (</strong><strong>app/ folder)</strong>:</p><ul><li>Next.js <strong>automatically looks for a file named </strong><strong>layout.js</strong> in each folder.</li><li>This is <strong>not arbitrary</strong> — the framework uses this name to know:</li></ul><p>-&gt; “Okay, this folder has a layout. Wrap all pages inside this folder with it.”</p><ul><li>The file must <strong>export a React component</strong> as default and accept { children }.</li></ul><h4>What happens if you rename it?</h4><ul><li>If you rename layout.js to main.js or app.js:</li></ul><pre>app/<br>├─ main.js<br>├─ page.js</pre><ul><li>Next.js will <strong>ignore it completely</strong>.</li><li>The homepage page.js will render <strong>without any layout</strong>.</li><li>You will <strong>not see Navbar/Footer or any shared structure</strong>, because Next.js <strong>only looks for </strong><strong>layout.js</strong>.</li></ul><h3>How layout.js works</h3><p>Basic example:</p><pre>export default function RootLayout({ children }) {<br>  return (<br>    &lt;html&gt;<br>      &lt;body&gt;<br>        {children}<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Now line by line:</p><p><strong>export default function RootLayout({ children })</strong></p><p>This is just a normal React component.</p><p>The name RootLayout is NOT important.</p><p>You can name it anything:</p><pre>export default function MyLayout()</pre><p>It will still work.</p><p>Next.js only cares about the filename: layout.js.</p><p>We export it because Next.js needs to use this component.</p><p><strong>What is </strong><strong>{children}?</strong></p><p>children means:</p><p>👉 Whatever page is currently active.</p><p>You do NOT import pages.</p><p>Next.js automatically puts the current page.js inside {children}.</p><p>Example:</p><p>If user visits /about:</p><ul><li>Next.js loads about/page.js</li><li>Then injects it into {children}</li></ul><p>So:</p><pre>{children}</pre><p>means:</p><p>👉 “Put the current page here.”</p><p>That’s it.</p><p><strong>Why </strong><strong>&lt;html&gt; and </strong><strong>&lt;body&gt; here?</strong></p><p>Because Next.js does not use index.html.</p><p>So layout.js becomes responsible for creating HTML structure.</p><p>This:</p><pre>&lt;html&gt;<br>  &lt;body&gt;</pre><p>is literally replacing index.html.</p><p>You must only write this in the root layout (app/layout.js).</p><p>If you create layouts inside folders (like about/layout.js), you do NOT write html/body again.</p><p><strong>metadata</strong></p><p>You may see</p><pre>export const metadata = {<br>  title: &quot;My App&quot;,<br>  description: &quot;Next.js app&quot;<br>};</pre><p>This is for SEO.</p><p>Next.js uses this to automatically set:</p><ul><li>Page title</li><li>Meta description</li></ul><p>We export it so Next.js can read it.</p><p>It is optional.</p><h3>Shared layouts</h3><p>You can also create layouts inside folders.</p><p>Example:</p><pre>app/layout.js<br>app/dashboard/layout.js<br>app/dashboard/page.js</pre><p>Here:</p><ul><li>Root layout wraps everything</li><li>Dashboard layout wraps only dashboard pages</li></ul><p>This is called nested layouts.</p><p>So:</p><ul><li>Navbar can be global</li><li>Sidebar only for dashboard</li></ul><p>This is powerful.</p><h3>React Rendering vs Next.js Server Rendering</h3><p>This is one of the biggest differences between React and Next.js.</p><h4>In a normal React app</h4><p>Flow looks like this:</p><ol><li>Browser requests the website</li><li>Server sends almost empty HTML</li><li>Browser downloads JavaScript</li><li>React runs in the browser</li><li>React builds the UI</li><li>Finally user sees the page</li></ol><p>So React apps depend mostly on the <strong>browser</strong> to create the page.</p><p>That’s why:</p><ul><li>First load feels slow sometimes</li><li>You may see white screen while JS loads</li><li>SEO is weaker (search engines get empty HTML)</li></ul><p>So simply:</p><p>👉 React builds UI in the browser.</p><h4>In Next.js (Server Rendering)</h4><p>Flow is different:</p><ol><li>Browser requests a page</li><li>Next.js server runs your React code</li><li>Server builds HTML</li><li>Server sends ready HTML to browser</li><li>Browser shows content immediately</li><li>JavaScript loads after that for interactivity</li></ol><p>So:</p><p>👉 Next.js builds HTML on the server first.</p><p>This is called <strong>Server Rendering</strong>.</p><h4>Why this is better?</h4><p>Because:</p><ul><li>User sees content faster</li><li>No blank white screen</li><li>Search engines see real content</li><li>Better performance</li></ul><p>Next.js still uses React — but React runs first on the server.</p><h4>Full Flow Diagram :</h4><pre>Normal React App:<br><br>Browser → Server → Empty HTML<br>Browser → Download JS<br>Browser → React builds UI<br>Browser → User sees page<br><br><br>Next.js App (Server Rendering):<br><br>Browser → Next.js Server<br>Next.js Server → Runs React<br>Next.js Server → Builds HTML<br>Server → Sends HTML to Browser<br>Browser → Shows content<br>Browser → JS loads for interactivity</pre><p><strong>Simple one-line meaning</strong></p><p>React:<br> 👉 Browser creates page.</p><p>Next.js:<br> 👉 Server creates page first.</p><h3>Full Example: What Happens When You Open Home Page (/)?</h3><p>Let’s say you open:</p><pre>http://localhost:3000/</pre><p>Here is what actually happens step by step in Next.js:</p><p><strong>Step 1: Browser requests the page</strong></p><p>Browser says: Hey server, give me /</p><p><strong>Step 2: Next.js server receives request</strong></p><p>Next.js server looks inside the app folder:</p><pre>app/layout.js<br>app/page.js</pre><p>It understands:</p><ul><li>page.js = Home page</li><li>layout.js = Wrapper</li></ul><p><strong>Step 3: Server runs layout.js first</strong></p><p>Next.js starts with:</p><pre>app/layout.js</pre><p>Because layout is the root.</p><p>Here it:</p><ul><li>Creates &lt;html&gt;</li><li>Creates &lt;body&gt;</li><li>Adds metadata</li><li>Prepares {children}</li></ul><p><strong>Step 4: Server runs page.js</strong></p><p>Then Next.js runs:</p><pre>app/page.js</pre><p>This generates Home page content.</p><p><strong>Step 5: Server injects page into layout</strong></p><p>Now Next.js does:</p><pre>&lt;html&gt;<br> &lt;body&gt;<br>   {HomePageContent}<br> &lt;/body&gt;<br>&lt;/html&gt;</pre><p>So page.js goes inside {children}.</p><p><strong>Step 6: Server builds final HTML</strong></p><p>Now server has complete HTML:</p><ul><li>layout + page combined</li></ul><p><strong>Step 7: Server sends HTML to browser</strong></p><p>Browser receives ready-made HTML and shows content immediately.</p><p>No blank screen.</p><p><strong>Step 8: Browser downloads JS</strong></p><p>After content is visible:</p><ul><li>JavaScript loads</li><li>React becomes interactive (buttons, clicks, etc)</li></ul><p>This step is called <strong>hydration</strong>.</p><h3>Visual Diagram</h3><pre>Browser requests &quot;/&quot;<br>        ↓<br>Next.js Server<br>        ↓<br>Reads app/layout.js<br>        ↓<br>Reads app/page.js<br>        ↓<br>Injects page into {children}<br>        ↓<br>Builds full HTML<br>        ↓<br>Sends HTML to Browser<br>        ↓<br>Browser shows content<br>        ↓<br>JS loads → React becomes interactive</pre><h3>Final Thoughts</h3><p>This blog is based on my own learning while starting with Next.js. I tried to explain App Router, page.js, layout.js, and server rendering in simple words the way I understood them.</p><p>I’m still learning Next.js, so if I made any mistakes or missed something, feel free to correct me ,I’d really appreciate it.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc39cf05992a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with HTTP and REST APIs]]></title>
            <link>https://medium.com/@dipikagandash411/getting-started-with-http-and-rest-apis-6a037bea2cb8?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a037bea2cb8</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Sat, 31 Jan 2026 12:08:58 GMT</pubDate>
            <atom:updated>2026-01-31T12:08:58.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bNDiQQC84UIQa3KSKctNQQ.jpeg" /></figure><p>Every time we open a website or use a mobile app, our device talks to a server behind the scenes. A request is sent, the server processes it, and a response comes back with the required data. This happens in just a few milliseconds, but it’s the foundation of every web application.</p><p>This communication is made possible by HTTP, and REST APIs help organize this communication in a structured way. Without them, modern web apps wouldn’t work the way they do today.</p><p>In this blog, we’ll understand how HTTP works, explore common HTTP methods and status codes, and learn the basics of REST APIs with simple examples.</p><h3>What is HTTP?</h3><p>HTTP stands for <strong>HyperText Transfer Protocol</strong>. It is a set of rules that defines how data is exchanged between a client (like your browser or mobile app) and a server.</p><p>In simple words, HTTP is the language that allows your frontend and backend to communicate.</p><p>Whenever you type a URL in your browser, click a button, or submit a form, an HTTP request is sent to the server. The server processes that request and sends back an HTTP response. This response can contain HTML pages, JSON data, images, or any other resources needed by the application.</p><p>HTTP works on a <strong>request–response model</strong>:</p><ul><li>The client sends a request</li><li>The server receives and processes it</li><li>The server sends back a response</li></ul><h4>How an HTTP Request works ?</h4><p>An HTTP request is a structured message sent by the client. It usually contains four main parts:</p><blockquote><strong>1. URL (Endpoint)</strong></blockquote><p><em>The URL tells the server </em><strong><em>which data you want</em></strong><em>.</em></p><pre>https://api.example.com/users/1</pre><p>Here:</p><ul><li>api.example.com → server address</li><li>/users/1 → specific resource (user with id 1)</li></ul><p>So the URL answers: <em>“What data do I want?”</em></p><blockquote><strong>2. HTTP Method</strong></blockquote><p>The method tells <strong>what action you want to perform</strong>.</p><p>Common methods:</p><ul><li><strong>GET</strong> → get data</li><li><strong>POST</strong> → create data</li><li><strong>PUT</strong> → replace data</li><li><strong>PATCH</strong> → update some fields</li><li><strong>DELETE</strong> → delete data</li></ul><p>Example:</p><pre>GET /users<br>POST /users<br>PATCH /users/1<br>DELETE /users/1</pre><p>So method answers: <em>What should be done?</em></p><blockquote><strong>3. Headers</strong></blockquote><p>Headers carry <strong>metadata</strong> (extra information) about the request.</p><p>They tell the server (or client):</p><ul><li>What type of data is being sent</li><li>Who is making the request</li><li>How the data should be read</li><li>What format is expected in response</li></ul><p>Headers do NOT usually contain main data — they only describe the data.</p><ol><li><strong>Content-Type</strong></li></ol><p>Content-Type tells the server <strong>what format your data is in</strong>.</p><p>Example:</p><pre>Content-Type: application/json</pre><p>This means:</p><p>👉 “Hey server, I am sending data in JSON format.”</p><p>Common Content-Type values:</p><ul><li>application/json → JSON data (most APIs)</li><li>multipart/form-data → file uploads</li><li>application/x-www-form-urlencoded → form data</li><li>text/plain → simple text</li></ul><p><strong>2. Accept Header</strong></p><p>Accept tells the server <strong>what type of response you want back</strong>.</p><p>Example:</p><pre>Accept: application/json</pre><p>Means:</p><p>👉 “Please send response in JSON.”</p><p><strong>3. Authorization Header</strong></p><p>Used when APIs need login or security.</p><p>Example:</p><pre>Authorization: Bearer token123</pre><p>This sends your login token so server knows who you are.</p><p>Without this, protected APIs return 401 Unauthorized.</p><p>So Authorization answers:</p><p><strong>Who am I?</strong></p><blockquote><strong><em>4. Body (Optional)</em></strong></blockquote><p>Body contains the actual data sent to server.<br> Mostly used with POST, PUT, PATCH.</p><p>Example:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><h4>How an HTTP Response works</h4><p>After receiving the request, the server sends back a response. This response also has structured parts:</p><blockquote><strong>1. Status Code</strong></blockquote><p>Status codes tell whether the request succeeded or failed.</p><p>Common ones:</p><ul><li><strong>200</strong> → Success</li><li><strong>201</strong> → Resource created</li><li><strong>400</strong> → Bad request</li><li><strong>401</strong> → Unauthorized</li><li><strong>404</strong> → Not found</li><li><strong>500</strong> → Server error</li></ul><p>Status codes answer: <em>“Did your request work?”</em></p><blockquote><strong>2. Response Headers</strong></blockquote><p>They give info about returned data like content type.</p><blockquote><strong>3. Response Body</strong></blockquote><p>This contains the actual data from server.</p><p>Example:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;Dipika&quot;<br>}</pre><p>Frontend uses this data.</p><h3>Stateless Nature of HTTP</h3><p>HTTP is stateless, which means server does not remember previous requests.</p><p>So login and user data are handled using:</p><ul><li>Cookies</li><li>Tokens (JWT)</li><li>Sessions</li></ul><p>on top of HTTP.</p><h3>HTTP Methods</h3><p>HTTP methods define <strong>what action the client wants to perform</strong> on server data. Each method has a specific purpose.</p><p>Think of a server like a database of resources (users, posts, products). HTTP methods tell the server what to do with those resources.</p><h4>1. GET — Fetch Data</h4><p>GET is used to <strong>read or retrieve data</strong> from the server.</p><p>It does NOT change anything on the server.</p><p>Examples:</p><pre>GET /users<br>GET /users/1</pre><ul><li>GET /users → get all users</li><li>GET /users/1 → get user with id 1</li></ul><p>Important points:</p><ul><li>No request body</li><li>Only used to fetch data</li><li>Safe method (does not modify data)</li></ul><p>Real-life example:<br> Opening a website or loading products → GET request.</p><h4>2. POST — Create New Data</h4><p>POST is used to <strong>create new resources</strong> on the server.</p><p>Example:</p><pre>POST /users</pre><p>Body:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><p>This creates a new user.</p><p>Important points:</p><ul><li>Has request body</li><li>Creates new data</li><li>Not idempotent (calling multiple times creates multiple users)</li></ul><p>Real-life example:<br> Signup form → POST request.</p><h4>3. PUT — Replace Existing Data</h4><p>PUT is used to <strong>completely replace an existing resource</strong>.</p><p>Example:</p><pre>PUT /users/1</pre><p>Body:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika Sharma&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><p>This replaces the entire user record.</p><p>Important points:</p><ul><li>Sends full object</li><li>Old data gets overwritten</li><li>If field missing, it may be removed</li></ul><p>Use PUT when you want to update everything.</p><h4>4. PATCH — Update Partial Data</h4><p>PATCH is used to <strong>update only specific fields</strong>.</p><p>Example:</p><pre>PATCH /users/1</pre><p>Body:</p><pre>{<br>  &quot;name&quot;: &quot;Dipikaa&quot;<br>}</pre><p>Only name changes, email stays same.</p><p>Important points:</p><ul><li>Sends only fields to update</li><li>Safer than PUT for small update</li><li>Most modern APIs prefer PATCH</li></ul><h4>5. DELETE — Remove Data</h4><p>DELETE is used to <strong>delete a resource</strong>.</p><p>Example:</p><pre>DELETE /users/1</pre><p>This removes user with id 1.</p><p>Important points:</p><ul><li>No body usually</li><li>Removes data permanently (unless soft delete)</li></ul><p>Real-life example:<br> Deleting account → DELETE.</p><h4>Idempotency</h4><p>Some methods are <strong>idempotent</strong>, meaning calling them multiple times gives same result.</p><ul><li>GET → idempotent</li><li>PUT → idempotent</li><li>DELETE → idempotent</li><li>POST → NOT idempotent</li></ul><p>Example:<br> Calling DELETE 5 times still deletes once.</p><p>Calling POST 5 times creates 5 users.</p><h3>HTTP Status Codes</h3><p>Whenever a server sends a response, it also sends a <strong>status code</strong>. Status codes tell the client whether the request was successful, failed, or needs some action.</p><p>Instead of guessing what happened, the client simply looks at the status code.</p><p>Each status code is a <strong>3-digit number</strong>, and each range has a meaning:</p><ul><li><strong>1xx</strong> → Informational</li><li><strong>2xx</strong> → Success</li><li><strong>3xx</strong> → Redirection</li><li><strong>4xx</strong> → Client error</li><li><strong>5xx</strong> → Server error</li></ul><p>In real applications, we mostly deal with <strong>2xx, 4xx, and 5xx</strong>.</p><p>Let’s understand them.</p><h3>2xx — Success Responses</h3><p>These mean the request worked correctly.</p><h4>1. 200 OK</h4><p>The request was successful and data is returned.</p><p>Example:<br> Fetching users:</p><pre>GET /users → 200 OK</pre><h4>2. 201 Created</h4><p>A new resource was successfully created.</p><p>Example:<br> After signup:</p><pre>POST /users → 201 Created</pre><p>used mostly with POST</p><h4>3. 204 No Content</h4><p>Request succeeded but no data is returned.</p><p>Example:<br> After deleting:</p><pre>DELETE /users/1 → 204 No Content</pre><h3>4xx — Client Errors</h3><p>These mean <strong>something is wrong with the request sent by client</strong>.</p><h4>1. 400 Bad Request</h4><p>The request format or data is invalid.</p><p>Example:<br> Missing required fields in form.</p><h4>2. 401 Unauthorized</h4><p>Authentication required or token missing/invalid.</p><p>Example:<br> Accessing protected route without login.</p><h4>3. 403 Forbidden</h4><p>User is authenticated but not allowed to access resource.</p><p>Example:<br> Normal user trying admin API.</p><h4>4. 404 Not Found</h4><p>Requested resource does not exist.</p><p>Example:</p><pre>GET /users/999</pre><p>user does not exist.</p><h4>5. 409 Conflict</h4><p>Data conflict.</p><p>Example:<br> Trying to register with already existing email.</p><h3>5xx — Server Errors</h3><p>These mean server failed to process a valid request.</p><h4>1. 500 Internal Server Error</h4><p>Generic server crash.</p><p>Example:<br> Bug in backend code.</p><h4>2. 502 Bad Gateway</h4><p>Server received invalid response from another server.</p><p>Common in microservices.</p><h4>3. 503 Service Unavailable</h4><p>Server is down or overloaded.</p><h3>Why Status Codes Matter</h3><p>Status codes help frontend decide what to do:</p><ul><li>200 → show data</li><li>401 → redirect to login</li><li>404 → show not found page</li><li>500 → show server error</li></ul><p>Without status codes, frontend wouldn’t know how to react.</p><h3>What is a REST API?</h3><p>REST stands for <strong>Representational State Transfer</strong>. A REST API is a way of designing backend APIs using standard HTTP methods and clear resource-based URLs.</p><p>In simple terms, REST defines <strong>how APIs should be structured</strong> so that clients and servers can communicate in a consistent and predictable way.</p><p>An API (Application Programming Interface) allows different applications to talk to each other. REST is just a <strong>set of rules and best practices</strong> that tell us how to build these APIs using HTTP.</p><p>So when we say “REST API”, we usually mean:</p><p>👉 An API that follows REST principles and uses HTTP methods like GET, POST, PUT, PATCH, and DELETE.</p><h4>Resources in REST</h4><p>In REST APIs, everything is treated as a <strong>resource</strong>.</p><p>A <strong>resource</strong> is basically any piece of data that your application manages.<br> It can be a user, product, order, post, comment — anything that can be stored in a database.</p><p>For example:</p><ul><li>A user in your app → resource</li><li>A product in an e-commerce site → resource</li><li>An order placed by customer → resource</li><li>A blog post → resource</li></ul><p>Each resource is given its own <strong>URL (endpoint)</strong> so it can be accessed over HTTP.</p><p>Examples:</p><pre>/users<br>/products<br>/orders</pre><p>Here:</p><ul><li>/users represents the collection of all users</li><li>/products represents all products</li><li>/orders represents all orders</li></ul><p>If you want a <strong>specific resource</strong>, you add an id:</p><pre>/users/1<br>/products/10<br>/orders/5</pre><p>Meaning:</p><ul><li>/users/1 → user with id 1</li><li>/products/10 → product with id 10</li><li>/orders/5 → order with id 5</li></ul><p>Now HTTP methods decide what happens to these resources:</p><ul><li>GET /users → get all users</li><li>POST /users → create new user</li><li>PATCH /users/1 → update user</li><li>DELETE /users/1 → delete user</li></ul><p>So in REST:</p><p>👉 URLs represent <strong>resources (data)</strong><br> 👉 HTTP methods represent <strong>actions</strong></p><p>This separation makes APIs clean, readable, and predictable.</p><h4>REST Uses Standard Status Codes</h4><p>REST APIs rely on HTTP status codes to communicate results:</p><ul><li>200 → success</li><li>201 → created</li><li>400 → bad request</li><li>401 → unauthorized</li><li>404 → not found</li><li>500 → server error</li></ul><p>Frontend uses these to decide UI behavior.</p><h4>REST Uses JSON Format</h4><p>Most REST APIs send and receive data in JSON.</p><p>Example response:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;Dipika&quot;<br>}</pre><p>JSON is lightweight and easy for frontend to parse.</p><h3>Key REST Principles</h3><p>Here are core REST ideas:</p><h4>1. Resource-based URLs</h4><p>Use nouns, not verbs.</p><h4><strong>2. Uses HTTP Methods</strong></h4><p>Actions decided by GET, POST, PATCH, DELETE.</p><h4>3. Stateless</h4><p>Each request is independent.</p><h4>4. Uses Standard Status Codes</h4><p>Clear success/error communication.</p><h4>5. Client–Server Separation</h4><p>Frontend and backend work independently.</p><h3>Small Real Example</h3><p>Imagine a user API:</p><p>Create user:</p><pre>POST /users</pre><p>Get users:</p><pre>GET /users</pre><p>Update user:</p><pre>PATCH /users/1</pre><p>Delete user:</p><pre>DELETE /users/1</pre><p>Same endpoint, different operations.</p><p>That’s REST.</p><h3>REST API Best Practices</h3><p>Following REST principles is good, but writing <strong>clean and maintainable APIs</strong> also requires some best practices. These help make APIs easier to use, scale, and debug.</p><p>Here are some important REST best practices:</p><h4>1. Use Nouns, Not Verbs in URLs</h4><p>Endpoints should represent <strong>resources</strong>, not actions.</p><p>❌ Bad:</p><pre>/getUsers<br>/createUser<br>/deleteProduct</pre><p>✅ Good:</p><pre>/users<br>/products</pre><p>Actions are handled by HTTP methods, not URLs.</p><h4>2. Use Proper HTTP Methods</h4><p>Always match the correct method with the correct action:</p><ul><li>GET → fetch data</li><li>POST → create data</li><li>PATCH → update data</li><li>DELETE → remove data</li></ul><p>This keeps APIs predictable.</p><h4>3. Use Meaningful Status Codes</h4><p>Return correct status codes so frontend understands what happened.</p><p>Examples:</p><ul><li>200 → success</li><li>201 → created</li><li>400 → bad request</li><li>401 → unauthorized</li><li>404 → not found</li><li>500 → server error</li></ul><p>Avoid always returning 200.</p><h4>4. Keep APIs Stateless</h4><p>Every request should contain all required information.</p><p>Do not rely on previous requests.</p><p>Use tokens (JWT) for authentication</p><h4>5. Use JSON for Request and Response</h4><p>JSON is lightweight and easy to parse.</p><p>Example:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><p>Keep response format consistent.</p><h4>6. Use Proper Naming Conventions</h4><p>Use lowercase and plural nouns:</p><pre>/users<br>/orders<br>/products</pre><p>Avoid:</p><pre>/UserList<br>/Order_Data</pre><h4>7. Version Your APIs</h4><p>When APIs change, older clients should not break.</p><p>Example:</p><pre>/api/v1/users<br>/api/v2/users</pre><h4>8. Handle Errors Properly</h4><p>Send clear error messages:</p><pre>{<br>  &quot;message&quot;: &quot;Email already exists&quot;<br>}</pre><p>Frontend can show meaningful feedback.</p><h4>9. Support Filtering and Pagination</h4><p>For large data:</p><pre>GET /users?page=1&amp;limit=10</pre><p>This improves performance.</p><h3>Small MERN REST API Example</h3><p>Let’s understand REST APIs with a simple MERN stack example.</p><p>Assume we are building a <strong>User Management</strong> feature using:</p><ul><li>MongoDB → database</li><li>Express + Node.js → backend API</li><li>React → frontend</li></ul><p>Our backend exposes REST endpoints for users.</p><h4>Backend Routes (Express)</h4><p>We create routes like:</p><pre>GET    /api/users<br>POST   /api/users<br>PATCH  /api/users/:id<br>DELETE /api/users/:id</pre><p>Each route performs a specific operation:</p><ul><li>GET /api/users → fetch all users</li><li>POST /api/users → create new user</li><li>PATCH /api/users/:id → update user</li><li>DELETE /api/users/:id → delete user</li></ul><p>Here, /api/users is the <strong>resource</strong>, and HTTP methods decide the action.</p><p><strong>Example: Create User</strong></p><p>Frontend sends:</p><pre>POST /api/users<br>Content-Type: application/json</pre><p>Body:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><p>Backend saves this in MongoDB and responds:</p><pre>201 Created</pre><pre>{<br>  &quot;_id&quot;: &quot;123&quot;,<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;<br>}</pre><p><strong>Example: Fetch Users</strong></p><p>Frontend calls:</p><pre>GET /api/users</pre><p>Backend responds:</p><pre>[<br>  {<br>    &quot;_id&quot;: &quot;123&quot;,<br>    &quot;name&quot;: &quot;Dipika&quot;<br>  }<br>]</pre><p>React receives this and displays users on UI.</p><p><strong>Example: Update User</strong></p><p>Frontend sends:</p><pre>PATCH /api/users/123</pre><p>Body:</p><pre>{<br>  &quot;name&quot;: &quot;Dipika Sharma&quot;<br>}</pre><p>Only name is updated.</p><p><strong>Example: Delete User</strong></p><p>Frontend sends:</p><pre>DELETE /api/users/123</pre><p>User is removed from database.</p><h4>Simple Summary</h4><p>REST APIs act as the bridge between frontend and database in MERN.</p><p>React → HTTP → Express/Node → MongoDB → Response → React</p><h3>Conclusion</h3><p>HTTP and REST APIs form the backbone of modern web applications. From sending requests and receiving responses to managing data using REST principles, every interaction between frontend and backend depends on these concepts. Understanding HTTP methods, status codes, headers, and REST design helps build cleaner APIs and scalable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a037bea2cb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with System Design: Understanding Client–Server Architecture]]></title>
            <link>https://medium.com/@dipikagandash411/getting-started-with-system-design-understanding-client-server-architecture-89b745b8ada8?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/89b745b8ada8</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Fri, 30 Jan 2026 07:44:09 GMT</pubDate>
            <atom:updated>2026-01-30T07:44:09.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTVL6eM2nEDEqJ7CwLe82Q.jpeg" /></figure><h3>📌 What Is System Design?</h3><p>System Design is the process of <strong>planning and structuring how a software application works as a complete system</strong>.</p><p>Instead of focusing only on writing code for small features, system design looks at the bigger picture:</p><ul><li>How different parts of the application communicate</li><li>How data is stored and retrieved</li><li>How the system handles many users at the same time</li><li>How performance, security, and reliability are ensured</li></ul><p>In simple words:</p><blockquote><strong><em>System design is creating the blueprint of an application before building it.</em></strong></blockquote><p>Just like we design a house before construction, we design software systems before implementing large applications.</p><h3>Why Do We Need System Design?</h3><p>When we build small projects, everything usually works on a single server.<br> But real-world applications like LinkedIn, Swiggy, or Netflix have millions of users.</p><p>Without proper system design:</p><ul><li>Servers may crash during high traffic</li><li>Applications become slow</li><li>Data can become inconsistent</li><li>Making changes becomes difficult</li></ul><p>System design helps avoid these problems by planning things in advance.</p><p>It makes sure the system is:</p><ul><li><strong>Scalable</strong> — can grow with more users</li><li><strong>Fast</strong> — gives quick responses</li><li><strong>Reliable</strong> — keeps working even if something fails</li><li><strong>Maintainable</strong> — easy to update and improve</li><li><strong>Secure</strong> — protects user data</li></ul><h3>🎯 Main Goals of System Design</h3><p>The main purpose of system design is to build applications that can grow, perform well, stay reliable, and remain easy to maintain over time. Let’s understand each goal in detail.</p><h4>1️⃣ Scalability</h4><p>Scalability means the ability of a system to <strong>handle increasing users, requests, or data without breaking or slowing down significantly</strong>.</p><p>When an application is small, a single server might be enough. But as users increase, that same server may become overloaded. A scalable system is designed in such a way that we can:</p><ul><li>Add more servers when traffic increases</li><li>Handle more data without redesigning everything</li></ul><p>For example, if a job portal suddenly gets 10x more users, a scalable system can distribute traffic across multiple servers instead of crashing.</p><p>In simple terms:</p><blockquote><em>Scalability ensures that your application can grow with your users.</em></blockquote><h4>2️⃣ Performance</h4><p>Performance refers to <strong>how fast the system responds to user requests</strong>.</p><p>Users expect applications to load quickly. Even a few seconds of delay can make people leave the app. System design improves performance by:</p><ul><li>Using caching (like Redis) to avoid hitting the database every time</li><li>Optimizing database queries</li><li>Serving static content through CDNs</li><li>Reducing unnecessary network calls</li></ul><p>For example, instead of fetching job listings from the database on every request, we can cache popular results and serve them instantly.</p><p>In short:</p><blockquote><em>Performance focuses on making the application fast and responsive.</em></blockquote><h4>3️⃣ Reliability</h4><p>Reliability means the system should <strong>continue working even when some parts fail</strong>.</p><p>In real-world systems, failures are normal:</p><ul><li>Servers can go down</li><li>Network issues can happen</li><li>Databases may temporarily become unavailable</li></ul><p>A reliable system is designed to handle such failures gracefully by:</p><ul><li>Using multiple servers instead of just one</li><li>Automatically redirecting traffic if a server crashes</li><li>Retrying failed requests</li><li>Backing up data regularly</li></ul><p>So even if one component fails, users should still be able to use the application.</p><p>Simply put:</p><blockquote><em>Reliability ensures your system does not completely stop because of a single failure.</em></blockquote><h4>4️⃣ Maintainability</h4><p>Maintainability means how easy it is for developers to <strong>update, fix, or improve the system over time</strong>.</p><p>As applications grow, new features are added and bugs need to be fixed. If the system is poorly designed, even small changes become risky and complicated.</p><p>Good system design improves maintainability by:</p><ul><li>Keeping frontend, backend, and database separated</li><li>Writing modular code</li><li>Using clear APIs</li><li>Organizing services properly</li></ul><p>For example, if login logic is separated from job-related logic, developers can change one part without affecting the other.</p><p>In simple words:</p><blockquote><em>Maintainability makes the system easy to understand, modify, and extend.</em></blockquote><h4>5️⃣ Security</h4><p>Security is about <strong>protecting user data and preventing unauthorized access</strong>.</p><p>Modern applications deal with sensitive information like passwords, emails, and personal details. System design ensures security by:</p><ul><li>Using authentication (like JWT or sessions)</li><li>Encrypting communication with HTTPS</li><li>Hashing passwords</li><li>Applying authorization rules (who can access what)</li><li>Limiting requests to prevent attacks</li></ul><p>For example, only logged-in users should be allowed to apply for jobs, and passwords should never be stored in plain text.</p><p>In short:</p><blockquote><em>Security ensures that user data is safe and only authorized users can access the system.</em></blockquote><h3>What Comes Under System Design?</h3><p>System design mainly involves making important technical decisions about how different parts of an application work together. Instead of jumping straight into coding, we first think about these core areas:</p><h4>🔹 Application Architecture</h4><p>This defines the overall structure of the application.</p><p>It decides how the system is divided into parts such as frontend, backend, and database, and how these parts interact with each other. For example, in a typical web application, the frontend handles user interface, the backend handles business logic, and the database stores data.</p><p>Good architecture helps in keeping the system organized, scalable, and easy to maintain.</p><h4>🔹 API Communication</h4><p>APIs define how the frontend and backend communicate.</p><p>System design involves deciding:</p><ul><li>What endpoints are needed</li><li>What data should be sent or receive</li><li>How requests and responses are structured</li></ul><p>For example, APIs like /login, /jobs, or /apply allow the frontend to interact with backend services. Clear API design makes integration easier and reduces bugs.</p><h4>🔹 Database Structure</h4><p>This focuses on how data is stored and organized.</p><p>It includes:</p><ul><li>Choosing SQL or NoSQL databases</li><li>Designing tables or collections</li><li>Defining relationships between data</li><li>Adding indexes for faster queries</li></ul><p>For example, deciding separate collections for users, jobs, and applications helps keep data structured and improves performance.</p><h4>🔹 Authentication Flow</h4><p>Authentication flow decides how users log in and how their identity is verified.</p><p>This includes:</p><ul><li>Login and signup process</li><li>Token or session management</li><li>Protecting private routes</li></ul><p>A good authentication flow ensures only authorized users can access certain features while keeping user data secure.</p><h4>🔹 Scaling Approach</h4><p>Scaling defines how the system will handle increasing traffic and data.</p><p>System design answers questions like:</p><ul><li>Should we add more servers?</li><li>How do we distribute traffic?</li><li>How do we prevent one server from becoming overloaded?</li></ul><p>Planning scaling early helps avoid performance issues when the application grows.</p><h4>🔹 Caching Strategy</h4><p>Caching is used to store frequently accessed data temporarily so that the system does not need to hit the database every time.</p><p>For example, popular job listings can be cached so users get faster responses. A good caching strategy greatly improves performance and reduces server load.</p><h4>🔹 Error Handling</h4><p>No system is perfect, and errors are unavoidable.</p><p>System design also includes deciding:</p><ul><li>How errors are handled</li><li>What users see when something fails</li><li>How failures are logged for debugging</li></ul><p>Proper error handling ensures the application does not crash suddenly and provides meaningful feedback to users.</p><h4>🤔 Questions System Design Tries to Answer</h4><p>System design helps answer practical questions like:</p><ul><li>How does frontend communicate with backend?</li><li>Where and how is data stored?</li><li>What happens when user traffic increases?</li><li>How do we protect user information?</li><li>How do we keep the system fast and reliable?</li></ul><p>By answering these questions early, we can build applications that are strong, scalable, and ready for real-world usage.</p><h3>High-Level Design (HLD) vs Low-Level Design (LLD)</h3><p>In system design, we usually divide the process into two parts: <strong>High-Level Design (HLD)</strong> and <strong>Low-Level Design (LLD)</strong>. Both are important, but they focus on different levels of detail.</p><h4>🔹 High-Level Design (HLD)</h4><p>High-Level Design gives a <strong>big-picture view of the system</strong>.</p><p>It focuses on <em>what components exist</em> and <em>how they connect with each other</em>, without going deep into implementation details.</p><p>HLD answers questions like:</p><ul><li>What are the main parts of the system?</li><li>How does data flow between them?</li><li>Which database should be used?</li><li>How does frontend communicate with backend?</li></ul><p>In HLD, we define:</p><ul><li>Overall architecture (for example: Frontend → Backend → Database)</li><li>Major services or modules</li><li>External systems (like authentication or third-party APIs)</li><li>Basic data flow</li></ul><p>Example of HLD:</p><p>A job portal might look like:</p><ul><li>React frontend for UI</li><li>Node/Express backend for APIs</li><li>MongoDB for storing users and jobs</li></ul><p>At this stage, we are not writing code. We are just designing the structure.</p><p>In simple words:</p><blockquote><strong><em>High-Level Design explains what the system looks like from a top view.</em></strong></blockquote><h4>🔹 Low-Level Design (LLD)</h4><p>Low-Level Design goes deeper into the system and explains <strong>how each part actually works internally</strong>.</p><p>LLD focuses on implementation details.</p><p>It answers questions like:</p><ul><li>What APIs will be created?</li><li>What fields will exist in database collections?</li><li>What validations are required?</li><li>How will business logic be handled?</li></ul><p>In LLD, we define:</p><ul><li>API endpoints (/login, /jobs, /apply)</li><li>Database schemas (Users, Jobs, Applications)</li><li>Controllers and services</li><li>Authentication logic</li><li>Error handling</li></ul><p>For example, in LLD of a job portal, we might design:</p><ul><li>User schema with email and password</li><li>Job schema with title and description</li><li>API flow for applying to a job</li></ul><p>In simple words:</p><blockquote><strong><em>Low-Level Design explains how each component is implemented in detail.</em></strong></blockquote><h3>🌐 Client–Server Architecture Basics</h3><p>Client–Server Architecture is one of the most fundamental concepts in system design. Almost every modern web application is built using this model.</p><p>In this architecture, the system is divided into two main parts:</p><ul><li><strong>Client</strong> — the part that users interact with</li><li><strong>Server</strong> — the part that processes requests and manages data</li></ul><p>They communicate with each other over a network, usually using HTTP or HTTPS.</p><p>In simple words:</p><blockquote><em>The client sends requests, the server processes them, and sends responses back.</em></blockquote><h3>🧑‍💻 What Is a Client?</h3><p>The client is the <strong>user-facing side of the application</strong>.</p><p>Examples of clients include:</p><ul><li>Web browsers</li><li>Mobile apps</li><li>Frontend applications</li></ul><p>The client is responsible for:</p><ul><li>Displaying UI</li><li>Taking user input</li><li>Sending requests to the server</li><li>Showing responses received from the server</li></ul><p>For example, when a user clicks the login button, the frontend collects the email and password and sends them to the backend. This action is handled by the client.</p><p>The client does NOT:</p><ul><li>Access the database directly</li><li>Perform heavy business logic</li></ul><h4>🖥️ What Is a Server?</h4><p>The server is the <strong>backend part of the application</strong>.</p><p>It receives requests from clients, performs business logic, interacts with the database, and sends responses back.</p><p>In most full-stack projects, the server is built using technologies like Node.js and Express.</p><p>The server is responsible for:</p><ul><li>Validating input</li><li>Authenticating users</li><li>Handling business logic</li><li>Communicating with the database</li><li>Sending responses to clients</li></ul><p>For example, when login data is sent from the frontend, the server checks the credentials in the database and returns success or failure.</p><p>The server does NOT:</p><ul><li>Handle UI rendering</li><li>Interact directly with users</li></ul><h4>🔄 How Client and Server Communicate</h4><p>Communication usually happens through HTTP requests.</p><p>Typical flow looks like this:</p><ol><li>User performs an action on frontend</li><li>Client sends an HTTP request to server</li><li>Server processes the request</li><li>Server interacts with database if needed</li><li>Server sends response back</li><li>Client displays result to user</li></ol><p>Example:</p><ul><li>Client sends POST /login</li><li>Server verifies user</li><li>Server returns JWT token</li><li>Client stores token and updates UI</li></ul><p>This complete process is called the <strong>request–response cycle</strong>.</p><h4>🗂️ Basic Client–Server Architecture Flow</h4><p>A simple structure looks like:</p><pre>Client (Frontend)<br>↓<br>Server (Backend APIs)<br>↓<br>Database</pre><p>This is also known as a <strong>three-tier architecture</strong>:</p><ul><li>Presentation layer (frontend)</li><li>Application layer (backend)</li><li>Data layer (database)</li></ul><p>Most beginner full-stack projects follow this pattern.</p><h4>🧠 Real World Example</h4><p>Think of a restaurant:</p><ul><li>You (client) → order food</li><li>Waiter (network) → carries order</li><li>Kitchen (server) → prepares food</li><li>Waiter → brings food back</li></ul><p>You don’t cook.<br> Kitchen doesn’t come to your table.</p><p>Same idea.</p><h3>Request Lifecycle in Client–Server Architecture</h3><p>The request lifecycle explains <strong>what happens from the moment a user performs an action on the frontend until the server sends a response back</strong>.</p><p>Understanding this flow is very important because it shows how client, server, and database work together.</p><p>Let’s understand this with a simple example: <strong>User Login</strong>.</p><h4>Step 1: User Action (Client Side)</h4><p>The user enters email and password and clicks the login button.</p><p>At this point, the frontend (client):</p><ul><li>Collects input data</li><li>Prepares an HTTP request</li></ul><h4>Step 2: Client Sends Request</h4><p>The client sends a request to the backend API:</p><pre>POST /login</pre><p>Along with the request, it sends user credentials in the request body.</p><p>This request travels over the internet using HTTP or HTTPS.</p><h4>Step 3: Server Receives Request</h4><p>The server receives the request and starts processing it.</p><p>It performs:</p><ul><li>Input validation</li><li>Checking required fields</li><li>Calling authentication logic</li></ul><h4>Step 4: Server Interacts with Database</h4><p>The server queries the database to find the user.</p><p>For example:</p><ul><li>It checks whether the email exists</li><li>It compares the hashed password</li></ul><p>This is where backend communicates with database.</p><h4>Step 5: Server Applies Business Logic</h4><p>After verifying credentials, the server:</p><ul><li>Generates a JWT token</li><li>Prepares the response data</li></ul><p>If credentials are wrong, it sends an error instead.</p><h4>Step 6: Server Sends Response</h4><p>The server sends back an HTTP response:</p><ul><li>Success response with token</li><li>Or error message</li></ul><p>This response travels back to the client.</p><h4>Step 7: Client Handles Response</h4><p>The client receives the response and:</p><ul><li>Stores JWT token</li><li>Updates UI</li><li>Redirects user to dashboard</li></ul><p>Now the user is logged in.</p><h4>Conclusion</h4><p>System design plays a crucial role in building modern applications by helping us plan how different parts of a system work together. In this blog, we covered the core ideas of system design, its main goals, and key components such as architecture, APIs, databases, and authentication. We also explored client–server architecture, understood how requests flow between client and server, and looked at different types of client–server models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89b745b8ada8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Context API Made Simple for Beginners]]></title>
            <link>https://medium.com/@dipikagandash411/react-context-api-made-simple-for-beginners-f05437d17120?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/f05437d17120</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 13:22:30 GMT</pubDate>
            <atom:updated>2025-09-25T13:22:30.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNrlKQE5e0jsd3rpob7-rA.jpeg" /></figure><p>Imagine this 👇</p><p>You’re building a food delivery app (like Zomato or Swiggy 🍔). At the very top, you have a User object that stores the username, location, and theme (dark/light).</p><p>Now, the problem?</p><ul><li>You need to show the username on the navbar (top).</li><li>You also need the username in the restaurant page (middle).</li><li>You also need it inside the checkout cart (deep inside child components).</li></ul><p>So what do you do? You pass username as a prop from the top → middle → deep child.<br> But wait… that’s <strong>props drilling</strong> 😩.<br> Every component in between has to carry props even if it doesn’t use them. Your code becomes messy, hard to maintain, and painful when the app grows.</p><p>This is where <strong>React Context API comes in as the hero 🦸</strong>.</p><p>With Context API:</p><ul><li>You create a UserContext.</li><li>Wrap your app with it.</li><li>Any component, no matter how deep, can directly access username without drilling props through every parent.</li></ul><p>It’s like having a <strong>global store</strong> but lighter than Redux.</p><h3>What is React Context API?</h3><p>Think of <strong>Context API</strong> like a <strong>global storage for React components</strong>. Normally, in React, if you want to send data from a parent component to a child component, you use <strong>props</strong>. But when many components need the same data, you end up passing props through multiple layers — this is called <strong>props drilling</strong>.</p><p><strong>Context API solves this</strong>: it allows you to <strong>share data directly with any component</strong>, without passing through every level.</p><p><strong>Example in real life</strong>:</p><ul><li>Imagine your app has a <strong>theme</strong> (dark or light mode).</li><li>Without Context: You’d pass theme as a prop through many components.</li><li>With Context: Any component can access theme directly.</li></ul><h3>🚀 Context API in Action</h3><h4>Step 1. Create a Context File</h4><p>Create a file for your context. Example:</p><pre>src/<br> └─ ThemeContext.js</pre><p>In this file, we <strong>create, export, and define our context provider</strong>.</p><h4>Step 2. Importing React and Necessary Functions</h4><pre>import React, { createContext, useState, useContext } from &#39;react&#39;;</pre><ul><li>React → Required for JSX</li><li>createContext → Function to create a new context object</li><li>useState → To manage state inside provider</li><li>useContext → To access the context in other components</li></ul><h4>Step 3. Creating the Context Object</h4><pre>export const ThemeContext = createContext();</pre><ul><li>createContext() is a <strong>function provided by React</strong>.</li><li>When you call it, it <strong>creates a new Context object</strong>.</li><li>This object has <strong>two main parts</strong>:</li></ul><ol><li><strong>Provider</strong> → This is a React component. It <strong>wraps parts of your app</strong> and <strong>supplies data</strong> to all child components.</li><li><strong>Consumer</strong> → This is a React component (or hook) that <strong>reads the data</strong> from the Provider.</li></ol><p>Think of it like a <strong>box</strong>:</p><ul><li>Provider puts something inside the box.</li><li>Any Consumer (or component using useContext) can open the box and get the value.</li></ul><h4>Step 4. What is the Provider?</h4><p>Every Context object has a <strong>Provider</strong>:</p><pre>ThemeContext.Provider</pre><ul><li>The <strong>Provider</strong> is a <strong>special component</strong> from React.</li><li>Its job is to <strong>hold and supply the data</strong> you want to share.</li><li>Any <strong>child component inside the Provider</strong> can access this data.</li></ul><p>The Provider is used to wrap the part of your component tree where you want the context to be available. It accepts a compulsory value prop that holds the data you want to share across other components. When the value prop of the Provider changes, all descendants that consume the context will re-render.</p><blockquote>Why put data inside Provider?</blockquote><pre>&lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>  {children}<br>&lt;/ThemeContext.Provider&gt;</pre><ul><li>value = <strong>the data you want to share</strong>.</li><li>Can be anything: string, number, object, function.</li><li>children = <strong>the components that can access this data</strong>.</li><li>When you put data inside Provider, <strong>React automatically gives it to any component that reads the context</strong>.</li></ul><h4>Step 5. Using State in the Provider</h4><pre>const [theme, setTheme] = useState(&#39;light&#39;);</pre><ul><li>We store the theme in state so it can <strong>change dynamically</strong>.</li><li>React will automatically <strong>re-render components</strong> consuming this context when theme changes.</li></ul><pre>const toggleTheme = () =&gt; {<br>  setTheme(prevTheme =&gt; (prevTheme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;));<br>};</pre><ul><li>toggleTheme is a <strong>function we want to share</strong> too.</li><li>Any component using this context can <strong>call this function</strong> to change the theme.</li></ul><h4>Full Code :</h4><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>// 1. Create Context object<br>export const ThemeContext = createContext();<br><br>export const ThemeProvider = ({ children }) =&gt; {<br>  // 2. Create state for theme<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br><br>  // 3. Create function to change theme<br>  const toggleTheme = () =&gt; {<br>    setTheme(prev =&gt; (prev === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;));<br>  };<br><br>  // 4. Wrap children with Provider and pass value<br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>      {children} {/* All components inside this Provider can access theme */}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};</pre><p><strong>Step by Step:</strong></p><ol><li><strong>Create Context</strong> → Gives you a container (ThemeContext)</li><li><strong>Create State</strong> → Store the actual data you want to share (theme)</li><li><strong>Create Function</strong> → Something that modifies the state (toggleTheme)</li><li><strong>Wrap children with Provider</strong> → Share the data (value={{ theme, toggleTheme }})</li><li><strong>Now all children can access the data</strong> → using useContext(ThemeContext)</li></ol><h3>🤔 Where is the data actually stored?</h3><h4>1. When you create a Context</h4><pre>const ThemeContext = createContext();</pre><ul><li>This line makes an <strong>empty Context object</strong>.</li><li>By itself, it doesn’t hold any data (like light or dark).</li><li>It’s just a <strong>box</strong> that can be filled with something later.</li></ul><p>Think: it’s like making an <em>empty storage locker</em>. The locker has a <strong>name</strong> (ThemeContext), but it’s empty until you put something in it.</p><h4>2. The Provider</h4><pre>&lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>   {children}<br>&lt;/ThemeContext.Provider&gt;</pre><ul><li><strong>Provider’s job = fill the box (Context) with data.</strong></li><li>Whatever you put in the value prop (here theme and toggleTheme) gets stored inside the Context, so any component that uses this context can access it.</li></ul><p>👉 Important:<br> The data itself is <strong>not stored inside the Provider component</strong>.<br> It’s stored in <strong>React’s internal Context system</strong>, and the Provider is like the <em>delivery person</em> that hands out that data to every child inside it.</p><p>Think:</p><ul><li><strong>Context</strong> = locker.</li><li><strong>Provider</strong> = puts stuff in locker (value).</li><li><strong>Consumer (useContext)</strong> = opens locker to take the stuff out.</li></ul><h4>3. Where is the actual data (theme, toggleTheme)?</h4><ul><li>The <strong>real source of truth</strong> is in your <strong>state inside ThemeProvider</strong>:</li></ul><pre>const [theme, setTheme] = useState(&quot;light&quot;);</pre><ul><li>That’s the actual variable where the current theme lives.</li><li>Provider <strong>just makes this state available to every child component</strong> without passing props manually.</li></ul><h4>4. What happens if you don’t wrap with Provider?</h4><p>If you don’t use:</p><pre>&lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;</pre><ul><li>Then your Context is still empty.</li><li>Any component using useContext(ThemeContext) will just get the <strong>default value</strong> (usually undefined unless you set one when creating the context).</li><li>So no theme, no toggle — nothing works.</li></ul><h3>🎁Wrapping Your App</h3><p>Now that you’ve created your ThemeProvider, the next crucial step is to wrap your entire application with it. This makes the theme and toggleTheme functions available to <strong>every single component</strong> within your app, no matter how deeply nested.</p><p>The best place to do this is in your top-level file, which is usually index.js or main.jsx, where your React app is first rendered.</p><p>To give every component in your app access to the theme context, simply import the ThemeProvider you created and wrap the &lt;App /&gt; component with it.</p><pre>// src/main.jsx<br><br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br>import &#39;./index.css&#39;;<br><br>// 🚀 Step 1: Import the ThemeProvider<br>import { ThemeProvider } from &#39;./ThemeContext&#39;; <br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;React.StrictMode&gt;<br>    {/* 🚀 Step 2: Wrap the App component with the ThemeProvider */}<br>    &lt;ThemeProvider&gt; <br>      &lt;App /&gt;<br>    &lt;/ThemeProvider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><h4>What’s Happening Here?</h4><p>By placing &lt;ThemeProvider&gt; around &lt;App /&gt;, you&#39;re ensuring that the value prop—which contains the theme state and the toggleTheme function—is accessible to every component rendered inside &lt;App /&gt;.</p><ul><li><strong>ThemeProvider</strong>: This component provides the context. It manages the state and passes the value down.</li><li><strong>&lt;App /&gt;</strong>: This is your main application component, which contains all your other components.</li><li><strong>children</strong>: The {children} prop inside your ThemeProvider.js file now refers to the &lt;App /&gt; component and everything within it.</li></ul><h3>What is useContext?</h3><p>The useContext hook in React lets you <strong>directly access values from a Context</strong> without having to pass them through props (props drilling).</p><p>Think of useContext as a <strong>shortcut</strong>:<br> 👉 Instead of saying “Hey parent, pass this value down to child → grandchild → great-grandchild”, we just say “Hey React, give me the value from this Context”.</p><p><strong>The </strong><strong>useContext hook </strong>is a React function that allows you to read a context&#39;s value directly from your component. It takes a context object (like the ThemeContext we created) as an argument and returns the <strong>current value</strong> for that context.</p><p>Its main job is to simplify accessing shared data. Before this hook, we had to use a Context.Consumer component, which was more verbose and less intuitive. useContext makes the process cleaner and more &quot;hook-like.&quot;</p><p>Here’s the basic syntax:</p><pre>const value = useContext(MyContext);</pre><ul><li>MyContext: This is the context object you created with createContext().</li><li>value: This will be the current data from the nearest MyContext.Provider above this component in the tree.</li></ul><h4>How useContext Works Behind the Scenes</h4><p>When you use useContext(ThemeContext) in your component, React does three important things:</p><ol><li><strong>It Locates the Provider</strong>: React searches up the component tree from your component’s position to find the <strong>closest</strong> ThemeContext.Provider.</li><li><strong>It Retrieves the Value</strong>: Once it finds the provider, it gets the value prop that the provider is currently supplying.</li><li><strong>It Subscribes the Component</strong>: This is the most critical part. React creates an internal subscription, linking your component to the ThemeContext.Provider. This means that if the value prop of that provider ever changes, React will <strong>automatically re-render</strong> your component to reflect the new data.</li></ol><p>This subscription is why your UI automatically updates when you toggle the theme. The component doesn’t need to be told to re-render; it’s listening for changes from the provider.</p><h4>The Header Component (A Consumer)</h4><p>This component will display the current theme and include a button to toggle it.</p><p><strong>File:</strong> src/components/Header.jsx</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { ThemeContext } from &#39;../context/ThemeContext&#39;;<br><br>const Header = () =&gt; {<br>  // Use the useContext hook to get the theme value<br>  const { theme } = useContext(ThemeContext);<br><br>  // Apply a style based on the theme<br>  const headerStyle = {<br>    padding: &#39;20px&#39;,<br>    backgroundColor: theme === &#39;light&#39; ? &#39;#f0f0f0&#39; : &#39;#333&#39;,<br>    color: theme === &#39;light&#39; ? &#39;#333&#39; : &#39;#fff&#39;,<br>    textAlign: &#39;center&#39;,<br>  };<br><br>  return (<br>    &lt;header style={headerStyle}&gt;<br>      &lt;h1&gt;My Themed App&lt;/h1&gt;<br>      &lt;p&gt;Current Theme: {theme}&lt;/p&gt;<br>    &lt;/header&gt;<br>  );<br>};<br><br>export default Header;</pre><h4>The Button Component (Another Consumer)</h4><p>This component is separate from the Header, but it also needs access to the toggleTheme function to change the theme. It will be located somewhere else in the app, demonstrating that you don&#39;t need to pass props down to it.</p><p><strong>File:</strong> src/components/Button.jsx</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { ThemeContext } from &#39;../context/ThemeContext&#39;;<br><br>const Button = () =&gt; {<br>  // Use the useContext hook to get the toggleTheme function<br>  const { toggleTheme } = useContext(ThemeContext);<br><br>  const buttonStyle = {<br>    padding: &#39;10px 20px&#39;,<br>    backgroundColor: &#39;dodgerblue&#39;,<br>    color: &#39;white&#39;,<br>    border: &#39;none&#39;,<br>    borderRadius: &#39;5px&#39;,<br>    cursor: &#39;pointer&#39;,<br>    marginTop: &#39;20px&#39;,<br>  };<br><br>  return (<br>    &lt;button onClick={toggleTheme} style={buttonStyle}&gt;<br>      Toggle Theme<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default Button;</pre><h4>The App Component (The Layout)</h4><p>The App component will bring the Header and Button together. Notice that we <strong>don&#39;t</strong> pass any props for theme or toggleTheme to either component. They get the data directly from the context.</p><p><strong>File:</strong> src/components/App.jsx</p><pre>import React from &#39;react&#39;;<br>import Header from &#39;./Header&#39;;<br>import Button from &#39;./Button&#39;;<br><br>const App = () =&gt; {<br>  const appStyle = {<br>    minHeight: &#39;100vh&#39;,<br>    display: &#39;flex&#39;,<br>    flexDirection: &#39;column&#39;,<br>    alignItems: &#39;center&#39;,<br>  };<br><br>  return (<br>    &lt;div style={appStyle}&gt;<br>      {/* Header component */}<br>      &lt;Header /&gt;<br>        {/* Button component */}<br>        &lt;Button /&gt;<br>      &lt;/main&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><h4>The Result➡️ :</h4><p><strong>The Initial State</strong></p><p>When the app first loads, here’s what happens:</p><p><strong>1.index.js</strong> renders the &lt;App /&gt; component, which is wrapped inside &lt;ThemeProvider&gt;.</p><p>2. The <strong>ThemeProvider</strong> initializes its state with const [theme, setTheme] = useState(&#39;light&#39;). The value prop is set to { theme: &#39;light&#39;, toggleTheme: ... }.</p><p>4. The <strong>Header.jsx</strong> component renders. It uses useContext(ThemeContext) to get the value from the provider. It receives { theme: &#39;light&#39;, toggleTheme: ... } and correctly displays &quot;Current Theme: light&quot; and sets its background to a light color.</p><p>3. The <strong>Button.jsx</strong> component renders. It also uses useContext(ThemeContext) and receives the same value object. It can now access the toggleTheme function.</p><p>At this point, the entire application is in sync, and both the Header and Button components know the current theme, even though no props were passed to them directly.</p><h4>The State Change (When You Click the Button)</h4><p>This is where the power of the Context API becomes clear.</p><ol><li>A user clicks the<strong> “Toggle Theme” button</strong> in Button.jsx.</li><li>The onClick handler calls the toggleTheme function, which it got from useContext.</li><li>The toggleTheme function calls setTheme. This changes the state inside the <strong>ThemeProvider</strong> from &#39;light&#39; to &#39;dark&#39;.</li><li><strong>Crucially, React detects this state change.</strong> It notices that the value prop being passed to &lt;ThemeContext.Provider&gt; has changed (specifically, the theme property is now &#39;dark&#39;).</li><li>React then finds <strong>all components</strong> that are <strong>subscribed</strong> to this ThemeContext via the useContext hook. In this case, that&#39;s both the Header and Button components.</li><li>React automatically <strong>re-renders</strong> both Header and Button.</li><li>During the re-render, both components run their useContext(ThemeContext) hooks again. This time, they get the new value: { theme: &#39;dark&#39;, toggleTheme: ... }</li><li>The <strong>Header</strong> component updates its display to &quot;Current Theme: dark&quot; and changes its background to a dark color. The <strong>Button</strong> doesn&#39;t change its appearance (since its style is not tied to the theme), but its onClick handler now has access to the updated toggleTheme function, which will correctly toggle the theme back to &#39;light&#39;.</li></ol><blockquote>The Key Takeaway</blockquote><p>The result is a fully functional, dynamic UI where a single action in one component (Button) automatically triggers an update in another component (Header) without any need for complex state management, prop drilling, or direct communication between the two. The ThemeProvider acts as the single source of truth, and useContext provides a simple way for any component to access that truth and subscribe to its changes.</p><h3>Analogy</h3><p>Think of Context API as a <strong>global whiteboard</strong> in an office building.</p><ul><li>The <strong>Provider</strong> is the person who writes on the whiteboard. They can put any information on it.</li><li>The <strong>useContext</strong> hook is a person on any floor of the building who can look at the whiteboard and read the information on it directly, without needing to ask the person on the floor above them.</li><li>When the person with the marker changes the information on the whiteboard, everyone looking at it sees the update immediately.</li></ul><h3>🚀 Key Components of Context API</h3><ul><li><strong>createContext</strong>: This function creates a new Context object. Think of it as creating a channel or a public &quot;storage locker&quot; for data. By itself, it doesn&#39;t hold any data.</li><li><strong>Provider</strong>: This is a React component that comes with every context object. Its job is to &quot;provide&quot; the data. You wrap the parts of your component tree that need access to the data with a Provider component and pass the data to its value prop. All components inside the Provider can then &quot;consume&quot; this data.</li><li><strong>useContext</strong>: This is a React hook that allows a functional component to &quot;consume&quot; or read the data from a context. When you use useContext with a context object, it automatically gives your component the current value from the nearest Provider above it in the component tree. It also creates a <strong>subscription</strong>, so if the data in the Provider changes, your component automatically re-renders with the new data.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f05437d17120" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authentication in Node.js: From Basics to JWT Implementation]]></title>
            <link>https://medium.com/@dipikagandash411/authentication-in-node-js-from-basics-to-jwt-implementation-40b914ec4d1c?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b914ec4d1c</guid>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 17:34:06 GMT</pubDate>
            <atom:updated>2025-06-26T17:34:06.148Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XbZxKQq_vhpmHX8Pa8hkAA.jpeg" /></figure><h3>🔐 What is Authentication?</h3><p><strong>Authentication</strong> is the process of <strong>verifying the identity of a user or system</strong>. It answers the basic question:</p><blockquote><strong><em>“Are you really who you say you are?”</em></strong></blockquote><p>When you log in to a website or app by entering your <strong>username and password</strong>, you’re going through <strong>authentication</strong>. The system checks the credentials you provide and verifies if they match a valid user in the database.</p><h4><strong>Real-Life Example:</strong></h4><p>Think of a <strong>college entrance gate</strong>.<br> To enter, you must show your <strong>ID card</strong> — this is your <strong>proof of identity</strong>.<br> The guard checks it against the college’s records.<br> If it matches, you’re <strong>authenticated</strong> and allowed to enter.</p><h4>🚫 What If There’s No Authentication?</h4><p>Without authentication:</p><ul><li><strong>Anyone can open your account</strong> and see your private data.</li><li>Hackers can <strong>act like you</strong> and misuse your profile.</li><li>People can <strong>change or delete important information</strong>.</li><li>There will be <strong>no security</strong> — anyone can do anything.</li></ul><p><strong>💡 Example:</strong></p><p>Imagine you open your email inbox — but there’s <strong>no login</strong>. Anyone who visits the site can read your emails. That’s what happens when there’s no authentication!</p><h4>✅ So, Why Is It Needed?</h4><p>We need authentication to:</p><ul><li>Keep data safe</li><li>Make sure only the right person can access their account</li><li>Protect the website from misuse</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*kolIMUuFq2m2WRe-CiXXFg.png" /></figure><h4>Imagine this:</h4><p>You open a social media website.</p><ol><li>You log in.</li><li>You go to your <strong>profile page</strong> → but first, the browser has to create a connection → send login again → then it gives your profile.</li><li>Now you go to the <strong>feed page</strong> → again it says:<br> <strong>“Please login to view feed.”</strong><br> So you enter your login again 😩</li><li>You like someone’s post → again it says:<br> <strong>“Please login to like this post.”</strong></li></ol><p>You’d be like:</p><blockquote><em>“Why do I have to login again and again for everything? I already logged in!”</em></blockquote><p>This would be <strong>super frustrating</strong> for users.<br> No one wants to enter their email and password for <strong>every click</strong> they make.</p><h4>🚀 That’s Why Authentication Systems Are Built Smartly</h4><p>To <strong>avoid repeated logins</strong>, we use:</p><h4>✅ Sessions (Stateful)</h4><p>or</p><h4>✅ Tokens (Stateless)</h4><p>Once you’re logged in:</p><ul><li>The server <strong>remembers you</strong> (in stateful),</li><li>or you send a <strong>token</strong> that proves who you are (in stateless),</li></ul><p>So you can:</p><ul><li>Open your profile ✅</li><li>Go to the feed ✅</li><li>Like a post ✅</li><li>Comment ✅</li><li>Even open settings ✅</li></ul><p><strong>All without logging in again.</strong><br> Just <strong>one login → full access</strong> (until you log out or your session/token expires).</p><h3>🆚 Stateful vs Stateless Authentication</h3><p>When a user logs in, the website needs a way to remember them.<br> There are <strong>two ways</strong> to do this:</p><h3>🧠 Stateful Authentication</h3><p>To solve the problem of asking the user to log in again and again, we use something called <strong>Stateful Authentication</strong>.</p><h4><strong>It means:</strong></h4><p>Once the user logs in, the <strong>server remembers who they are</strong> by creating a <strong>session</strong>.</p><p>So the next time the user opens profile, feed, likes a post, or does anything — the server already knows:</p><blockquote><em>“Oh yes, I remember this user. They are logged in.”</em></blockquote><h4>🔁 How it Works (In Simple Steps):</h4><ol><li>User logs in with email and password.</li><li>The server checks the credentials.</li><li>If correct, the server creates a <strong>session</strong> (like a memory note) that says:</li></ol><pre>sessionId: abc123 → belongs to Dipika</pre><p>4. This session ID is sent to the browser and stored as a <strong>cookie</strong>.</p><p>5. From now on, whenever the browser makes a request (like /profile, /feed, /like-post), it automatically sends that <strong>session ID</strong> with the request.</p><p>The server looks at the session ID and says:</p><blockquote><em>✅ “Session ID abc123? That’s Dipika! Let her in.”</em></blockquote><h4>🧾 Real-Life Example:</h4><p>Think of it like going to a restaurant.</p><ul><li>You get a <strong>token</strong> (session) after you place your order.</li><li>You don’t need to say your name again and again — just show the token.</li><li>The waiter remembers your table, your order — everything.</li></ul><p>That’s <strong>stateful authentication</strong> — the <strong>server (waiter)</strong> keeps track of you using the <strong>session (token)</strong>.</p><h4>📦 Where is the “state”?</h4><p>The <strong>“state”</strong> (session info) is saved on the <strong>server</strong> — either in memory, database, or some cache like Redis.</p><h3>🧾 What is a Session?</h3><p>A <strong>session</strong> is like a <strong>temporary memory</strong> that the server uses to <strong>remember the logged-in user</strong>.</p><p>When you log in, the server says:</p><blockquote><em>“Okay, I’ll remember you for some time.”</em></blockquote><p>And it stores your login info (like user ID, name, etc.) in a special storage called a <strong>session store</strong>.</p><h3>🆔 What is a Session ID?</h3><p>The server doesn’t send all your user data to the browser (that’s unsafe).<br> Instead, it creates a <strong>unique random string</strong> like:</p><pre>sessionId = &quot;abc123xyz&quot;</pre><p>This is like your <strong>identity token</strong>, but only the server knows what it really means.</p><p>The server stores it like this:</p><pre>sessionId: &quot;abc123xyz&quot; → {<br>   userId: 101,<br>   name: &quot;Dipika&quot;,<br>   email: &quot;dipika@example.com&quot;<br>}</pre><p>Then it sends only the session ID to the browser and stores it as a <strong>cookie</strong>:</p><pre>Set-Cookie: sessionId=abc123xyz</pre><h3>📦 What Happens Behind the Scenes (Step-by-Step)</h3><h4>🔐 Step 1: User Logs In</h4><ol><li>User fills login form.</li><li>Server checks the email &amp; password.</li><li>If correct:</li></ol><ul><li>Server creates a session:</li></ul><pre>sessionId: &quot;abc123xyz&quot; → { userId: 101, name: &quot;Dipika&quot; }</pre><p>Sends this sessionId to the browser as a cookie.</p><h4>📲 Step 2: User Makes a Request (e.g. /profile)</h4><ol><li>Browser sends request:</li></ol><pre>GET /profile<br>Cookie: sessionId=abc123xyz</pre><p>2. Server reads the sessionId from the cookie.</p><p>3. It looks up in session storage:</p><pre>Does sessionId &quot;abc123xyz&quot; exist?<br>→ Yes! It&#39;s Dipika.</pre><p>4. Server knows the user is authenticated → sends profile data in response</p><h4>🔁 This Happens Automatically for Every Request</h4><p>The browser automatically sends the session cookie on every request.<br> The server just reads it and checks the session store.</p><p>You don’t have to log in again and again — the <strong>session handles it all!</strong></p><h4>🧠 Where is Session Data Stored?</h4><ul><li>In memory (for small apps)</li><li>In databases (like MongoDB, PostgreSQL)</li><li>Or in fast storage like <strong>Redis</strong> (for big apps)</li></ul><h4>🔒 What Happens on Logout?</h4><ul><li>Server <strong>deletes the session</strong> from its session store.</li><li>So next time, even if browser sends the old session ID, the server replies:</li></ul><pre>Session not found → Please login again.</pre><h3>🍪 What is a Cookie?</h3><p>A <strong>cookie</strong> is a <strong>small piece of data</strong> that the <strong>server stores in the user’s browser</strong>.</p><p>It’s like giving the browser a <strong>mini note</strong> and saying:</p><blockquote><em>“Keep this safe and send it back to me every time you visit.”</em></blockquote><h4>💡 Example:</h4><p>When you log in to a website, the server may say:</p><blockquote><em>“Hey browser, here’s your cookie:<br> </em><em>sessionId = abc123xyz — send this to me every time you visit.&quot;</em></blockquote><p>And the browser <strong>automatically sends</strong> this cookie with every request.</p><h4>📬 Cookies = Automatic ID Carrier</h4><p>When you store sessionId in a cookie:</p><ul><li>The browser will <strong>automatically send it</strong> with each request.</li><li>You don’t have to manually attach the session ID again and again.</li><li>This makes the <strong>login experience smooth</strong> for users.</li></ul><h4>🔒 Are Cookies Safe?</h4><p>Cookies themselves can be made secure:</p><p>HttpOnly : JS can&#39;t access the cookie (safer from XSS attacks)</p><p>Secure : Only sent over HTTPS (not plain HTTP)</p><p>SameSite : Controls cross-site request behavior (CSRF protection)</p><h3>🧠 Stateless Authentication</h3><p><strong>Stateless Authentication</strong> means that the <strong>server does not remember anything about the user</strong> between requests.</p><p>Instead, <strong>the user proves their identity</strong> on every request using something like a <strong>token (usually a JWT)</strong>.</p><blockquote><em>So there is </em><strong><em>no session saved on the server</em></strong><em> — the user must </em><strong><em>carry their own identity</em></strong><em> in the form of a token.</em></blockquote><h4>💡 Real-Life Example:</h4><p>Imagine you’re at an <strong>airport</strong> ✈️.</p><p>When you check in, you get a <strong>boarding pass</strong> with all your flight details — your name, seat number, gate, etc.</p><p>Now, wherever you go — security check, boarding gate, food counter — <br> you don’t need to introduce yourself again or explain your details.</p><p>You simply <strong>show the same boarding pass</strong>, and they <strong>verify it</strong> and allow you to pass.</p><p>✅ They don’t remember you — they just check the pass.<br> ✅ You carry your identity with you.</p><h4>🔁 This is exactly how Stateless Authentication works:</h4><ul><li>The <strong>boarding pass = JWT token</strong></li><li>You send it on <strong>every request</strong></li><li>The <strong>server = airport staff</strong> just verifies it</li><li>No one stores your identity — it’s all in the <strong>token you carry</strong></li></ul><h3>🔐 JWT (JSON Web Token)</h3><p><strong>JWT (JSON Web Token)</strong> is a <strong>compact, secure way</strong> to share <strong>user identity data</strong> between the client (browser) and server.</p><p>It’s like a <strong>digital ID card</strong> the server gives you after you log in — and you carry it with you (usually stored in localStorage or cookie).<br> You send this token on <strong>every request</strong>, and the server verifies it to know who you are.</p><h4>🧾 Real-Life Example:</h4><p>You log in → the server gives you a <strong>signed token (JWT)</strong> →<br> You go to /profile, /feed, /settings → you <strong>show the token</strong> every time →<br> Server verifies → ✅ access granted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmFjcpxsqurscHW9vF6fXw.png" /></figure><h4>✨ Why use JWT?</h4><p>Traditional session-based authentication stores user data <strong>on the server</strong> (like in session memory or database), which doesn’t scale well.</p><p>JWT enables <strong>stateless authentication</strong>:</p><ul><li>No server-side session storage is required.</li><li>The server just <strong>verifies the token</strong> that the client sends in every request.</li></ul><h4>🔍 JWT Structure</h4><p>A <strong>JWT (JSON Web Token)</strong> looks like this:</p><pre>xxxxx.yyyyy.zzzzz</pre><p>It’s made of <strong>three parts</strong>, separated by dots (.):</p><ol><li><strong>Header</strong> (xxxxx)</li><li><strong>Payload</strong> (yyyyy)</li><li><strong>Signature</strong> (zzzzz)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*7bs0RXugjcBbGlUVcfIY6w.jpeg" /></figure><h4>1. Header</h4><p>The <strong>header</strong> contains <strong>metadata</strong> about the token:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,   // the signing algorithm<br>  &quot;typ&quot;: &quot;JWT&quot;       // type is JWT<br>}</pre><ul><li><strong>alg</strong> = Algorithm used to create the signature (like HS256).</li><li>This is important because the server will use the same algorithm to <strong>verify the signature</strong> later.</li></ul><h4>2. Payload (yyyyy) — the actual data</h4><p>This is the <strong>heart of the token</strong>. It contains the <strong>data about the user</strong> and other information.</p><pre>{<br>  &quot;userId&quot;: &quot;abc123&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;iat&quot;: 1719332077,<br>  &quot;exp&quot;: 1719335677<br>}</pre><h4>What’s inside the payload?</h4><ol><li><strong>Custom data</strong> — like userId, email, role, etc.</li></ol><ul><li>This is added when the token is created and is later <strong>read by the server</strong> to know <em>who</em> the user is.</li></ul><p><strong>2. Standard claims</strong>:</p><ul><li>iat = issued at (timestamp)</li><li>exp = expires at (timestamp)</li><li>sub, iss, etc. (optional)</li></ul><h4>How is this used?</h4><p>The <strong>payload is not encrypted</strong>, just <strong>Base64-encoded</strong>. So:</p><ul><li>The client <strong>receives</strong> the token after logging in.</li><li>Later, the client <strong>sends the token back</strong> with each API request.</li><li>The server <strong>reads the payload</strong> after verifying it using the <strong>signature</strong>.</li><li>It helps the server know which user is making the request (without checking the DB every time).</li></ul><p>📌 <strong>Important:</strong> The server <strong>does not trust the payload directly</strong> — it first <strong>verifies the signature</strong> to check if it’s tampered with.</p><h4>🔐 3. Signature (zzzzz) — to verify authenticity</h4><p>This part <strong>protects</strong> the token.</p><p>It’s created like this:</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),<br>  secret<br>)</pre><p>This means:</p><ul><li>The header and payload are <strong>encoded</strong>.</li><li>They are <strong>combined with a secret key</strong>.</li><li>Then hashed using SHA256 (or whatever algorithm you chose).</li><li>The output is the <strong>signature</strong>.</li></ul><h4>❓ Why is signature important?</h4><p>It <strong>proves</strong> that:</p><ul><li>The token was really created by your server.</li><li>The data (header &amp; payload) hasn’t been changed or hacked.</li></ul><p>If anyone <strong>modifies</strong> the payload (like changing the email to admin@site.com), the signature will no longer match, and the server will <strong>reject</strong> it.</p><h4>🔑 What is the secret key?</h4><p>The <strong>secret key</strong> is a private value only the server knows. It’s stored in your .env file:</p><pre>JWT_SECRET=&quot;mySuperSecretKey123&quot;</pre><p>It is used to:</p><ul><li><strong>Sign</strong> the token when it’s created.</li><li><strong>Verify</strong> the token when the client sends it back.</li></ul><p>🛡️ If someone doesn’t know your secret key, they <strong>cannot modify</strong> your tokens.</p><h3>How to Create a JWT Token ❓</h3><h4>Step 1: Install the required packages</h4><pre>npm install jsonwebtoken </pre><h4>Step 2: Setup project file</h4><p>app.js :</p><pre>const express = require(&quot;express&quot;);<br>const jwt = require(&quot;jsonwebtoken&quot;);<br>const dotenv = require(&quot;dotenv&quot;);<br><br>dotenv.config(); // to use .env variables<br><br>const app = express();<br>app.use(express.json()); // to parse JSON body<br><br>const PORT = 5000;</pre><h4>Step 3: Create a .env file with a secret key</h4><p>Create .env in the root folder:</p><pre>JWT_SECRET=yourSuperSecretKey123</pre><p>This key is private — used to <strong>sign and verify</strong> tokens.</p><h4>Step 4: Simulate a login route to generate token</h4><pre>app.post(&quot;/login&quot;, async(req, res) =&gt; {<br>  const {email, password} = req.body;<br><br>  try{<br>   const user = await User.findOne({email : email});<br>   if(!user){<br>   throw new Error(&quot;Invalid credentials!&quot;);<br>   }<br><br>   const isPasswordValid = await bcrypt.compare(password, user.password);<br>   if(!isPasswordValid){<br>    return res.status(401).send(&quot;Incorrect Password&quot;);<br>   }<br><br>   const token = await jwt.sign({_id : user._id, email : user.email}, process.env.JWT_SECRET_KEY, {expiresIn : &quot;1h&quot;});<br>    res.cookie(&quot;token&quot;, token);<br>   const {firstName, lastName, bio} = user;<br>   res.json({<br>    message : &quot;Login Successful!&quot;,<br>    firstName, <br>    lastName, <br>    bio<br>   })<br><br>  } catch(error){<br>    return res.status(400).send(error.message);<br>  }<br>})</pre><p>if email and password are valid then server will create a jwt token for particular user.</p><h4>Step 5: What happens in jwt.sign()</h4><p>Syntax :</p><pre>const token = jwt.sign(payload, secret, options);</pre><p><strong>Here’s what’s inside:</strong></p><ul><li>payload: your data (like userId, email)</li><li>secret: your private key (process.env.JWT_SECRET)</li><li>options: like expiresIn, issuer, etc.</li></ul><pre>  const token = await jwt.sign({_id : user._id, email : user.email}, process.env.JWT_SECRET_KEY, {expiresIn : &quot;1h&quot;});</pre><p>This line creates a <strong>JWT token</strong> containing:</p><ul><li>The user’s _id and email (called the <strong>payload</strong>)</li><li>Signed using a secret &quot;abc123xyz&quot; (for verifying later)</li><li>Set to <strong>expire in 1 hour</strong></li></ul><p>Now let’s go <strong>behind the scenes :</strong></p><h3>⚙️ Step-by-Step Behind the Scenes</h3><h4>Step 1: Create the Header</h4><p>JWT first builds the <strong>header</strong>:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><ul><li>alg: Algorithm used to sign (HMAC SHA-256 here)</li><li>typ: This is a JWT token</li></ul><p>This is a <strong>JSON object</strong> → it gets converted to a string:</p><pre>&#39;{&quot;alg&quot;:&quot;HS256&quot;,&quot;typ&quot;:&quot;JWT&quot;}&#39;</pre><p>Then <strong>base64url-encoded</strong> to:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9</pre><h4>Step 2: Create the Payload</h4><p>This is the <strong>data</strong> you want to include in the token:</p><pre>{<br>  &quot;_id&quot;: &quot;user123&quot;,<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;,<br>  &quot;iat&quot;: 1719332077,  // Issued At (automatically added)<br>  &quot;exp&quot;: 1719335677   // Expires In 1 Hour (calculated automatically)<br>}</pre><p>Note:</p><ul><li>iat (issued at): when token is created</li><li>exp (expires at): iat + 1 hour</li></ul><p>Convert to string:</p><pre>&#39;{&quot;_id&quot;:&quot;user123&quot;,&quot;email&quot;:&quot;dipika@gmail.com&quot;,&quot;iat&quot;:1719332077,&quot;exp&quot;:1719335677}&#39;</pre><p>Then base64url-encoded:</p><pre>eyJfaWQiOiJ1c2VyMTIzIiwiZW1haWwiOiJkaXBpa2FAZ21haWwuY29tIiwiaWF0IjoxNzE5MzMyMDc3LCJleHAiOjE3MTkzMzU2Nzd9</pre><h4>Step 3: Create the Signature</h4><p>Now comes the magic 💫 — the <strong>signature</strong>.</p><p>JWT uses:</p><pre>signature = HMAC-SHA256(<br>  header + &quot;.&quot; + payload,<br>  secret = &quot;abc123xyz&quot;<br>)</pre><p>So:</p><ul><li>Combines header.payload</li></ul><p>combined string</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJ1c2VyMTIzIiwiZW1haWwiOiJkaXBpa2FAZ21haWwuY29tIiwiaWF0IjoxNzE5MzMyMDc3LCJleHAiOjE3MTkzMzU2Nzd9</pre><p>Now the important part: <strong>Creating the Signature</strong></p><pre>signature = HMACSHA256( header.payload, secret )</pre><p>Here’s what happens:</p><ul><li>JWT runs the combined string through a hashing function: <strong>HMAC-SHA256</strong></li><li>It <strong>uses your secret key</strong> in that hashing</li></ul><h4><strong>What is HMAC-SHA256?</strong></h4><p>It’s a type of <strong>hashing algorithm</strong> that takes:</p><ul><li>A <strong>message</strong> = (your header.payload string)</li><li>A <strong>secret</strong> = (like &quot;abc123xyz&quot;)</li></ul><p>And generates a unique string called the <strong>signature</strong>:</p><pre>ywF3dB5xZpO2gR2lTz8S7zC89t7oXZVZRWK1bEkq5Lo</pre><p>Even a tiny change in header, payload, or secret will create a completely different signature.</p><p>So:</p><ul><li>This signature guarantees: <strong>“This token was created by the server and hasn’t been changed.”</strong></li></ul><h4><strong><em>Final JWT Token :</em></strong></h4><p>Putting it all together:</p><pre>&lt;header&gt;.&lt;payload&gt;.&lt;signature&gt;</pre><p>For example:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<br>eyJfaWQiOiJ1c2VyMTIzIiwiZW1haWwiOiJkaXBpa2FAZ21haWwuY29tIiwiaWF0IjoxNzE5MzMyMDc3LCJleHAiOjE3MTkzMzU2Nzd9.<br>ywF3dB5xZpO2gR2lTz8S7zC89t7oXZVZRWK1bEkq5Lo</pre><h4>Step 6: Send token to client</h4><pre>res.cookie(&quot;token&quot;, token, { httpOnly: true });</pre><h4>Step 7: Test it</h4><p>Use <strong>Postman</strong>:</p><ul><li>Send a POST request to <a href="http://localhost:5000/login">http://localhost:5000/login</a></li></ul><pre>{<br>  &quot;email&quot;: &quot;dipika@gmail.com&quot;,<br>  &quot;password&quot;: &quot;123456&quot;<br>}</pre><p>You’ll get a token in response ✅</p><h3>How JWT Verification Works</h3><p>Verifying a JWT means:</p><ol><li><strong>Checking if the token is valid (not tampered)</strong></li><li><strong>Checking if it’s not expired</strong></li><li><strong>Extracting the user info (from the payload)</strong></li></ol><p>This is done using:</p><pre>const decoded = jwt.verify(token, process.env.JWT_SECRET);</pre><p>Suppose the client sends a request like this:</p><pre>GET /profile</pre><p>Now here’s what happens behind the scenes:</p><h4>Step 1: Extract the token from the request</h4><p>You’ll typically get the token from:</p><ul><li>Authorization header (most common)</li><li>or a cookie (if you stored it there)</li></ul><pre>const {token} = req.cookies;</pre><h4>Step 2: Verify the token using jwt.verify</h4><pre>const decoded = jwt.verify(token, process.env.JWT_SECRET);</pre><p>What this does internally:</p><ol><li><strong>Splits the token</strong> into:</li></ol><pre>[header].[payload].[signature]</pre><p><strong>2. Recreate the signature from header and payload</strong>:</p><ul><li>header + payload</li><li>your server’s secret (process.env.JWT_SECRET)</li><li>same algorithm (e.g., HMAC-SHA256)</li></ul><p><strong>3. Compares</strong> the recreated signature with the one in the token:</p><ul><li>If they match → ✅ token is valid</li><li>If not → ❌ token is rejected</li></ul><p>This signature is <strong>unique</strong> for each:</p><ul><li>payload</li><li>header</li><li>secret</li></ul><p>Even 1-letter change = whole signature changes ⚠️</p><p><strong>4. Checks the expiry time (</strong><strong>exp)</strong>:</p><ul><li>If expired → ❌ rejected with TokenExpiredError</li><li>If still valid → ✅ allowed</li></ul><p>5. If valid, it <strong>returns the decoded payload</strong>:</p><pre>{<br>  _id: &#39;user123&#39;,<br>  email: &#39;dipika@gmail.com&#39;,<br>  iat: 1719332077,<br>  exp: 1719335677<br>}</pre><p>Example : GET /profile</p><pre>app.get(&quot;/profile&quot;, async (req, res) =&gt; {<br>  const {token} = req.cookies;<br>  if(!token){<br>    return res.status(401).send(&quot;Unauthorized! Please login first.&quot;)<br>  }<br><br>  try{<br>    const decodedMessage = await jwt.verify(token, process.env.JWT_SECRET_KEY);<br>    console.log(decodedMessage);<br><br>  const user = await User.findById(decodedMessage._id);<br>  if(!user){<br>    return res.status(404).send(&quot;User not found&quot;);<br>  }<br>  <br>  res.json({<br>    firstName : user.firstName, <br>    lastName : user.lastName,<br>    email : user.email,<br>    bio : user.bio<br>  })<br><br>  } catch(error){<br>    return res.status(500).send(&quot;Error fetching profile :&quot; + error.message);<br>  }<br>})</pre><h3>🔓 Logout Functionality</h3><p>Logging out a user in a JWT-based system is a bit different from traditional session-based authentication, since JWT is <strong>stateless</strong>. However, if you’re storing the JWT token in a <strong>cookie</strong>, you can simply clear that cookie to log the user out.</p><p>Here’s how to implement the logout route :</p><pre>app.get(&quot;/logout&quot;, (req, res) =&gt; {<br>  res.clearCookie(&quot;token&quot;); // replace &#39;token&#39; with your cookie name<br>  res.send(&quot;User logged out successfully&quot;);<br>});</pre><ul><li>res.clearCookie(&quot;token&quot;): This removes the JWT cookie from the browser.</li><li>After this, the user’s browser no longer sends the token with requests.</li><li>As a result, protected routes will now reject the user since there’s no valid token.</li></ul><h3>🔐 Stateful vs Stateless Authentication</h3><h4>1. Core Working Principle</h4><ul><li>In <strong>stateful authentication</strong>, once a user logs in, the server creates a session and stores user-specific data like session ID in memory or a database. The client receives a session ID, usually stored in cookies, and sends it with every request. The server uses this session ID to find the user’s details.</li><li>In <strong>stateless authentication</strong>, the server does not store any session data. Instead, it issues a token (usually JWT) that holds the user’s information. This token is stored on the client-side and sent with each request. The server verifies the token without needing to remember anything from the past.</li></ul><h4>2. Scalability &amp; Load Balancing</h4><ul><li><strong>Stateful systems</strong> are not ideal for scaling across multiple servers. If sessions are stored in a specific server’s memory, load balancing becomes difficult unless you implement sticky sessions or use a shared session store like Redis. It adds extra infrastructure complexity.</li><li><strong>Stateless systems</strong> are naturally scalable. Since no session is stored on the server, any server can validate a request as long as it can verify the token. This makes stateless authentication perfect for microservices, distributed systems, and cloud-based applications.</li></ul><h4>3. Performance Impact</h4><ul><li><strong>Stateful systems</strong> require a lookup in the session store for each request, which can slightly affect performance at scale.</li><li><strong>Stateless systems</strong> are faster. Once the token is issued, the server just verifies it (locally or using a public key, if signed). There’s no lookup delay, making it lightweight and fast for APIs and mobile clients.</li></ul><h3>4. Real-World Suitability</h3><ul><li>Choose <strong>stateful authentication</strong> if your app is small or medium-scale, or where strict session control is required — such as admin panels, banking systems, or apps where logging users out instantly is important.</li><li>Go for <strong>stateless authentication</strong> if you’re building SPAs (Single Page Applications), mobile apps, or distributed systems that require high scalability and flexibility — JWT is the most common approach here.</li></ul><h3>Final Thoughts</h3><p>Both approaches have their own strengths. <strong>Stateful</strong> is simple and secure for smaller apps or where logout/session expiration needs full control. <strong>Stateless</strong>, on the other hand, supports modern architectures, horizontal scaling, and is ideal for APIs.</p><p>As a developer, your choice should be based on your project’s needs. If you’re building something scalable, cloud-ready, and service-oriented — <strong>stateless JWT authentication is the way forward.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b914ec4d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Hash Passwords Securely in Node.js Using Bcrypt]]></title>
            <link>https://medium.com/@dipikagandash411/how-to-hash-passwords-securely-in-node-js-using-bcrypt-610ae3e100a9?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/610ae3e100a9</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[hashing-and-salting]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 14:03:36 GMT</pubDate>
            <atom:updated>2025-06-22T14:03:36.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*06JZlrnNws4FeJxiLmi4MQ.jpeg" /></figure><p><strong>Imagine this:</strong><br> You’re building a user login system and everything works fine. Users can sign up, log in, and you’re storing their email and password in your MongoDB database.</p><p>But here’s the problem — you’re saving the password exactly as the user typed it.</p><p>Now ask yourself:</p><ul><li>What if someone gets access to your database?</li><li>What if a developer, admin, or employee can see those raw passwords?</li><li>What if the database is leaked in a security breach?</li></ul><p>Yes — <strong>everyone’s password would be exposed in plain text</strong>.</p><p>This is a <strong>huge security risk</strong> and one of the most common mistakes beginners make. That’s why we <strong>never store plain passwords</strong> — instead, we <strong>hash them</strong> before saving.</p><p>In this blog, you’ll learn:</p><ul><li>✅ What hashing is</li><li>🔐 How to hash passwords securely using <strong>bcrypt</strong> in <strong>Node.js</strong></li><li>🛡️ How to store and compare hashed passwords safely in MongoDB</li></ul><p>Let’s get started!</p><h3>🔑 What is Hashing?</h3><p><strong>Hashing</strong> is a one-way process of converting plain data (like a password) into a fixed-length string of characters — called a <strong>hash</strong>.</p><p><strong>Hashing</strong> is a way to convert your actual password (like mypassword123) into a long, random-looking string — called a <strong>hash</strong>.</p><p>For example:</p><pre>mypassword123 → $2b$10$z8yA1H6Pv03F/dp8x5PAAuTnDW8NDnRuKr8Xy5n.tR4PCmRnOfjIy</pre><p>Once hashed, the original password <strong>can’t be converted back</strong>. That’s why hashing is called a <strong>one-way process</strong>.</p><p>So even if someone sees your database, they won’t know the real passwords — only these random hash strings.</p><p>For passwords, we use <strong>hashing</strong> because we don’t want anyone — not even the developers — to ever retrieve the original password. We just need a way to <strong>check</strong> if the user entered the correct password. And that’s exactly what hashing lets us do.</p><h3>🔐 What is Bcrypt?</h3><p>When users sign up on your website, they enter their password — and it’s your job to <strong>keep that password safe</strong>.</p><p>But storing the real password in your database is <strong>dangerous</strong>.<br> If someone hacks your system, all your users’ passwords will be exposed.</p><p>That’s where <strong>Bcrypt</strong> comes in.</p><h4>🛡️ Bcrypt is a password-hashing library</h4><p>It <strong>converts plain text passwords into unreadable strings</strong> (called hashes), so even if your database gets leaked — the actual passwords are still hidden.</p><p>Here’s how Bcrypt helps:</p><ul><li>✅ <strong>Hashes passwords</strong> — turns them into unreadable code</li><li>✅ <strong>Adds salt</strong> — a random string to make each hash unique</li><li>✅ <strong>Slows down hackers</strong> — it’s designed to be slow, so brute-force attacks take much longer</li></ul><h3>🛠️ How to Use Bcrypt in Node.js</h3><p>Using <strong>Bcrypt</strong> in your Node.js project is easy. You just need to install it, hash the password while signing up, and compare it during login</p><p><strong>✅ Step 1: Install Bcrypt</strong></p><pre>npm install bcrypt</pre><p><strong>✅ Step 2: Import Bcrypt</strong></p><p>At the top of your file, import it like this:</p><pre>const bcrypt = require(&#39;bcrypt&#39;);</pre><h3>Hash the Password (During Signup)</h3><p>Here’s our current code:</p><pre>app.post(&quot;/signup&quot;, async (req, res) =&gt; {<br>  const { firstName, lastName, email, password, age} =<br>    req.body;<br><br>  try {<br>    const user = new User({<br>      firstName,<br>      lastName,<br>      email,<br>      password, // ❌ this is plain text<br>      age<br>    });<br><br>    await user.save();<br>    res.send(&quot;User created successfully&quot;);<br>  } catch (error) {<br>    res.status(500).send(&quot;Error creating user : &quot; + error.message);<br>  }<br>});</pre><p>In this code, we are saving the <strong>plain password</strong> directly — which is very risky!</p><h3>✅ bcrypt.hash()</h3><p>bcrypt.hash() is a method provided by the <strong>bcrypt</strong> library in Node.js. It is used to <strong>securely hash passwords</strong> before storing them in a database like MongoDB.</p><p><strong>Syntax :</strong></p><pre>bcrypt.hash(password, saltRounds, callback);</pre><p>Or using async/await:</p><pre>const hashedPassword = await bcrypt.hash(password, saltRounds);</pre><p><strong>📌 Parameters Explained</strong></p><p>password : The plain text password you want to hash (e.g., &quot;mypassword123&quot;)</p><p>saltRounds :A number that defines the <strong>cost factor</strong> (recommended: 10)</p><p>callback(Optional) : A function that runs after hashing is done</p><p>hashedPassword :+The final hash string you’ll store in your database</p><h3>⚙️ How Does bcrypt.hash() Work Internally?</h3><p>When you call:</p><pre>bcrypt.hash(&quot;mypassword123&quot;, 10);</pre><p>Here’s what happens <strong>behind the scenes</strong>:</p><h4><strong>1. Salt is Generated</strong></h4><p><strong>Salting</strong> is the process of adding a <strong>random string of characters</strong> to a password <em>before</em> hashing it.</p><p>Why?<br> To make the final hash <strong>unique</strong>, even if two users have the same password.</p><blockquote>Bcrypt automatically generates a salt based on the saltRounds you give.</blockquote><p>Example :</p><pre>const salt = bcrypt.genSaltSync(10); // auto-generated inside bcrypt.hash()</pre><h4>🔄 What Are Salt Rounds in Bcrypt?</h4><p><strong>Salt rounds</strong> determine <strong>how many times</strong> the hashing algorithm runs to generate the final password hash.</p><p>When you write:</p><pre>bcrypt.hash(password, 10);</pre><p>The 10 is the <strong>salt rounds</strong> — also called the <strong>cost factor</strong>.</p><h4>🧠 What Do Salt Rounds Actually Do?</h4><p>When you hash a password using bcrypt, it doesn’t just run the hashing algorithm once — it runs it <strong>2^saltRounds</strong> times.</p><p>So if:</p><ul><li>saltRounds = 10 → ²¹⁰ = <strong>1,024 rounds</strong></li><li>saltRounds = 12 → ²¹² = <strong>4,096 rounds</strong></li><li>saltRounds = 15 → ²¹⁵ = <strong>32,768 rounds</strong></li></ul><p>The higher the number, the <strong>more time it takes</strong> to hash the password.</p><h4><strong>⚖️ Why Is This Important?</strong></h4><ul><li>✅ <strong>More rounds = more secure</strong>, because it takes longer to hash — which <strong>slows down hackers</strong> trying to brute-force passwords.</li><li>❌ <strong>Too few rounds = fast, but unsafe</strong>, because hackers can try millions of guesses quickly.</li><li>❌ <strong>Too many rounds = too slow</strong>, even for your real users during sign-up/login</li></ul><h3>💡 What Salt Rounds Should You Use?</h3><p>The number of salt rounds you choose affects both <strong>security</strong> and <strong>performance</strong>. As the number of rounds increases, the hashing process becomes slower — which is good for security (it slows down hackers), but too many rounds can also slow down your app’s login and signup process for real users.</p><p>Here are some commonly used values:</p><ul><li>🔹 <strong>8 rounds</strong> — Fast, but not recommended anymore. It’s too quick and easier for attackers to brute-force.</li><li>🔹 <strong>10 rounds</strong> — The most commonly used and recommended value. It provides a good balance between <strong>security</strong> and <strong>performance</strong>.</li><li>🔹 <strong>12 rounds</strong> — More secure than 10, but slightly slower. Good for apps that need higher protection (e.g., finance-related).</li><li>🔹 <strong>14+ rounds</strong> — Very secure but <strong>slow</strong>. Usually used in highly sensitive systems, not ideal for public-facing user apps.</li></ul><p>So in most cases, <strong>10 or 12 salt rounds</strong> are ideal — strong enough to protect passwords, yet still fast enough for user experience.</p><h4>2. <strong>Password + Salt Are Hashed Together</strong></h4><ul><li>The plain password is combined with the generated salt.</li><li>Bcrypt runs this combination through a <strong>complex algorithm</strong> multiple times.</li></ul><h4>3. <strong>Returns a Final Hash String</strong></h4><p>The returned hash looks like this:</p><pre>$2b$10$w47jUKFEmqv45Lt7JkhvC.dhTcPdPvuYQFEONwZLHzvVjUl9OGFFe</pre><p>Which contains:</p><ul><li>$2b$ → Bcrypt version</li><li>10 → Salt rounds used</li><li>The salt + hashed password (all encoded together)</li></ul><p><strong>Example Code (With Async/Await)</strong></p><pre>const bcrypt = require(&#39;bcrypt&#39;);<br><br>const plainPassword = &#39;mypassword123&#39;;<br>const saltRounds = 10;<br><br>const hashedPassword = await bcrypt.hash(plainPassword, saltRounds);<br>console.log(&quot;Hashed Password:&quot;, hashedPassword);</pre><h3>✅ Fix: Hash the Password Before Saving</h3><p>Let’s update our code using bcrypt.hash():</p><pre>const bcrypt = require(&#39;bcrypt&#39;);<br><br>app.post(&quot;/signup&quot;, async (req, res) =&gt; {<br>  const { firstName, lastName, email, password, age} =<br>    req.body;<br><br>  try {<br>    // Hash the password before saving<br>    const saltRounds = 10;<br>    const hashedPassword = await bcrypt.hash(password, saltRounds);<br><br>    const user = new User({<br>      firstName,<br>      lastName,<br>      email,<br>      password: hashedPassword, // ✅ save hashed version<br>      age<br>    });<br><br>    await user.save();<br>    res.send(&quot;User created successfully&quot;);<br>  } catch (error) {<br>    res.status(500).send(&quot;Error creating user: &quot; + error.message);<br>  }<br>});</pre><h3>🔐 Compare Passwords During Login Using bcrypt.compare()</h3><p>After a user signs up, their <strong>hashed password</strong> is stored in the database.</p><p>Now when they try to <strong>log in</strong>, they send a plain text password again. But remember — we never stored the original password, only the hashed one. So how do we check if the password is correct?</p><p>We use bcrypt.compare().</p><p>Syntax :</p><pre>bcrypt.compare(plainPassword, hashedPassword, callback);</pre><p>Or with async/await:</p><pre>const isMatch = await bcrypt.compare(plainPassword, hashedPassword);</pre><h4>🔄 How It Works Internally</h4><p>Let’s say:</p><p>Stored (hashed) password in DB:</p><pre>$2b$10$J9sKibJrjclqUwDQfz8HruVX9LM1A1QEVrKExSRB7XZd4ByOEzxeu</pre><p>Entered password during login:</p><pre>password123</pre><p>Here’s what bcrypt.compare() does behind the scenes:</p><ol><li><strong>Takes the plain password (e.g., </strong><strong>password123)</strong></li><li><strong>Extracts the salt and rounds</strong> from the stored hash string in database</li><li><strong>Rehashes the entered password</strong> using that same salt and rounds</li><li><strong>Compares the result</strong> with the stored hash</li></ol><p>5. ✅ If they match → password is correct<br> ❌ If not → invalid password</p><h3>✔️ Login API</h3><pre>app.post(&quot;/login&quot;, async (req, res) =&gt; {<br>  const { email, password } = req.body;<br><br>  try {<br>    // 1. Find the user by email<br>    const user = await User.findOne({ email });<br><br>    if (!user) {<br>      return res.status(400).send(&quot;User not found&quot;);<br>    }<br><br>    // 2. Compare entered password with hashed password in DB<br>    const isMatch = await bcrypt.compare(password, user.password);<br><br>    if (!isMatch) {<br>      return res.status(401).send(&quot;Incorrect password&quot;);<br>    }<br><br>    // 3. Password matched<br>    res.send(&quot;Login successful!&quot;);<br>  } catch (error) {<br>    res.status(500).send(&quot;Server error: &quot; + error.message);<br>  }<br>});</pre><h3>📝 Final Summary</h3><p>Hashing passwords using <strong>bcrypt</strong> is a secure way to protect user data. It converts plain text passwords into unreadable strings using <strong>salt</strong> and multiple <strong>rounds of hashing</strong>, making them extremely hard to crack. With bcrypt.hash() during sign-up and bcrypt.compare() during login, you can safely handle passwords without ever storing them in plain text. This is a must-have practice in any secure authentication system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=610ae3e100a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB CRUD Tutorial]]></title>
            <link>https://medium.com/@dipikagandash411/mongodb-crud-tutorial-059b4e6e0c66?source=rss-550151d94051------2</link>
            <guid isPermaLink="false">https://medium.com/p/059b4e6e0c66</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[crud-operations]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Dipika_gandash]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 12:40:42 GMT</pubDate>
            <atom:updated>2025-06-17T12:40:42.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*qdI5aEWF0psSa0Dya88Ulw.png" /></figure><p>CRUD operations are the <strong>basic building blocks of any application</strong> that stores and manages data. Whether you’re building a blog, e-commerce site, or social media app — you’re always creating, reading, updating, and deleting data.</p><p>CRUD operations in <strong>MongoDB</strong> refer to the four basic functions used to interact with a database. CRUD stands for:</p><ul><li><strong>Create</strong> — Add new data.</li><li><strong>Read</strong> — Retrieve or view existing data.</li><li><strong>Update</strong> — Modify or edit existing data.</li><li><strong>Delete</strong> — Remove data.</li></ul><h3>🟢 <strong>Create Operation in MongoDB</strong></h3><p>The Create operation is used to <strong>insert</strong> new documents (records) into a <strong>collection</strong> (similar to a table in SQL).</p><h4><strong>Syntax for Create Operation:</strong></h4><h4>🔹 insertOne()</h4><p>Inserts <strong>one document</strong> into a collection.</p><pre>db.collectionName.insertOne({ key1: value1, key2: value2 })</pre><h4>🔹 insertMany()</h4><p>Inserts <strong>multiple documents</strong> at once.</p><pre>db.collectionName.insertMany([<br>  { key1: value1, key2: value2 },<br>  { key1: value1, key2: value2 },<br>])</pre><h4><strong>💡 Example: Inserting Users into a “users” Collection</strong></h4><p><strong>📌</strong> Insert One Document:</p><pre>db.users.insertOne({<br>  name: &quot;Dipika&quot;,<br>  age: 22,<br>  city: &quot;Delhi&quot;,<br>  email: &quot;dipika@example.com&quot;<br>})</pre><p>📌 Insert Multiple Documents:</p><pre>db.users.insertMany([<br>  {<br>    name: &quot;Rohit&quot;,<br>    age: 25,<br>    city: &quot;Mumbai&quot;,<br>    email: &quot;rohit@example.com&quot;<br>  },<br>  {<br>    name: &quot;Asha&quot;,<br>    age: 21,<br>    city: &quot;Kolkata&quot;,<br>    email: &quot;asha@example.com&quot;<br>  }<br>])</pre><h4>✅ After Insert: View Your Data in MongoDB Compass</h4><ol><li><strong>Open MongoDB Compass</strong></li></ol><p>Make sure your MongoDB server is running and Compass is connected to the correct database (e.g., localhost:27017).</p><p><strong>2. Go to Your Database</strong></p><p>After inserting data (e.g., using db.users.insertOne() in the MongoDB shell or terminal):</p><ul><li>In Compass, look on the <strong>left sidebar</strong> for your <strong>database name</strong> (e.g., test, ecommerce, etc.)</li><li>Click on it to <strong>expand</strong> and see all the <strong>collections</strong> (e.g., users)</li></ul><p><strong>3. Reload / Refresh</strong></p><p>Click the <strong>“Reload” or “Refresh” icon</strong> (usually at the top or near the collection name). This will fetch the latest data.</p><p><strong>4. View Your Collection</strong></p><ul><li>Click on the users collection (or whichever collection you inserted into).</li><li>You will now <strong>see your document(s)</strong> displayed in a clean table format.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bs0-FPuzwYEnLzxk0SuR9g.png" /></figure><h4>🛑 Things to Know</h4><blockquote>1.MongoDB automatically creates a unique _id field if not provided.</blockquote><blockquote>2. Documents are in <strong>BSON</strong> (Binary JSON) format.</blockquote><blockquote>3. If the collection doesn’t exist, it is automatically <strong>created</strong> on insert.</blockquote><blockquote>4. ErrorInserting with the same _id twice will throw a duplicate key error.</blockquote><h3>🟡 <strong>Read Operation in MongoDB</strong></h3><p>To <strong>fetch</strong> documents (records) from a collection, either all documents or filtered ones based on conditions.</p><h4>Syntax for Read Operation</h4><h4>🔹<strong> </strong><strong>find() – Get multiple documents (returns a cursor)</strong></h4><pre>db.collectionName.find()<br>db.collectionName.find({ filter })</pre><h4>🔹 findOne() – Get only the <strong>first matching document</strong></h4><pre>db.collectionName.findOne({ filter })</pre><h4>💡 Example: Reading from the “users” collection</h4><p><strong>📌 Fetch All Users:</strong></p><pre>db.users.find()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwqeNeOZzDY7PwNHI-n6UQ.png" /></figure><blockquote>📝 This will return <strong>all the documents</strong> in the users collection, coz filter is not applied here.</blockquote><p><strong>📌 Fetch Users with a Condition:</strong></p><pre>db.users.find({ city: &quot;Delhi&quot; })</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*tgfJoOuGRBi_IMtI097nRA.png" /></figure><blockquote>Returns all users whose city is <strong>Delhi</strong>.</blockquote><p><strong>📌 Fetch a Single User (First Match):</strong></p><pre>db.users.findOne({ name: &quot;Dipika&quot; })</pre><blockquote>Returns the <strong>first document</strong> where name is <strong>Dipika</strong>.</blockquote><h3>🟠 <strong>Update Operation in MongoDB</strong></h3><p>To <strong>change</strong> or update the data in one or more existing documents inside a collection.</p><h4>🔸 MongoDB Update Methods</h4><p>1. updateOne() = Updates the <strong>first</strong> matching document</p><p>2. updateMany() = Updates <strong>all</strong> matching documents</p><p>3. replaceOne() = Replaces the entire document</p><h4>🔧 Basic Syntax:</h4><pre>db.collectionName.updateOne(<br>  { filter },<br>  { $set: { field: newValue } }<br>)<br><br>db.collectionName.updateMany(<br>  { filter },<br>  { $set: { field: newValue } }<br>)</pre><blockquote>🔍 What is $set in MongoDB?</blockquote><blockquote>$set is an <strong>update operator</strong> in MongoDB. It is used to <strong>add a new field</strong> or <strong>update the value of an existing field</strong> in a document.</blockquote><blockquote>If the field <strong>already exists</strong>, $set will <strong>change its value</strong>.</blockquote><blockquote>If the field <strong>does not exist</strong>, $set will <strong>create it</strong> with the given value.</blockquote><p>Example :</p><pre>db.users.updateOne(<br>  { name: &quot;Dipika&quot; },<br>  { $set: { age: 23, city: &quot;Bangalore&quot; } }<br>)</pre><h4>🔍 Let’s break it down:</h4><p>1. db.users.updateOne(...)</p><ul><li>This means: Go to the users collection and update <strong>one</strong> document.</li></ul><p>2. { name: &quot;Dipika&quot; } → This is the filter</p><ul><li>It finds the <strong>first document</strong> where name is &quot;Dipika&quot;.</li></ul><p>3. . { $set: { age: 23, city: &quot;Bangalore&quot; } } → This is the update operation</p><p>$set tells MongoDB to:</p><ul><li>Change age to 23 (was 22 before)</li><li>Change city to &quot;Bangalore&quot; (was &quot;Delhi&quot; before)</li></ul><p>Final updated document will be:</p><pre>{<br>  _id: ObjectId(&quot;abc123&quot;),<br>  name: &quot;Dipika&quot;,<br>  age: 23,<br>  city: &quot;Bangalore&quot;<br>}</pre><h4>📌 Update Multiple Documents</h4><pre>db.users.updateMany(<br>  { city: &quot;Delhi&quot; },<br>  { $set: { city: &quot;New Delhi&quot; } }<br>)</pre><blockquote>✅ This updates <strong>all users</strong> from Delhi to <strong>New Delhi</strong>.</blockquote><h4>📌 Increment a Value</h4><pre>db.users.updateOne(<br>  { name: &quot;Asha&quot; },<br>  { $inc: { age: 1 } }<br>)</pre><blockquote>✅ This will <strong>increase Asha’s age by 1</strong>.</blockquote><h4>📌 Replace a Whole Document (Caution!)</h4><pre>db.users.replaceOne(<br>  { name: &quot;Dipika&quot; },<br>  { name: &quot;Dipika&quot;, age: 24, city: &quot;Pune&quot; }<br>)</pre><blockquote>⚠️ Replaces the <strong>entire document</strong>. Any fields not listed here will be <strong>removed</strong>.</blockquote><h3>🔴 <strong>Delete Operation in MongoDB</strong></h3><p>The delete operation is used to <strong>remove</strong> one or more documents from a <strong>collection</strong>.</p><h4>🔸 MongoDB Delete Methods</h4><p>1. deleteOne() -&gt; Deletes the <strong>first</strong> document that matches the filter</p><p>2. deleteMany() -&gt; Deletes <strong>all</strong> documents that match the filter</p><h4>🔧 Syntax:</h4><pre>db.collectionName.deleteOne({ filter })<br>db.collectionName.deleteMany({ filter })</pre><p><strong>💡 Example: Deleting from a </strong><strong>users Collection</strong></p><p>Let’s assume you have the following documents:</p><pre>{<br>  name: &quot;Dipika&quot;,<br>  city: &quot;Delhi&quot;<br>}<br>{<br>  name: &quot;Asha&quot;,<br>  city: &quot;Mumbai&quot;<br>}<br>{<br>  name: &quot;Rohit&quot;,<br>  city: &quot;Delhi&quot;<br>}</pre><p><strong>📌 1. Delete One Document</strong></p><pre>db.users.deleteOne({ city: &quot;Delhi&quot; })</pre><p>🔹 This will:</p><ul><li>Find the <strong>first document</strong> where city is &quot;Delhi&quot;</li><li>And <strong>delete it</strong></li></ul><p>✅ Result: Only <strong>one</strong> user from Delhi will be deleted (e.g., Dipika or Rohit, depending on order)</p><p><strong>📌 2. Delete Multiple Documents</strong></p><pre>db.users.deleteMany({ city: &quot;Delhi&quot; })</pre><p>🔹 This will:</p><ul><li>Delete <strong>all</strong> users whose city is &quot;Delhi&quot;</li></ul><p>✅ Result: Both Dipika and Rohit are removed</p><p><strong>📌 3. Delete a Document by Name</strong></p><pre>db.users.deleteOne({ name: &quot;Asha&quot; })</pre><p>✅ Deletes the user whose name is Asha</p><h3>🔥Connect MongoDB with Node.js and Perform CRUD Operations…</h3><h4><strong>Step 1: Create a New Node.js Project</strong></h4><ol><li>Initialize Node Project:</li></ol><pre>mkdir myproject<br>cd myproject<br>npm init -y</pre><p>2. Install Required Packages:</p><pre>npm install express mongoose dotenv</pre><blockquote><strong><em>Explanation</em></strong><em>:</em></blockquote><blockquote>express: Web framework</blockquote><blockquote>mongoose: To interact with MongoDB</blockquote><blockquote>dotenv: To store secrets like MongoDB connection URI</blockquote><h4><strong>Step 2: Setup Folder Structure (Optional but Recommended)</strong></h4><pre>myproject/<br>│<br>├── .env<br>├── server.js<br>├── models/<br>│   └── User.js<br>├── routes/<br>│   └── userRoutes.js</pre><h4>Step 3: Get MongoDB Atlas Connection String</h4><ol><li>Go to <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas</a></li><li>Create a cluster (free tier is fine)</li><li>Add your IP address under <strong>Network Access</strong></li><li>Create a <strong>Database User</strong> with username/password</li><li>Click <strong>Connect &gt; Connect your application &gt; Node.js</strong></li></ol><p>6. Copy the connection string (looks like this):</p><pre>mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.mongodb.net/myDatabase?retryWrites=true&amp;w=majority</pre><h4><strong>Step 4: Create </strong><strong>.env File</strong></h4><pre>MONGO_URI=mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster0.mongodb.net/myDatabase?retryWrites=true&amp;w=majority<br>PORT=5000</pre><blockquote><em>Replace </em><em>&lt;username&gt;, </em><em>&lt;password&gt;, and </em><em>myDatabase with actual values.</em></blockquote><h4><strong>Step 5: Connect MongoDB in </strong><strong>server.js</strong></h4><pre>// Import required packages<br>const express = require(&quot;express&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>require(&quot;dotenv&quot;).config(); // Load environment variables<br><br>// Create an Express app<br>const app = express();<br><br>// Middleware to handle JSON data in requests<br>app.use(express.json());<br><br>// Connect to MongoDB using Mongoose<br>mongoose.connect(process.env.MONGO_URI)<br>  .then(() =&gt; {<br>    console.log(&quot;✅ Connected to MongoDB&quot;);<br>  })<br>  .catch((error) =&gt; {<br>    console.log(&quot;❌ Error connecting to MongoDB:&quot;, error);<br>  });<br><br>// Sample route to check if API is working<br>app.get(&quot;/&quot;, (req, res) =&gt; {<br>  res.send(&quot;API is working fine!&quot;);<br>});<br><br>// Start the server on port 5000 or the one in .env file<br><br>app.listen(3000, () =&gt; {<br>  console.log(`🚀 Server is running at http://localhost:3000`);<br>});</pre><h4>Step 6: Create Mongoose Model</h4><p>📁 <strong>models/User.js</strong></p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>// Create a schema (structure of user data)<br>const userSchema = new mongoose.Schema({<br>  name: {<br>    type: String,<br>    required: true<br>  },<br>  email: {<br>    type: String,<br>    required: true,<br>    unique: true<br>  },<br>  age: {<br>    type: Number<br>  }<br>});<br><br>// Create model using schema<br>const User = mongoose.model(&quot;User&quot;, userSchema);<br><br>// Export the model<br>module.exports = User;</pre><h4>Step 7: Use This Model in app.js and Create APIs</h4><p>📄 <strong>app.js</strong></p><pre>const express = require(&quot;express&quot;);<br>const mongoose = require(&quot;mongoose&quot;);<br>const dotenv = require(&quot;dotenv&quot;);<br>const User = require(&quot;./models/User&quot;);<br><br>dotenv.config();<br><br>const app = express();<br>app.use(express.json());<br><br>// Connect to MongoDB<br>mongoose.connect(process.env.MONGO_URI)<br>  .then(() =&gt; console.log(&quot;✅ MongoDB Connected&quot;))<br>  .catch(err =&gt; console.log(&quot;❌ MongoDB Connection Error:&quot;, err));<br><br>// Routes<br><br>// 🟢 Create User<br>app.post(&quot;/users&quot;, async (req, res) =&gt; {<br>  try {<br>    const newUser = await User.create(req.body);<br>    res.status(201).json(newUser);<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});<br><br>// 🔵 Get All Users<br>app.get(&quot;/users&quot;, async (req, res) =&gt; {<br>  const users = await User.find();<br>  res.json(users);<br>});<br><br>// 🟡 Get Single User by ID<br>app.get(&quot;/users/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const user = await User.findById(req.params.id);<br>    if (!user) return res.status(404).json({ message: &quot;User not found&quot; });<br>    res.json(user);<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});<br><br>// 🟠 Update User<br>app.put(&quot;/users/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const updatedUser = await User.findByIdAndUpdate(<br>      req.params.id,<br>      req.body,<br>      { new: true }<br>    );<br>    if (!updatedUser) return res.status(404).json({ message: &quot;User not found&quot; });<br>    res.json(updatedUser);<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});<br><br>// 🔴 Delete User<br>app.delete(&quot;/users/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const deletedUser = await User.findByIdAndDelete(req.params.id);<br>    if (!deletedUser) return res.status(404).json({ message: &quot;User not found&quot; });<br>    res.json({ message: &quot;User deleted successfully&quot; });<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});<br><br>// Start server<br>const PORT = 3000;<br>app.listen(PORT, () =&gt; {<br>  console.log(`🚀 Server running on http://localhost:${PORT}`);<br>});</pre><h4>🧠 CRUD API Explanation for /users</h4><h4><strong>1. 🟢 Create a User</strong></h4><p><strong>Route:</strong> POST /users</p><pre>app.post(&quot;/users&quot;, async (req, res) =&gt; {<br>  try {<br>    const newUser = await User.create(req.body);<br>    res.status(201).json(newUser);<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});</pre><p><strong>🔍 What it does:</strong></p><ul><li>Accepts new user data (like name, email, age) in req.body</li><li>Creates a new user in MongoDB using User.create()</li><li>Returns the created user with a 201 status</li></ul><p><strong>🧪 Example JSON Body (use in Postman):</strong></p><pre>{<br>  &quot;name&quot;: &quot;Dipika&quot;,<br>  &quot;email&quot;: &quot;dipika@example.com&quot;,<br>  &quot;age&quot;: 22<br>}</pre><h4><strong>2. 🔵 Get All Users</strong></h4><p><strong>Route:</strong> GET /users</p><pre>app.get(&quot;/users&quot;, async (req, res) =&gt; {<br>  const users = await User.find();<br>  res.json(users);<br>});</pre><p><strong>🔍 What it does:</strong></p><ul><li>Fetches all users from the database using User.find()</li><li>Returns them as a JSON array</li></ul><p><strong>🧪 Example Output:</strong></p><pre>[<br>  {<br>    &quot;_id&quot;: &quot;123abc&quot;,<br>    &quot;name&quot;: &quot;Dipika&quot;,<br>    &quot;email&quot;: &quot;dipika@example.com&quot;,<br>    &quot;age&quot;: 22<br>  },<br>  ...<br>]</pre><h4>3. 🟡 Get a User by ID</h4><p><strong>Route:</strong> GET /users/:id</p><pre>app.get(&quot;/users/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const user = await User.findById(req.params.id);<br>    if (!user) return res.status(404).json({ message: &quot;User not found&quot; });<br>    res.json(user);<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});</pre><p><strong>🔍 What it does:</strong></p><ul><li>Takes user id from the URL (e.g., /users/123abc)</li><li>Uses User.findById() to find and return that user</li><li>If user not found, returns 404 with an error message</li></ul><h4>4. 🟠 Update a User by ID</h4><p><strong>Route:</strong> PUT /users/:id</p><pre>app.put(&quot;/users/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const updatedUser = await User.findByIdAndUpdate(<br>      req.params.id,<br>      req.body,<br>      { new: true }<br>    );<br>    if (!updatedUser) return res.status(404).json({ message: &quot;User not found&quot; });<br>    res.json(updatedUser);<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});</pre><p><strong>🔍 What it does:</strong></p><ul><li>Takes the id and updated data from URL and req.body</li><li>Updates the user using User.findByIdAndUpdate()</li><li>{ new: true } means return the updated user</li><li>Returns the updated user or 404 if not found</li></ul><h4>5. 🔴 Delete a User by ID</h4><p><strong>Route:</strong> DELETE /users/:id</p><pre>app.delete(&quot;/users/:id&quot;, async (req, res) =&gt; {<br>  try {<br>    const deletedUser = await User.findByIdAndDelete(req.params.id);<br>    if (!deletedUser) return res.status(404).json({ message: &quot;User not found&quot; });<br>    res.json({ message: &quot;User deleted successfully&quot; });<br>  } catch (error) {<br>    res.status(400).json({ error: error.message });<br>  }<br>});</pre><p><strong>🔍 What it does:</strong></p><ul><li>Takes the user id from the URL</li><li>Deletes the user using User.findByIdAndDelete()</li><li>Returns success message if user deleted</li></ul><p>Recommedn to watch:</p><p><a href="https://youtu.be/_7UQPve99r4?si=ns1vgRyl_MiQlJ3_">https://youtu.be/_7UQPve99r4?si=ns1vgRyl_MiQlJ3_</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=059b4e6e0c66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>