<?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 Sumit Sakpal on Medium]]></title>
        <description><![CDATA[Stories by Sumit Sakpal on Medium]]></description>
        <link>https://medium.com/@sumitsakpal02?source=rss-45689927527a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K9BdbF7rdqoGyvFeQCgUhg.png</url>
            <title>Stories by Sumit Sakpal on Medium</title>
            <link>https://medium.com/@sumitsakpal02?source=rss-45689927527a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:43:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumitsakpal02/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[ #38 How to Log Out a User Properly in JWT Auth: Token Revocation Explained with Node.js]]></title>
            <link>https://medium.com/@sumitsakpal02/38-how-to-log-out-a-user-properly-in-jwt-auth-token-revocation-explained-with-node-js-424878d99e9d?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/424878d99e9d</guid>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[token-revocation]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 04:41:53 GMT</pubDate>
            <atom:updated>2025-08-04T04:41:53.627Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve built an app using JWT (JSON Web Tokens), you probably love how simple and fast it is. You log in once, get a token, and then send that token with every request to prove who you are. But here’s the problem: <strong>how do you actually log someone out?</strong> Just deleting the token from the client isn’t enough.</p><p>In this article, we’ll explore what <em>token revocation</em> means, why it matters, and how you can implement it the right way using Node.js and a simple blacklist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F8M2bAH7KICmCzqA" /><figcaption>Photo by <a href="https://unsplash.com/@rahuulmiishra?utm_source=medium&amp;utm_medium=referral">Rahul Mishra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>🔗 <em>New to access and refresh tokens? Read this article first:</em><br><a href="https://medium.com/@sumitsakpal02/how-to-secure-your-node-js-api-with-jwt-refresh-tokens-33-ea846431b084"> 👉 How to Secure Your Node.js API with JWT and Refresh Tokens</a></blockquote><h3>🔁 The Problem with JWTs</h3><p>A JWT is just a signed token that contains some user data (like user ID) and is usually stored in the browser’s localStorage or sent with cookies. It works like a digital pass.</p><p>But once the token is created, the server doesn’t know about it anymore. The server can’t “take back” the token or delete it. That means:</p><ul><li>If a user logs out, the token still works unless it expires.</li><li>If someone steals the token, they can use it until it naturally expires.</li></ul><p>This is dangerous. Imagine someone leaves a website open in a public computer or their token gets leaked. There’s no way to <em>invalidate</em> that token on the server unless we have a plan.</p><h3>❓What is Token Revocation?</h3><p><strong>Token revocation</strong> is a way to block or cancel a token before it expires. So even if a token is valid on paper, it won’t work if it’s revoked.</p><p>There are two popular ways to revoke a token:</p><ol><li><strong>Blacklist</strong> — Store tokens you want to block.</li><li><strong>Short-lived tokens + refresh tokens</strong> — Make access tokens expire quickly, and verify refresh tokens carefully.</li></ol><p>In this article, we’ll focus on the <strong>blacklist method</strong>, which is simple and works well for most use cases.</p><h3>🛠 How to Revoke Tokens Using a Blacklist (with Redis)</h3><p>Let’s say your app uses access tokens (short-term) and refresh tokens (longer-term). When a user logs out, you want to block both tokens.</p><p>Here’s a simple way to do it using <strong>Redis</strong> and <strong>Node.js</strong>.</p><h4>🧪 Step 1: Install Redis and Connect It</h4><pre>npm install redis</pre><pre>// redisClient.ts<br>import { createClient } from &quot;redis&quot;;<br><br>const client = createClient();<br>client.on(&quot;error&quot;, (err) =&gt; console.error(&quot;Redis Error&quot;, err));<br>await client.connect();<br>export default client;</pre><h4>🚪 Step 2: Add a Logout Route to Blacklist Tokens</h4><p>When a user clicks logout, their token gets added to the blacklist.</p><pre>// logout.ts<br>import client from &quot;./redisClient&quot;;<br>export const logout = async (req, res) =&gt; {<br>  const token = req.headers.authorization?.split(&quot; &quot;)[1];<br>  if (!token) return res.status(400).json({ message: &quot;Token missing&quot; });<br>  // Set token in Redis with expiry same as token&#39;s expiry<br>  const expiryInSeconds = 60 * 60 * 1; // 1 hour<br>  await client.set(`bl_${token}`, token, { EX: expiryInSeconds });<br>  return res.status(200).json({ message: &quot;Logged out successfully&quot; });<br>};</pre><h4>🧱 Step 3: Block Blacklisted Tokens in Middleware</h4><p>Every time a request comes in, check if the token is blacklisted.</p><pre>// middleware/auth.ts<br>import jwt from &quot;jsonwebtoken&quot;;<br>import client from &quot;./redisClient&quot;;<br><br>export const protect = async (req, res, next) =&gt; {<br>  const token = req.headers.authorization?.split(&quot; &quot;)[1];<br>  if (!token) return res.status(401).json({ message: &quot;Unauthorized&quot; });<br>  const isBlacklisted = await client.get(`bl_${token}`);<br>  if (isBlacklisted) return res.status(401).json({ message: &quot;Token revoked&quot; });<br>  try {<br>    const decoded = jwt.verify(token, process.env.JWT_SECRET);<br>    req.user = decoded;<br>    next();<br>  } catch (err) {<br>    return res.status(401).json({ message: &quot;Invalid token&quot; });<br>  }<br>};</pre><h3>🧩 Bonus Tip: Use Refresh Tokens Wisely</h3><p>If you’re using both access and refresh tokens, don’t forget to revoke refresh tokens too. You can store them in Redis or your database with user session info, and delete them on logout.</p><blockquote>Check this guide for full implementation:<br> <a href="https://medium.com/@sumitsakpal02/how-to-secure-your-node-js-api-with-jwt-refresh-tokens-33-ea846431b084">👉 How to Secure Your Node.js API with JWT and Refresh Tokens</a></blockquote><h3>🧼 Clean-Up Strategy</h3><p>You don’t want your Redis to be full of old tokens. That’s why we use the EX (expire) option when blacklisting. Redis will automatically remove expired keys.</p><p>Also, keep access tokens short-lived (like 15 minutes). If you’re using long access tokens (like 1 day or more), you must implement revocation to protect users properly.</p><h3>🧠 Final Thoughts</h3><p>Just having a token system isn’t enough. You need a plan to <em>revoke</em> tokens, especially when users log out or when security is at risk.</p><p>By blacklisting tokens and using a simple Redis setup, you can build a safer and more reliable authentication system in Node.js.</p><p>It’s a small step that makes a big difference in keeping your app — and your users — protected.</p><blockquote><em>📘 </em>Want to avoid other backend mistakes too?<em><br> </em><a href="https://medium.com/@sumitsakpal02/37-10-common-node-js-mistakes-developers-make-and-how-to-avoid-them-f0c40cfdc25c"><em>👉 10 Common Node.js Mistakes Developers Make (And How to Avoid Them)</em></a></blockquote><h3>📌 Summary</h3><ul><li>JWTs can’t be invalidated by default — you need a revocation system.</li><li>Use Redis to store blacklisted tokens with an expiry time.</li><li>Check every request against the blacklist.</li><li>Always keep your access tokens short-lived.</li><li>Combine with refresh tokens for a smooth and safe login flow.</li></ul><h3>💬 Let’s Connect!</h3><p>Was this article helpful?<br>Follow me for more backend tutorials and security tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=424878d99e9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#37  10 Common Node.js Mistakes Developers Make (And How to Avoid Them)]]></title>
            <link>https://medium.com/@sumitsakpal02/37-10-common-node-js-mistakes-developers-make-and-how-to-avoid-them-f0c40cfdc25c?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0c40cfdc25c</guid>
            <category><![CDATA[backend-bugs]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node-js-mistakes]]></category>
            <category><![CDATA[node-js-best-practices]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 04:41:49 GMT</pubDate>
            <atom:updated>2025-07-28T04:41:49.867Z</atom:updated>
            <content:encoded><![CDATA[<p>Node.js is fast, lightweight, and perfect for building backend apps — but with great power comes common mistakes.</p><p>Whether you’re a beginner or working on real-world projects like admin dashboards or CRM systems, here are the <strong>10 most common Node.js mistakes</strong> developers make — and how to <strong>avoid them like a pro</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m1ASJW1riUenC1YA" /><figcaption>Photo by <a href="https://unsplash.com/@manuelsardo?utm_source=medium&amp;utm_medium=referral">Manuel Sardo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1️⃣ Blocking the Event Loop</h3><h3>❌ The Problem:</h3><p>Using CPU-heavy tasks (like loops or encryption) directly in your app blocks other operations.</p><pre>// BAD: Freezes the app<br>for (let i = 0; i &lt; 1e9; i++) {}</pre><h3>✅ The Fix:</h3><p>Use <strong>worker threads</strong>, <strong>child processes</strong>, or delegate to <strong>background jobs</strong>.</p><h3>2️⃣ Poor Async/Await Error Handling</h3><h3>❌ The Problem:</h3><p>Assuming async/await magically handles all errors.</p><pre>const user = await getUser(); // Crashes on failure</pre><h3>✅ The Fix:</h3><p>Wrap with try/catch.</p><pre>try {<br>  const user = await getUser();<br>} catch (error) {<br>  console.error(&quot;Error fetching user:&quot;, error);<br>}</pre><h3>3️⃣ Forgetting to Close DB Connections</h3><h3>❌ The Problem:</h3><p>Open connections keep hanging and lead to memory leaks.</p><h3>✅ The Fix:</h3><p>Use proper shutdown handlers.</p><pre>mongoose.connection.close();</pre><p>Or gracefully handle with:</p><pre>process.on(&quot;SIGINT&quot;, async () =&gt; {<br>  await mongoose.disconnect();<br>  process.exit(0);<br>});</pre><h3>4️⃣ Hardcoding Secrets</h3><h3>❌ The Problem:</h3><p>Saving credentials or tokens directly in code.</p><pre>const API_KEY = &quot;123456&quot;; // Risky!</pre><h3>✅ The Fix:</h3><p>Use .env files + dotenv.</p><pre>API_KEY=your_secret</pre><pre>require(&#39;dotenv&#39;).config();<br>const key = process.env.API_KEY;</pre><h3>5️⃣ Not Validating Input</h3><h3>❌ The Problem:</h3><p>Letting users send bad or unsafe data.</p><h3>✅ The Fix:</h3><p>Validate with Zod, Joi, or express-validator.</p><pre>const schema = z.object({<br>  email: z.string().email(),<br>  password: z.string().min(6),<br>});</pre><h3>6️⃣ Using console.log in Production</h3><h3>❌ The Problem:</h3><p>Logs everywhere, but no structure.</p><h3>✅ The Fix:</h3><p>Use logging libraries like winston or pino.</p><pre>logger.info(&quot;User created&quot;);<br>logger.error(&quot;Something failed&quot;, error);</pre><h3>7️⃣ No Central Error Handler</h3><h3>❌ The Problem:</h3><p>Errors scattered across multiple files.</p><h3>✅ The Fix:</h3><p>Use centralized middleware in Express:</p><pre>app.use((err, req, res, next) =&gt; {<br>  console.error(err.stack);<br>  res.status(500).json({ message: &quot;Something broke!&quot; });<br>});</pre><h3>8️⃣ Forgetting await</h3><h3>❌ The Problem:</h3><p>Calling async functions without await.</p><pre>sendEmail(); // Not awaited — can fail silently</pre><h3>✅ The Fix:</h3><pre>await sendEmail();</pre><h3>9️⃣ Writing Monolithic Code</h3><h3>❌ The Problem:</h3><p>Everything in one giant file.</p><h3>✅ The Fix:</h3><p>Structure into folders:</p><pre>/controllers<br>/services<br>/routes<br>/utils</pre><p>Keeps code clean and maintainable.</p><h3>🔟 Skipping Middleware</h3><h3>❌ The Problem:</h3><p>Repeating logic in multiple routes.</p><h3>✅ The Fix:</h3><p>Use reusable middleware:</p><pre>const protect = (req, res, next) =&gt; {<br>  // JWT auth logic<br>};<br>app.use(protect);</pre><h3>✅ Final Thoughts</h3><p>Avoiding these mistakes will make your <strong>Node.js apps faster, safer, and easier to maintain</strong>. Clean code isn’t just about syntax — it’s about making your work future-proof.</p><h3>💬 Let’s Connect!</h3><p>Was this article helpful?<br>Follow me for more backend tutorials and security tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0c40cfdc25c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ #36 Why async/await Isn’t Always Asynchronous (And What You Should Know)]]></title>
            <link>https://medium.com/@sumitsakpal02/36-why-async-await-isnt-always-asynchronous-and-what-you-should-know-b538ee62e637?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b538ee62e637</guid>
            <category><![CDATA[promise-vs-async]]></category>
            <category><![CDATA[js-microtask-queue]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[async-function-javascript]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 04:41:48 GMT</pubDate>
            <atom:updated>2025-07-21T04:41:48.512Z</atom:updated>
            <content:encoded><![CDATA[<p>When you hear the word “async”, it’s natural to think of <strong>non-blocking</strong>, <strong>parallel</strong>, or <strong>background</strong> execution. After all, async/await <em>sounds</em> like a tool that always makes your code run asynchronously, right?</p><p><strong>Wrong.</strong></p><p>In this article, we’ll break down:</p><ul><li>What async/await really does (under the hood)</li><li>Why it’s not truly “asynchronous” in some cases</li><li>Real examples where your await doesn’t do what you expect</li><li>Tips to write better async code</li></ul><p>Let’s get into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l5UtdcZdfN96AnMy" /><figcaption>Photo by <a href="https://unsplash.com/@kaip?utm_source=medium&amp;utm_medium=referral">Kai Pilger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>💡 Quick Recap: What Does async/await Do?</h3><p>Before diving deep, here’s a quick refresher:</p><h3>✅ async</h3><p>When you mark a function as async, it automatically returns a <strong>promise</strong>.</p><pre>async function greet() {<br>  return &quot;Hello&quot;;<br>}</pre><pre>greet().then(console.log); // Output: Hello</pre><h3>✅ await</h3><p>The await keyword pauses the execution of the function <strong>until</strong> the promise resolves.</p><pre>async function getData() {<br>  const res = await fetch(&quot;https://api.com/data&quot;);<br>  const data = await res.json();<br>  console.log(data);<br>}</pre><p>So far, so good. But here comes the twist…</p><h3>❗ Misconception: “Async Always Means Asynchronous”</h3><p>Let’s see this simple example:</p><pre>async function sayHi() {<br>  return &quot;Hi&quot;;<br>}</pre><pre>console.log(&quot;Start&quot;);<br>sayHi().then(console.log);<br>console.log(&quot;End&quot;);</pre><h3>Output:</h3><pre>Start<br>End<br>Hi</pre><p>The sayHi function is async but has <strong>no </strong><strong>await</strong> inside. It returns a resolved promise <strong>immediately</strong>, but still, JavaScript pushes the .then() callback to the <strong>microtask queue</strong> — meaning it runs <strong>after the current synchronous code finishes</strong>.</p><p>Even though the function returns instantly, it acts <em>asynchronously</em> because of the <strong>event loop</strong> behavior.</p><p>But now let’s look at a different case:</p><h3>⚠️ Case 1: await with Non-Promise Values</h3><pre>async function demo() {<br>  const result = await 42;<br>  console.log(result);<br>}</pre><pre>demo();</pre><p>You might think await 42 would pause, but it doesn’t!</p><h3>✅ Behind the Scenes:</h3><p>If await gets a <strong>non-promise</strong> (like a number, string, or boolean), JavaScript wraps it in Promise.resolve() — which resolves <strong>immediately</strong>, and the function continues on the <strong>next microtask tick</strong>.</p><p>So technically, it’s still asynchronous — but not <em>in the way you might expect</em>. There’s <strong>no real waiting</strong> going on.</p><h3>⚠️ Case 2: Synchronous Code Inside async Function</h3><pre>async function calculate() {<br>  let sum = 0;<br>  for (let i = 0; i &lt; 1e9; i++) {<br>    sum += i;<br>  }<br>  return sum;<br>}</pre><pre>calculate().then(console.log);</pre><p>Even though calculate is async, the loop blocks the thread.</p><h3>Why?</h3><p>Because the loop is pure <strong>synchronous JavaScript</strong>. Marking the function async <strong>does NOT make its contents non-blocking</strong>. Only await can introduce pauses.</p><h3>🧠 So What’s Really Happening?</h3><p>When you use await, JavaScript <strong>pauses execution</strong> <em>inside the async function</em>, waits for the promise to settle, and then continues.</p><p>BUT — this doesn’t mean it <strong>offloads</strong> the work or <strong>runs it in the background</strong> magically. If there’s no real asynchronous work (like fetch, setTimeout, I/O, etc.), nothing is truly “waited on.”</p><h3>⚡ Real Asynchronous Example</h3><pre>async function fetchUser() {<br>  const res = await fetch(&quot;https://api.com/user&quot;);<br>  const data = await res.json();<br>  console.log(&quot;User:&quot;, data);<br>}</pre><p>Here, await actually makes sense. fetch is asynchronous — it returns a promise that resolves <strong>later</strong>, so your app doesn’t freeze while waiting.</p><p>But if you write:</p><pre>await Math.random();</pre><p>You’re still creating a microtask pause — but no actual waiting is happening. You just delayed the code to the <strong>next tick</strong> of the event loop.</p><h3>🔍 Common Pitfall: Sequential await in Loops</h3><pre>const ids = [1, 2, 3];</pre><pre>async function fetchAll() {<br>  for (const id of ids) {<br>    const data = await fetch(`/api/${id}`);<br>    console.log(data);<br>  }<br>}</pre><p>Here, the loop <strong>waits one-by-one</strong>. That’s slow!</p><h3>✅ Better Way: Run in Parallel</h3><pre>const ids = [1, 2, 3];</pre><pre>async function fetchAll() {<br>  const promises = ids.map(id =&gt; fetch(`/api/${id}`));<br>  const results = await Promise.all(promises);<br>  console.log(results);<br>}</pre><h3>🧽 Cleaning Up: Tips to Use async/await Properly</h3><ol><li>✅ Use await only when the function returns a real <strong>promise</strong></li><li>⚠ Don’t wrap heavy synchronous code in async thinking it will become non-blocking</li><li>⛓ Avoid serial await in loops — use Promise.all where possible</li><li>🧪 For testing, use tools like <strong>Chrome DevTools</strong> to check if your async code is actually deferring work</li><li>💭 Remember: async/await is <strong>syntax sugar</strong>, not a magic wand</li></ol><h3>🏁 Final Thoughts</h3><p>The async/await combo is powerful and makes code readable — but it can be <strong>misleading</strong>. Just because something is inside an async function doesn’t mean it’s asynchronous in behavior.</p><p>Understanding what goes under the hood — promises, microtasks, and the event loop — will help you write <strong>faster</strong>, <strong>non-blocking</strong>, and <strong>cleaner</strong> code.</p><p>When in doubt, <strong>measure</strong> — use console logs, performance tools, and always check: <em>Is this really async? Or just syntactic sugar?</em></p><h3>📌 TL;DR</h3><ul><li>async functions return promises — always</li><li>await pauses inside async functions — but only if the value is a promise</li><li>Non-promise values get wrapped in Promise.resolve() — no real delay</li><li>Synchronous code inside async functions still blocks the thread</li><li>Don’t trust async to make things “parallel” — know what’s actually async</li></ul><h3>💬 Let’s Connect!</h3><p>Was this article helpful?<br>Follow me for more backend tutorials and security tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b538ee62e637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#35 Memory Leaks in JavaScript: The Invisible Performance Killer]]></title>
            <link>https://medium.com/@sumitsakpal02/35-memory-leaks-in-javascript-the-invisible-performance-killer-a19ca64bd304?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19ca64bd304</guid>
            <category><![CDATA[javascript-performance]]></category>
            <category><![CDATA[why-is-my-app-slow]]></category>
            <category><![CDATA[memory-leak-in-browser]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[how-to-fix-memory-leak]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 04:41:45 GMT</pubDate>
            <atom:updated>2025-07-14T04:41:45.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered why your web app becomes slower after running for a while? Maybe you’ve seen the browser hang or crash, even when you didn’t make any heavy changes. One silent culprit might be a <strong>memory leak</strong> — a sneaky bug that hides quietly and eats up your computer’s memory over time.</p><p>Let’s understand what memory leaks are in the simplest way possible, and how you can avoid them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qKHjSHw_JOhdSKyT" /><figcaption>Photo by <a href="https://unsplash.com/@sanatoga?utm_source=medium&amp;utm_medium=referral">Joe Zlomek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>💡 What Is Memory?</h3><p>Every program needs some memory to work. Think of memory like a whiteboard. When your code runs, JavaScript writes stuff on that board — numbers, text, images, and more. When you’re done using something, JavaScript erases it from the board to make space for new things.</p><p>But sometimes, it forgets to erase something. This leftover stuff is called a <strong>memory leak</strong>.</p><h3>🚨 What Is a Memory Leak?</h3><p>A memory leak happens when your code keeps holding on to data it no longer needs. That data stays in memory forever, slowly filling up the system. Over time, your app may slow down, behave oddly, or even crash.</p><p>You can think of it like this:<br> Imagine you’re packing for a trip and keep putting clothes in your bag but forget to remove the ones you no longer need. Eventually, your bag will become too heavy to carry.</p><h3>🛠️ How JavaScript Manages Memory</h3><p>JavaScript is a garbage-collected language, which means it automatically clears out memory that’s no longer being used.</p><p>But JavaScript isn’t magic. It only removes things that it <strong>knows</strong> are no longer needed. If something is <strong>still referenced</strong>, JavaScript thinks it’s important — even if it’s actually junk.</p><p>This is where memory leaks creep in.</p><h3>🧵 Common Causes of Memory Leaks</h3><p>Let’s look at a few everyday examples where memory leaks happen without you realizing it:</p><h3>1. Global Variables</h3><pre>leakedData = [];</pre><p>When you forget to use let, const, or var, the variable becomes global. Global variables live as long as the page is open, even if you don’t need them anymore.</p><p><strong>Fix:</strong> Always declare your variables properly.</p><h3>2. Forgotten Timers</h3><pre>setInterval(() =&gt; {<br>  console.log(&quot;Still running...&quot;);<br>}, 1000);</pre><p>If you forget to clear an interval or timeout using clearInterval or clearTimeout, it keeps running forever.</p><p><strong>Fix:</strong> Always clear intervals when you’re done:</p><pre>const id = setInterval(() =&gt; { ... }, 1000);<br>// later<br>clearInterval(id);</pre><h3>3. DOM Elements That Are Removed Visually But Not in Code</h3><p>Suppose you remove a button from the screen, but still keep a reference in JavaScript:</p><pre>let button = document.getElementById(&quot;myButton&quot;);<br>button.remove(); // visually gone<br>// BUT the `button` variable still holds memory</pre><p><strong>Fix:</strong> Set it to null when you’re done:</p><pre>button = null;</pre><h3>4. Closures That Keep Holding Data</h3><pre>function outer() {<br>  let bigData = new Array(1000000).fill(&quot;data&quot;);<br>  return function inner() {<br>    console.log(&quot;Hello&quot;);<br>  };<br>}</pre><pre>const hello = outer();</pre><p>Even though bigData is never used again, it stays in memory because the inner function closes over it.</p><p><strong>Fix:</strong> Only close over what you need. Or use cleaner patterns that don’t capture unnecessary data.</p><h3>5. Detached DOM Nodes</h3><p>If you move elements around in the DOM but still keep references in your JS, memory won’t be freed.</p><pre>const node = document.getElementById(&quot;some-id&quot;);<br>document.body.removeChild(node);<br>// but node is still in memory if you have a reference</pre><h3>🔍 How to Detect a Memory Leak</h3><p>Thankfully, browser dev tools can help.</p><h3>👉 Chrome DevTools</h3><ol><li>Open Chrome → DevTools (F12) → <strong>Memory</strong> tab</li><li>Take a <strong>Heap Snapshot</strong></li><li>Interact with your app</li><li>Take another snapshot</li><li>Compare what increased — if memory keeps growing after doing the same things, you may have a leak.</li></ol><h3>✅ Tips to Avoid Memory Leaks</h3><ul><li>Don’t overuse global variables</li><li>Clear your timers (setInterval, setTimeout) when done</li><li>Remove event listeners when components unmount (especially in frameworks like React)</li><li>Be careful with closures; avoid capturing unnecessary variables</li><li>Don’t hold references to DOM elements that you’ve removed</li></ul><h3>⚙️ Real-World Example</h3><p>Imagine a chat app where messages keep loading and the chat box never clears memory for old messages. Over time, users experience lag. The issue? Developers forgot to remove old message elements and listener events when chats were cleared.</p><p>This kind of mistake is common, and fixing it can improve performance dramatically.</p><h3>🌱 Final Thoughts</h3><p>Memory leaks are like invisible termites. You don’t see them, but they eat away at your app from the inside. The good news? With simple habits — like proper variable scope, clearing timers, and careful use of closures — you can build apps that stay fast and healthy over time.</p><p>By understanding how JavaScript handles memory and being proactive about cleaning up, you can avoid these sneaky bugs — and write code that scales like a pro.</p><h3>🏁 TL;DR (Too Long, Didn’t Read)</h3><ul><li>JavaScript auto-cleans memory, but only if you stop referencing old data.</li><li>Memory leaks make apps slow, laggy, and crash-prone.</li><li>Common causes: global vars, un-cleared intervals, retained DOM nodes, closures.</li><li>Use Chrome DevTools to detect and fix leaks.</li><li>Clean as you go — your users (and your future self) will thank you.</li></ul><h3>💬 Let’s Connect!</h3><p>Was this article helpful?<br>Follow me for more backend tutorials and security tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19ca64bd304" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Thread Pool in Node.js? Simplified with Real Examples #34]]></title>
            <link>https://medium.com/@sumitsakpal02/what-is-thread-pool-in-node-js-simplified-with-real-examples-34-a1b7c5f7a059?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1b7c5f7a059</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 04:41:39 GMT</pubDate>
            <atom:updated>2025-07-07T04:41:39.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Node.js is known for being fast, non-blocking, and single-threaded. But have you ever wondered how it handles time-consuming tasks like reading large files, encrypting passwords, or compressing data — without slowing down?</p><p>The answer lies in something called the <strong>Thread Pool</strong>.</p><p>Let’s break it down with real-world analogies, practical examples, and performance tips — in the simplest way possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sNDNBkJ-5yUE58dF" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_source=medium&amp;utm_medium=referral">frank mckenna</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🧵 Is Node.js Really Single-Threaded?</h3><p>Yes and no.</p><p>Node.js runs JavaScript on a <strong>single thread</strong>, which means it executes one task at a time in the main event loop. But behind the scenes, Node.js uses a C++ library called <strong>libuv</strong>, which gives it access to a <strong>thread pool</strong> — a group of background workers that can run heavy operations <strong>in parallel</strong>.</p><p>By default, this thread pool has <strong>4 threads</strong>.</p><h3>🏭 Real-Life Analogy: Manager and Workers</h3><p>Imagine you’re the manager of a small workshop (like the event loop). You’re smart and quick — handling small tasks like sending emails or answering calls.</p><p>But when a heavy task comes up — like lifting a 50kg box, drilling metal, or copying 1,000 pages — you delegate it to one of your 4 workers.</p><p>While they do the heavy lifting, <strong>you don’t stop working</strong>. You continue doing the smaller, faster tasks.</p><p>This is how Node.js works. It offloads heavy tasks to the <strong>thread pool</strong>, while the main thread continues running smoothly.</p><h3>🔍 What Uses the Thread Pool in Node.js?</h3><p>Not everything uses the thread pool.</p><p>Here’s a quick table:</p><pre>| Operation           | Uses Thread Pool?           |<br>| ------------------- | ----------------------------|<br>| `fs.readFile()`     | ✅ Yes                      |<br>| `crypto.pbkdf2()`   | ✅ Yes                      |<br>| `dns.lookup()`      | ✅ Yes                      |<br>| `zlib.gzip()`       | ✅ Yes                      |<br>| `setTimeout()`      | ❌ No                       |<br>| HTTP/HTTPS Requests | ❌ No (handled by OS async) |</pre><p>So when you run something like fs.readFile(), it’s handled by a background thread — keeping your main thread free.</p><h3>📊 Let’s See It in Action</h3><h4>Example: File Reading</h4><pre>const fs = require(&#39;fs&#39;);<br><br>console.log(&#39;Start reading file&#39;);<br><br>fs.readFile(&#39;bigfile.txt&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;File read complete&#39;);<br>});<br><br>console.log(&#39;Other work continues...&#39;);</pre><h4>Output:</h4><pre>Start reading file<br>Other work continues...<br>File read complete</pre><p>Even though reading the file takes time, Node.js doesn’t wait — it hands off the task to a worker in the thread pool.</p><h3>⚙️ What is UV_THREADPOOL_SIZE and When to Use It?</h3><p>Node.js uses 4 threads by default in its thread pool. But what if your app needs to handle many blocking operations <strong>at the same time</strong>?</p><p>You can increase the thread pool size using the UV_THREADPOOL_SIZE environment variable.</p><h3>🛠️ How to Use</h3><p>In your terminal or command prompt:</p><pre>UV_THREADPOOL_SIZE=8 node app.js</pre><blockquote><em>This tells Node.js to use 8 threads in the background instead of the default 4.</em></blockquote><p>📌 Note:</p><ul><li>Must be set <strong>before</strong> starting your Node.js process</li><li>Cannot be changed at runtime</li></ul><h3>🔧 Real Scenario: Running 10 Heavy Crypto Tasks</h3><pre>const crypto = require(&#39;crypto&#39;);<br><br>for (let i = 0; i &lt; 10; i++) {<br>  crypto.pbkdf2(&#39;password&#39;, &#39;salt&#39;, 100000, 64, &#39;sha512&#39;, () =&gt; {<br>    console.log(`Task ${i + 1} done`);<br>  });<br>}</pre><p>Now run it with:</p><pre>UV_THREADPOOL_SIZE=10 node cryptoTasks.js</pre><p>✅ All 10 tasks can run in parallel, increasing throughput.<br> 🚫 With the default 4 threads, only 4 tasks run at a time — others have to wait.</p><h3>🧪 Blocking vs Non-Blocking in Crypto</h3><p>Let’s compare sync vs async crypto operations:</p><h3>❌ Blocking (Sync)</h3><pre>const crypto = require(&#39;crypto&#39;);<br><br>crypto.pbkdf2Sync(&#39;password&#39;, &#39;salt&#39;, 100000, 64, &#39;sha512&#39;);<br>console.log(&#39;Done&#39;);</pre><blockquote><em>The main thread waits for this to finish — </em><strong><em>bad</em></strong><em> for scalability.</em></blockquote><h3>✅ Non-Blocking (Async)</h3><pre>const crypto = require(&#39;crypto&#39;);<br>crypto.pbkdf2(&#39;password&#39;, &#39;salt&#39;, 100000, 64, &#39;sha512&#39;, () =&gt; {<br>  console.log(&#39;Done&#39;);<br>});<br>console.log(&#39;Main thread is free&#39;);</pre><blockquote><em>The task goes to the thread pool — main thread continues. 🚀</em></blockquote><h3>🎯 Why Does the Thread Pool Matter?</h3><p>Understanding the thread pool helps you:</p><ul><li>Avoid blocking the event loop</li><li>Write faster, scalable code</li><li>Optimize performance for file, crypto, DNS, or compression-heavy apps</li><li>Tune performance by adjusting UV_THREADPOOL_SIZE</li></ul><h3>✅ Summary</h3><ul><li>Node.js uses a <strong>thread pool</strong> behind the scenes (via libuv) for heavy I/O tasks.</li><li>By default, there are <strong>4 threads</strong> — you can increase it using UV_THREADPOOL_SIZE.</li><li>Tasks like file reading, encryption, and DNS lookups use the thread pool.</li><li>Use <strong>async versions</strong> of functions to avoid blocking the event loop.</li><li>Knowing how the thread pool works helps you build better Node.js applications.</li></ul><h3>📚 Want to Learn More?</h3><ul><li><a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick">Node.js Event Loop and libuv (Official Docs)</a></li><li><a href="https://docs.libuv.org/en/v1.x/threadpool.html">libuv Thread Pool</a></li><li><a href="https://nodejs.dev/en/learn/nodejs-performance-tuning">Node.js Performance Tips</a></li></ul><h3>💬 Let’s Connect!</h3><p>Was this article helpful?<br>Follow me for more backend tutorials and security tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1b7c5f7a059" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Secure Your Node.js API with JWT + Refresh Tokens #33]]></title>
            <link>https://medium.com/@sumitsakpal02/how-to-secure-your-node-js-api-with-jwt-refresh-tokens-33-ea846431b084?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea846431b084</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[secure]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 04:41:53 GMT</pubDate>
            <atom:updated>2025-06-30T04:41:53.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 Intro:</h3><p>If you’re building a Node.js API, using <strong>JWT (JSON Web Tokens)</strong> is one of the most popular ways to handle authentication.</p><p>But here’s the problem:</p><blockquote><em>What happens when a user’s access token expires after 15 minutes?<br> Do they have to log in again?</em></blockquote><p>That’s where <strong>refresh tokens</strong> come in.</p><p>In this article, we’ll break down:</p><ul><li>What JWT and refresh tokens are</li><li>Why you need both</li><li>How to implement them in a secure way using Node.js + Express</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nek4dXIqvoH2b5Rl" /><figcaption>Photo by <a href="https://unsplash.com/@domenicoloia?utm_source=medium&amp;utm_medium=referral">Domenico Loia</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🔑 What is JWT?</h3><p>JWT stands for <strong>JSON Web Token</strong> — a compact way to represent claims between two parties. It’s commonly used for authentication.</p><p>When a user logs in:</p><ol><li>They get a <strong>JWT access token</strong></li><li>This token is stored (usually in the browser or mobile app)</li><li>Every protected request sends the token in the Authorization header</li></ol><pre>Authorization: Bearer &lt;access_token&gt;</pre><p>But access tokens are usually <strong>short-lived</strong> (like 15 minutes) for security.</p><h3>💡 Why Use Refresh Tokens?</h3><p>Let’s say:</p><ul><li>Your access token expires every 15 minutes</li><li>You don’t want users to log in every time it expires</li></ul><p>💡 Use a <strong>refresh token</strong>, which:</p><ul><li>Has a longer expiry (7 days or more)</li><li>Is used to <strong>get a new access token</strong> without logging in again</li><li>Is stored securely (e.g., in <strong>HttpOnly cookies</strong>)</li></ul><h3>⚙️ How It Works (Flow):</h3><pre>[Login] ➡️ [Access Token + Refresh Token]</pre><pre>[API Request] ➡️ [Access Token] ✅</pre><pre>[Access Token Expired] ➡️ [Send Refresh Token]<br>➡️ [Backend verifies + issues new Access Token]</pre><h3>🛠️ Implementation in Node.js + Express</h3><h4>📦 Step 1: Install dependencies</h4><pre>npm install express jsonwebtoken dotenv</pre><h4>🧪 Step 2: Create Tokens</h4><pre>const jwt = require(&#39;jsonwebtoken&#39;);</pre><pre>const generateAccessToken = (user) =&gt; {<br>  return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: &#39;15m&#39; });<br>};</pre><pre>const generateRefreshToken = (user) =&gt; {<br>  return jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, { expiresIn: &#39;7d&#39; });<br>};</pre><h4>🔐 Step 3: Login Route</h4><pre>app.post(&#39;/login&#39;, (req, res) =&gt; {<br>  const user = { id: 1, email: req.body.email };</pre><pre>  const accessToken = generateAccessToken(user);<br>  const refreshToken = generateRefreshToken(user);</pre><pre>  // Store refreshToken in memory, DB, or Redis<br>  refreshTokens.push(refreshToken);</pre><pre>  res.json({ accessToken, refreshToken });<br>});</pre><h4>🔁 Step 4: Token Refresh Route</h4><pre>app.post(&#39;/token&#39;, (req, res) =&gt; {<br>  const refreshToken = req.body.token;</pre><pre>  if (!refreshToken || !refreshTokens.includes(refreshToken))<br>    return res.sendStatus(403);</pre><pre>  jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET, (err, user) =&gt; {<br>    if (err) return res.sendStatus(403);</pre><pre>    const accessToken = generateAccessToken({ id: user.id });<br>    res.json({ accessToken });<br>  });<br>});</pre><h4>🔒 Step 5: Protecting Routes with Access Token</h4><pre>const authenticate = (req, res, next) =&gt; {<br>  const authHeader = req.headers[&#39;authorization&#39;];<br>  const token = authHeader?.split(&#39; &#39;)[1];</pre><pre>  if (!token) return res.sendStatus(401);</pre><pre>  jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) =&gt; {<br>    if (err) return res.sendStatus(403);<br>    req.user = user;<br>    next();<br>  });<br>};</pre><pre>app.get(&#39;/protected&#39;, authenticate, (req, res) =&gt; {<br>  res.send(&#39;Protected content accessed!&#39;);<br>});</pre><h3>🔐 Security Tips</h3><p>✅ Use <strong>HttpOnly Cookies</strong> for refresh tokens (not localStorage)<br> ✅ Store refresh tokens in DB/Redis to manage blacklist/logout<br> ✅ Rotate refresh tokens on every refresh<br> ✅ Use <strong>HTTPS</strong> in production<br> ✅ Expire refresh tokens on logout or suspicion of compromise</p><h3>🧠 When to Use This Approach?</h3><ul><li>SPAs (React/Vue) with login systems</li><li>Mobile apps using token-based auth</li><li>APIs that need scalable, stateless sessions</li><li>Security-critical apps (banking, admin dashboards)</li></ul><h3>✅ Final Thoughts</h3><p>JWTs make authentication stateless and scalable, but <strong>adding refresh tokens</strong> makes your app <strong>secure AND user-friendly</strong>.</p><p>You’ve now learned:</p><ul><li>The difference between access and refresh tokens</li><li>How to implement both in Node.js</li><li>Best practices for security and scalability</li></ul><h3>💬 Let’s Connect!</h3><p>Was this article helpful?<br> Follow me for more backend tutorials and security tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea846431b084" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is CORS and Why Does It Block My API Requests? #32]]></title>
            <link>https://medium.com/@sumitsakpal02/what-is-cors-and-why-does-it-block-my-api-requests-32-beb69b0ed8b6?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/beb69b0ed8b6</guid>
            <category><![CDATA[cross-origin-resource]]></category>
            <category><![CDATA[web-developer]]></category>
            <category><![CDATA[node-js-developer]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[cors]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 04:41:36 GMT</pubDate>
            <atom:updated>2025-06-23T04:41:36.074Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re working with frontend-backend apps — especially in Node.js — you’ve probably seen this scary message:</p><blockquote><strong><em>“Access to fetch at ‘</em></strong><a href="http://localhost:4000/api"><strong><em>http://localhost:4000/api</em></strong></a><strong><em>&#39; from origin ‘</em></strong><a href="http://localhost:3000/"><strong><em>http://localhost:3000</em></strong></a><strong><em>&#39; has been blocked by CORS policy…”</em></strong></blockquote><p>😨 What does it mean? And how do you fix it?</p><p>In this article, let’s understand CORS (Cross-Origin Resource Sharing) in simple terms, why it exists, and how to handle it properly in your backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kzLH_atZdt6B_LYq" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🌐 What is CORS?</h3><p><strong>CORS</strong> stands for <strong>Cross-Origin Resource Sharing</strong>.<br> It’s a <strong>security feature</strong> implemented by browsers to <strong>protect users from malicious requests</strong>.</p><p>By default, a web browser blocks frontend code (like React) from making requests to a backend API <strong>hosted on a different domain, port, or protocol.</strong></p><p>That’s called a <strong>cross-origin request</strong>, and it gets blocked unless the server <strong>explicitly allows it.</strong></p><h3>🔥 Why Does CORS Matter?</h3><p>Let’s say:</p><ul><li>Your frontend runs on: <a href="http://localhost:3000/">http://localhost:3000</a></li><li>Your backend API runs on: <a href="http://localhost:4000/">http://localhost:4000</a></li></ul><p>Now your React app wants to call your Node.js API.</p><p>➡️ The browser sees this as <strong>two different origins</strong> — even though they’re on localhost!</p><p>If your backend doesn’t send the correct headers like:</p><pre>Access-Control-Allow-Origin: http://localhost:3000</pre><p>…then the browser <strong>blocks the request.</strong></p><h3>🛠️ How Does CORS Work?</h3><p>When a frontend sends a cross-origin request:</p><ol><li>The <strong>browser sends a “preflight” request</strong> using the OPTIONS method</li><li>The <strong>backend must respond</strong> with the allowed Origin, Methods, and Headers</li><li>If the headers match, the browser allows the actual request</li></ol><h4>Example Headers:</h4><pre>Access-Control-Allow-Origin: http://localhost:3000<br>Access-Control-Allow-Methods: GET, POST, PUT, DELETE<br>Access-Control-Allow-Headers: Content-Type, Authorization</pre><h3>⚙️ How to Enable CORS in Node.js (Express)</h3><p>The simplest way is using the cors middleware:</p><h4>📦 Step 1: Install it</h4><pre>npm install cors</pre><h4>📄 Step 2: Use it in your app</h4><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();</pre><pre>app.use(cors({<br>  origin: &#39;http://localhost:3000&#39;, // frontend domain<br>  methods: [&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;DELETE&#39;],<br>  credentials: true,<br>}));</pre><pre>app.get(&#39;/api&#39;, (req, res) =&gt; {<br>  res.json({ message: &#39;CORS is working!&#39; });<br>});</pre><pre>app.listen(4000, () =&gt; console.log(&#39;Server running on port 4000&#39;));</pre><h3>📌 When to Use CORS</h3><ul><li>Your frontend and backend are on <strong>different domains, subdomains, or ports</strong></li><li>You’re using <strong>React/Vue + Express API</strong> setup in local dev or production</li><li>You’re building <strong>mobile apps or browser extensions</strong> calling your API</li><li>You want to allow <strong>limited external access</strong> to your API (e.g. public API)</li></ul><h3>⚠️ Common CORS Mistakes</h3><p>🚫 Using &#39;*&#39; (wildcard origin) with credentials: true — this <strong>won’t work</strong><br> 🚫 Forgetting to allow <strong>custom headers</strong> (like Authorization)<br> 🚫 Not handling OPTIONS method properly for <strong>preflight requests</strong></p><h3>✅ Final Thoughts</h3><p>CORS isn’t a bug — it’s a <strong>security layer</strong> that protects users.<br> As a backend developer, you control who gets access to your APIs. With the right setup, your app stays both functional and secure.</p><p>So the next time you see a CORS error — smile 😊 — it means your browser is doing its job, and <strong>you’re now smart enough to fix it.</strong></p><h3>💬 Let’s Connect!</h3><p>Did this help you understand CORS better?<br> Drop a comment or follow me for more backend dev tips</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beb69b0ed8b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is JWE? Understanding JSON Web Encryption Made Simple #31]]></title>
            <link>https://medium.com/@sumitsakpal02/what-is-jwe-understanding-json-web-encryption-made-simple-31-14847f89ebac?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/14847f89ebac</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Fri, 20 Jun 2025 04:41:34 GMT</pubDate>
            <atom:updated>2025-06-20T04:41:34.026Z</atom:updated>
            <content:encoded><![CDATA[<p>If you already know about JWT (JSON Web Token), you might wonder:<br> <strong>What is JWE and how is it different from JWT?</strong></p><p>This article explains JWE — JSON Web Encryption — in simple words, so you understand why and when to use it, how it works, and why it matters for security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cMqqy-LGIGW42VXK" /><figcaption>Photo by <a href="https://unsplash.com/@bugsster?utm_source=medium&amp;utm_medium=referral">Taras Shypka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is JWE?</h3><p><strong>JWE stands for JSON Web Encryption.</strong><br> It is a standard format for <strong>encrypting data inside a token</strong>, so the content is <strong>hidden and secure</strong> from anyone who doesn’t have the decryption key.</p><h3>Why do we need JWE?</h3><p>Regular JWT tokens (also called <strong>JWS — JSON Web Signature</strong>) are <strong>signed but not encrypted</strong>. This means:</p><ul><li>The payload inside JWT is <strong>Base64URL encoded</strong> — anyone can decode and read it.</li><li>Signing ensures the data is not tampered with, but <strong>does not hide the data</strong>.</li></ul><p>Sometimes, you need to keep the data <strong>private and confidential</strong>, for example:</p><ul><li>Sending sensitive user information (like passwords, personal details)</li><li>Passing secret keys or tokens that must not be exposed</li><li>Securing communication between services where data privacy is critical</li></ul><p>This is where <strong>JWE</strong> comes in.</p><h3>How does JWE work?</h3><p>JWE encrypts the token data so only someone with the right <strong>decryption key</strong> can read it.</p><h3>A JWE token consists of five parts:</h3><pre>JWE = Protected Header . Encrypted Key . Initialization Vector . Ciphertext . Authentication Tag</pre><ul><li><strong>Protected Header</strong>: Metadata about the encryption algorithm</li><li><strong>Encrypted Key</strong>: The key encrypted using the recipient’s public key or a shared secret</li><li><strong>Initialization Vector (IV)</strong>: Random data used in encryption for security</li><li><strong>Ciphertext</strong>: The actual encrypted payload (the sensitive data)</li><li><strong>Authentication Tag</strong>: Used to verify the token’s integrity and authenticity</li></ul><h3>When to Use JWE?</h3><p>Use JWE if you need to:</p><ul><li>Keep the data <strong>confidential</strong> (hidden from everyone but the intended recipient)</li><li>Transmit <strong>sensitive information</strong> securely between services</li><li>Add an extra layer of protection beyond simple signatures</li></ul><p>If you just want to verify identity or integrity without hiding data, regular JWT (JWS) is enough.</p><h3>Final thoughts</h3><p>JWE is an important standard when you want <strong>true confidentiality</strong> in your tokens. While JWT (JWS) tokens are widely used for authentication because they are simple and fast, JWE protects your data from prying eyes by encrypting it.</p><p>If you are building applications that handle sensitive data, consider using JWE for maximum security.</p><h3>💬 Let’s Connect!</h3><p>Did you find this article helpful? Drop your thoughts or questions below 👇 and follow for more JavaScript deep dives!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14847f89ebac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JWT: Why You Can See the Payload but Can’t Tamper with It #30]]></title>
            <link>https://medium.com/@sumitsakpal02/understanding-jwt-why-you-can-see-the-payload-but-cant-tamper-with-it-30-474881085461?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/474881085461</guid>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node-js-development]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 04:42:36 GMT</pubDate>
            <atom:updated>2025-06-16T04:42:36.601Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Have you ever pasted a JWT token into </strong><a href="https://jwt.io/"><strong>jwt.io</strong></a><strong> and seen the payload data clearly?</strong> Many developers get confused and worry, “If anyone can see my JWT payload, isn’t my data exposed? And if the payload is visible and changeable, then what’s the point of the secret key?”</p><p>Don’t worry! This article will explain everything in simple words, so even a beginner or a 5-year-old can understand how JWT works, why it’s safe, and what the secret key really does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r8TaB-SkeAU9oI19" /><figcaption>Photo by <a href="https://unsplash.com/@szolkin?utm_source=medium&amp;utm_medium=referral">Sergey Zolkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is JWT?</h3><p>JWT stands for <strong>JSON Web Token</strong>. It’s a way to securely transmit information between a client and a server as a JSON object. It looks like this:</p><pre>xxxxx.yyyyy.zzzzz</pre><p>These three parts are:</p><ul><li><strong>Header</strong> — information about the token type and signing algorithm</li><li><strong>Payload</strong> — the actual data (claims) like user ID, roles, or expiration time</li><li><strong>Signature</strong> — a cryptographic signature to verify the token wasn’t tampered with</li></ul><h3>Why can I see the Payload on jwt.io without a secret key?</h3><p>The header and payload parts of JWT are <strong>only encoded, not encrypted</strong>. They use <strong>Base64URL encoding</strong>, which means anyone can decode and read them. That’s why you can paste your JWT into <a href="https://jwt.io/">jwt.io</a> and see the payload clearly.</p><p><strong>Important:</strong> This does NOT mean your data is secret or safe from attackers — it’s just not hidden.</p><h3>What does the Secret Key do?</h3><p>The secret key is used to <strong>sign</strong> the token, creating the signature part. The signature guarantees that:</p><ul><li>The token was created by a trusted party (someone who has the secret key)</li><li>The token data (payload) has not been changed since it was signed</li></ul><p>If someone tries to change the payload or header, they can’t generate a new valid signature without the secret key. This makes the token invalid.</p><h3>What happens if someone changes the payload?</h3><p>If an attacker modifies the payload and sends the token:</p><ul><li>The server will try to verify the token signature using the secret key.</li><li>Because the payload changed, the signature will no longer match.</li><li>The server will reject the token as invalid.</li></ul><p><strong>So, even though anyone can see and decode the payload, they cannot tamper with it without the secret key.</strong></p><h3>How does verification work?</h3><p>When a server receives a JWT, it:</p><ol><li>Decodes the header and payload (anyone can do this).</li><li>Uses the secret key and the decoded data to generate a new signature.</li><li>Compares the new signature with the signature in the token.</li><li>If they match, the token is valid; if not, it’s rejected.</li></ol><h3>What encoding does JWT use by default?</h3><p>JWT uses <strong>Base64URL encoding</strong> for the header and payload. It’s like Base64 but URL-safe — meaning it uses characters that are safe to put in URLs without extra encoding.</p><h3>Are there other types?</h3><p>JWT can be:</p><ul><li><strong>Signed (JWS)</strong> — the usual kind with a signature for verification.</li><li><strong>Encrypted (JWE)</strong> — less common, encrypts the payload so it’s hidden and secure.</li></ul><p>Most JWTs you see are signed (JWS), which means the payload is readable but tamper-proof.</p><h3>Final thoughts</h3><p>Seeing your payload on jwt.io might worry you, but remember: JWT is designed this way — <strong>to be transparent yet secure</strong>. You can decode the token anytime, but without the secret key, no one can tamper with it.</p><p>If you want truly private data in the token, use encryption (JWE), but for most cases, signed JWTs are enough to keep things safe.</p><p>Hope this clears your doubts! Feel free to share or ask if you want me to help with more JWT topics.</p><h3>💬 Let’s Connect!</h3><p>Did you find this article helpful? Drop your thoughts or questions below 👇 and follow for more JavaScript deep dives!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474881085461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is a Blob Database? Explained with Real-World Examples #29]]></title>
            <link>https://medium.com/@sumitsakpal02/what-is-a-blob-database-explained-with-real-world-examples-29-831ab212bc65?source=rss-45689927527a------2</link>
            <guid isPermaLink="false">https://medium.com/p/831ab212bc65</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[databse]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[blob-storage]]></category>
            <dc:creator><![CDATA[Sumit Sakpal]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 04:41:36 GMT</pubDate>
            <atom:updated>2025-06-13T04:41:36.101Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital world, we work with all kinds of data — text, images, videos, documents, and more. But not all data fits nicely into rows and columns like an Excel sheet. Some of it is just… big and messy. That’s where <strong>BLOB databases</strong> come in.</p><p>In this article, we’ll explain what BLOB databases are, how they work, and where you might use them in real life. Don’t worry — we’ll keep things simple and skip the fancy jargon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lTFSo452bi4dztDo" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=medium&amp;utm_medium=referral">Jan Antonin Kolar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🎈 What is a BLOB?</h3><p>Imagine you have a toy box. Inside the toy box, you put anything you want — cars, dolls, puzzles, even a coloring book. You don’t worry about size or shape. You just throw it in.</p><p>A <strong>BLOB</strong>, short for <strong>Binary Large Object</strong>, is kind of like that toy box in the world of databases. It’s used to store <strong>huge chunks of data</strong> that can’t be easily divided into small pieces. This data is usually stored in <strong>binary format</strong>, which means it can be anything:</p><ul><li>A photo</li><li>A video</li><li>An audio file</li><li>A PDF document</li><li>A backup file</li></ul><h3>🧠 Why Use a BLOB Database?</h3><p>Let’s say you’re building a simple document storage system. Users can upload files like PDFs or images. You need a place to keep those files. You could use:</p><ul><li>A file system (like folders on your laptop)</li><li>A <strong>BLOB database</strong>, which stores the actual content in a database</li></ul><p>The second option is better if you want everything — data and metadata — to stay together in one system, with better access control and backup support.</p><h3>🧩 When to Use a BLOB Database</h3><p>You might choose a BLOB-based database when you:</p><ul><li>Want to store <strong>large files</strong> alongside related data</li><li>Need to <strong>index or track</strong> uploaded documents or media files</li><li>Don’t want to manage separate file servers</li><li>Need <strong>transactional integrity</strong> (the file must be stored only if the database update is successful)</li></ul><h3>📦 Real-World Examples of BLOB Usage</h3><h3>1. Cloud Storage Services</h3><p>Services like Google Drive, Dropbox, and iCloud use systems similar to BLOB databases. When you upload a file, it’s saved in binary format and linked to your account.</p><h3>2. Social Media Platforms</h3><p>When you post a photo on Instagram or Facebook, the image is stored as a BLOB in their database or object storage.</p><h3>3. Banking Systems</h3><p>Banks often store scanned documents like signed forms or IDs as BLOBs attached to your account records.</p><h3>4. Medical Records</h3><p>Hospitals store X-ray images, scans, and reports in databases as BLOBs connected to a patient profile.</p><h3>⚙️ How Does a BLOB Database Work?</h3><p>Let’s break it down in simple steps:</p><ol><li>You upload a file (like an image).</li><li>The system converts the file into <strong>binary data</strong>.</li><li>That binary data is saved in a database field marked as a <strong>BLOB type</strong>.</li><li>A link or ID connects that BLOB to other useful information like who uploaded it, when, and why.</li></ol><p>It’s like writing your name on the toy box so you know who it belongs to.</p><h3>🧪 Simple Example Using MongoDB</h3><p>Here’s a basic example of how you can use MongoDB to store a BLOB (like an image or PDF):</p><pre>const mongoose = require(&#39;mongoose&#39;);</pre><pre>const FileSchema = new mongoose.Schema({<br>  name: String,<br>  data: Buffer,<br>  contentType: String,<br>  uploadedBy: String,<br>  createdAt: { type: Date, default: Date.now }<br>});</pre><pre>const File = mongoose.model(&#39;File&#39;, FileSchema);</pre><p>This schema lets you store the raw data (BLOB) and some extra info about it.</p><p>To save a file:</p><pre>const fs = require(&#39;fs&#39;);<br>const newFile = new File({<br>  name: &#39;profile-pic.jpg&#39;,<br>  data: fs.readFileSync(&#39;./uploads/profile-pic.jpg&#39;),<br>  contentType: &#39;image/jpeg&#39;,<br>  uploadedBy: &#39;john_doe&#39;<br>});</pre><pre>await newFile.save();</pre><p>To get and use the file later:</p><pre>const file = await File.findById(fileId);<br>fs.writeFileSync(&#39;./downloaded.jpg&#39;, file.data);</pre><h3>🚀 Benefits of Using BLOBs</h3><ul><li>All-in-one storage: Your files and related data live together</li><li>Access control and security: Built-in with your database</li><li>Easier backup and recovery</li><li>Simpler API and fewer moving parts</li></ul><h3>⚠️ Things to Watch Out For</h3><ul><li>BLOBs can make your database big and heavy</li><li>Reading and writing large BLOBs may slow down performance</li><li>Sometimes it’s better to store files in a dedicated file storage and keep only the link in the DB</li></ul><p>Pro tip: For extremely large-scale apps, consider <strong>hybrid storage</strong> — use services like AWS S3 or Azure Blob Storage and store the URL in your database.</p><h3>🧵 Final Words</h3><p>BLOB databases are perfect when you need to store large, unstructured files in your app. They keep your data and files in one neat place and make it easy to search, secure, and scale your app.</p><p>Next time you think of storing a PDF, image, or video, ask yourself: “Do I want this in my app’s brain?” If yes, a BLOB database might just be your best friend.</p><p>Need help implementing BLOBs in your next project or want more examples? Let me know and I’ll write a follow-up guide!</p><h3>💬 Let’s Connect!</h3><p>Did you find this article helpful? Drop your thoughts or questions below 👇 and follow for more JavaScript deep dives!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831ab212bc65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>