<?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 Arka Sheikh on Medium]]></title>
        <description><![CDATA[Stories by Arka Sheikh on Medium]]></description>
        <link>https://medium.com/@skarka90?source=rss-4fdc48f59362------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pmhYhT4Rb74cUH2A</url>
            <title>Stories by Arka Sheikh on Medium</title>
            <link>https://medium.com/@skarka90?source=rss-4fdc48f59362------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:09:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skarka90/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[The Secret Detective Story Behind Every Website You Visit]]></title>
            <link>https://medium.com/@skarka90/the-secret-detective-story-behind-every-website-you-visit-fb70d2af0ae3?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb70d2af0ae3</guid>
            <category><![CDATA[dns-servers]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 04:21:01 GMT</pubDate>
            <atom:updated>2026-04-05T04:21:01.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSWbZe0ubicdO5SufDqoSg.png" /></figure><p>You type a website.<br>You hit Enter.<br>Three milliseconds later you’re rage-scrolling memes, reading blogs, or arguing with strangers about tabs vs spaces.</p><p>Looks simple.</p><p>But behind the scenes?</p><p>The internet just launched a full-blown FBI investigation involving:</p><ul><li>your browser</li><li>your laptop</li><li>your router</li><li>your ISP</li><li>several servers across the planet</li><li>a giant invisible phonebook</li><li>and at least one machine that basically says:</li></ul><blockquote><em>“I don’t know the answer, but I know a guy who knows a guy.”</em></blockquote><p>That system is called DNS.</p><p>And honestly? DNS is the most overworked, underappreciated employee on the entire internet.</p><h3>DNS, Explained Like You’re Ordering Food</h3><p>Humans like names.</p><p>Machines like numbers.</p><p>You want:</p><p>google.com</p><p>Your computer wants:</p><p>142.250.183.14</p><p>Because computers are weird little goblins that only trust numbers.</p><p>DNS (Domain Name System) is the translator between those two worlds.</p><p>Think of it like this:</p><ul><li>You say: “Take me to Netflix.”</li><li>DNS says: “Cool, that’s actually 52.89.something.something.”</li><li>Your browser goes there.</li><li>You lose 4 hours of your life watching one episode “just before sleeping.”</li></ul><h3>A Domain Name Is Basically an Address With Layers</h3><p>Take this:</p><p>routerx.heyarka.cloud</p><p>Your brain reads it left to right.</p><p>DNS reads it like a suspicious detective reading a license plate backwards.</p><p>It starts from the end:</p><h3>.cloud</h3><p>The big category.<br>Like saying:</p><blockquote><em>“This place exists somewhere in Cloud-Town.”</em></blockquote><h3>heyarka</h3><p>The actual property owner.</p><blockquote><em>“Ah yes, heyarka owns a house in Cloud-Town.”</em></blockquote><h3>routerx</h3><p>The exact room inside the house.</p><blockquote><em>“You want the weird little server room in the basement labeled routerx.”</em></blockquote><p>So DNS doesn’t see one giant word.<br>It sees a trail of clues.</p><h3>Step 1: Your Browser Tries Being Smart First</h3><p>Before your computer asks the internet anything, it first checks if it already knows the answer.</p><p>Because asking the internet is expensive.</p><p>Your browser basically does this:</p><blockquote><em>“Wait… have we been to this site before?”</em></blockquote><p>If yes:</p><p>Boom. Instant answer.</p><p>If no:</p><p>Your operating system checks.</p><p>If the OS doesn’t know:</p><p>Your router checks.</p><p>If the router doesn’t know:</p><p>Now everybody starts panicking.</p><h3>DNS Cache = That Sticky Note You Refuse to Throw Away</h3><p>Imagine your friend changes their phone number.</p><p>But you wrote the old number on a sticky note three weeks ago.</p><p>And instead of updating your contacts like a functional adult, you keep calling the old number because:</p><blockquote><em>“Well… it’s still on the sticky note.”</em></blockquote><p>That’s exactly how DNS caching works.</p><p>Your computer stores old answers so it doesn’t have to ask again.</p><p>But every answer comes with a timer called TTL:</p><p><strong>Time To Live</strong></p><p>Example:</p><ul><li>DNS says: “The website is at this IP.”</li><li>TTL says: “You’re allowed to trust this answer for 1 hour.”</li></ul><p>After that, the answer expires.</p><p>Like milk.<br>But for networking.</p><h3>Enter the Heavyweight: Recursive DNS</h3><p>When your computer gives up, it sends the problem to a bigger, smarter machine called a recursive resolver.</p><p>This is the internet’s professional investigator.</p><p>Its whole job is:</p><blockquote><em>“Don’t come back until you find where this website lives.”</em></blockquote><p>Usually this is run by your ISP.</p><p>But many people use:</p><ul><li>Google DNS → 8.8.8.8</li><li>Cloudflare DNS → 1.1.1.1</li></ul><p>Because ISP DNS is often slower than that one teammate who says:</p><blockquote><em>“Sorry, just saw this message.</em></blockquote><p>…three business days later.</p><h3>Why Doesn’t 8.8.8.8 Explode?</h3><p>Billions of people use Google DNS.</p><p>So why doesn’t one poor server in a basement catch fire instantly?</p><p>Because 8.8.8.8 is not one server.</p><p>Plot twist.</p><p>It’s hundreds of servers around the world pretending to be one server.</p><p>That trick is called Anycast.</p><p>You ask for 8.8.8.8.</p><p>The internet quietly routes you to the nearest Google server.</p><ul><li>In India? Probably somewhere nearby.</li><li>In London? Different server.</li><li>In Tokyo? Entirely different server.</li></ul><p>Same IP.<br>Different physical machine.</p><p>Like the world’s most organized catfish.</p><h3>The DNS Journey: “I Know a Guy Who Knows a Guy”</h3><p>Now the recursive resolver starts digging.</p><p>It doesn’t magically know where routerx.heyarka.cloud is.</p><p>It asks around.</p><p>Exactly like trying to find a shady mechanic through friends of friends.</p><h3>Step 1: Ask the Root Server</h3><p>DNS goes to the top boss of the internet and says:</p><blockquote><em>“Hey, where’s routerx.heyarka.cloud?”</em></blockquote><p>Root server says:</p><blockquote><em>“No clue. But I know who handles </em><em>.cloud.”</em></blockquote><p>And gives it the address.</p><h3>Step 2: Ask the .cloud Server</h3><p>Now DNS goes there.</p><blockquote><em>“Okay cool. Where’s </em><em>heyarka.cloud?”</em></blockquote><p>.cloud server says:</p><blockquote><em>“I don’t know the final answer either. But I know who owns </em><em>heyarka.cloud.”</em></blockquote><p>And hands over another address.</p><h3>Step 3: Ask the Authoritative Server</h3><p>Finally DNS reaches the one server that actually knows.</p><p>The server checks its records and says:</p><blockquote><em>“routerx.heyarka.cloud = 192.0.2.45”</em></blockquote><p>Mission accomplished.</p><p>The answer travels all the way back.<br>Your browser finally gets the IP.<br>And the website loads.</p><p>All of that usually happens in under 50 milliseconds.</p><p>Which is frankly ridiculous.</p><h3>The Secret Menu: Different Types of DNS Records</h3><p>DNS doesn’t just store website addresses.</p><p>It stores different kinds of instructions.</p><p>Here are the only ones you actually need to remember:</p><h3>A Record</h3><p>Maps a website to an IPv4 address.</p><blockquote><em>“This site lives here.”</em></blockquote><p>Example:</p><p>routerx.heyarka.cloud → 192.0.2.45</p><h3>AAAA Record</h3><p>Same thing, but for IPv6.</p><p>Basically the internet saying:</p><blockquote><em>“We ran out of old addresses, so here’s an address with 47 extra characters.”</em></blockquote><h3>CNAME Record</h3><p>Alias.</p><p>Like saying:</p><blockquote><em>“portal.heyarka.cloud is actually the same thing as routerx.heyarka.cloud”</em></blockquote><p>One record.<br>Multiple names.<br>Tiny networking sorcery.</p><h3>MX Record</h3><p>Tells email where to go.</p><p>Without MX records, emails just wander the internet like a lost uncle in a shopping mall.</p><h3>TXT Record</h3><p>The weird junk drawer of DNS.</p><p>It stores random text.</p><p>But these days it’s mostly used for security stuff like:</p><ul><li>SPF</li><li>DKIM</li><li>DMAR</li></ul><p>Which are basically email’s way of saying:</p><blockquote><em>“Prove you’re not a scammer.”</em></blockquote><h3>The Dark Side: DNS Can Be Hacked</h3><p>Here’s the cursed part.</p><p>The original DNS system was built in the 1980s.</p><p>Back when internet engineers still believed humans could be trusted.</p><p>So DNS originally had almost no security.</p><p>If a hacker could trick DNS into giving you the wrong address, they could send you to a fake website.</p><p>You think you’re opening your bank.</p><p>Actually you’re opening:</p><p>totally-not-a-bank.in</p><p>Same logo.<br>Same design.<br>Same login page.</p><p>You type your password.</p><p>Congratulations. You’ve just donated your account to a stranger.</p><p>This attack is called DNS spoofing or cache poisoning.</p><p>Which sounds like a rejected Spider-Man villain.</p><h3>The Facebook Outage That Accidentally Deleted Facebook</h3><p>Back in 2021, Facebook, Instagram, and WhatsApp disappeared for hours.</p><p>The internet lost its collective mind.</p><p>People suddenly had to text actual humans.</p><p>Terrifying.</p><p>Everyone thought DNS broke.</p><p>But what actually happened was even dumber.</p><p>Facebook accidentally removed the directions to its own servers.</p><p>Its DNS system basically went:</p><blockquote><em>“I can’t find Facebook.”</em></blockquote><p>Which is a pretty awkward thing for Facebook to say about itself.</p><p>Even Facebook employees couldn’t fix it remotely because the network required to access the fix… was also broken.</p><p>That’s like locking your keys inside the car, except the car is an entire company.</p><h3>How Modern DNS Protects Itself</h3><p>Luckily, modern DNS got some armor upgrades.</p><h3>DNS over HTTPS (DoH)</h3><p>Old DNS was like sending your browsing history on a postcard.</p><p>Anyone could read it.</p><p>Your ISP.<br>Hackers.<br>That sketchy coffee shop Wi‑Fi.</p><p>DoH wraps DNS inside encrypted HTTPS traffic.</p><p>So now instead of a postcard, your DNS request travels inside a locked metal briefcase.</p><h3>DNSSEC</h3><p>DNSSEC makes sure the answer itself is real.</p><p>It adds a cryptographic signature.</p><p>So if somebody tries to replace the real IP with a fake one, the signature fails and DNS says:</p><blockquote><em>“Nice try, villain.”</em></blockquote><h3>Final Thought</h3><p>The next time a website loads instantly, remember:</p><p>Your browser didn’t just “go to a site.”</p><p>It launched a tiny global detective story.</p><p>Your device checked its memory.<br>Your router checked its memory.<br>A recursive resolver called around.<br>The root server said “ask that guy.”<br>That guy said “ask this other guy.”</p><p>And eventually one exhausted server somewhere finally yelled:</p><blockquote><em>“OH MY GOD YES, THE WEBSITE IS AT 192.0.2.45.”</em></blockquote><p>And all of that happened before you could even blink.</p><p>The internet is held together by caffeine, ancient protocols, and an unbelievable number of machines saying:</p><blockquote><em>“I know a guy.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb70d2af0ae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React’s useEffectEvent: Finally, a Hook That Gets Us ]]></title>
            <link>https://medium.com/@skarka90/reacts-useeffectevent-finally-a-hook-that-gets-us-0090af857853?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/0090af857853</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 09:02:14 GMT</pubDate>
            <atom:updated>2025-10-18T09:02:14.682Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture this: You’re coding late at night, your coffee’s gone cold, and you’re staring at a useEffect that&#39;s re-running more times than your favorite playlist on repeat. You know <em>exactly</em> what you want—just react to one thing, but read the latest value of something else. Simple, right?</p><p>Wrong.</p><p>Welcome to the dependency array dilemma, where React has been giving us the silent treatment for years. But fear not, fellow developers! React’s experimental useEffectEvent hook is here to save us from this beautiful mess.</p><h3>The Problem: When useEffect Becomes useEffectTooMuch 😅</h3><p>Let’s talk about the elephant in the room — or should I say, the dependency array in the Effect?</p><p>We’ve all been there. You write a useEffect that needs to do something when one value changes, but it also needs to <em>read</em> another value. React, being the responsible parent it is, immediately scolds you:</p><pre>React Hook useEffect has a missing dependency: &#39;theme&#39;. <br>Either include it or remove the dependency array.</pre><p>Thanks, React. Very helpful. <em>Very</em>.</p><p>So you have two choices:</p><ol><li>Add theme to the dependency array (Effect re-runs every time theme changes—even when you don&#39;t want it to)</li><li>Ignore the warning (and feel guilty for the rest of your life)</li></ol><p>Neither option sparks joy.</p><h3>What Was Life Like Before useEffectEvent? (Spoiler: Complicated)</h3><p>Let’s look at a real example. Imagine you’re building a music player app (because who doesn’t love a good Spotify clone?).</p><pre>function MusicPlayer({ songId, volume }) {<br>  useEffect(() =&gt; {<br>    const player = createAudioPlayer();<br>    player.load(songId);<br>    player.onReady(() =&gt; {<br>      player.setVolume(volume);<br>      player.play();<br>    });<br>    <br>    return () =&gt; player.cleanup();<br>  }, [songId]); // ⚠️ Missing dependency: &#39;volume&#39;<br>  <br>  // ...<br>}</pre><p>Here’s the drama: You want to load a new song only when songId changes. Makes sense—you don&#39;t want to restart the entire song every time the user adjusts the volume slider. That would be... annoying, to say the least.</p><p>But you <em>do</em> want the player to use the current volume when it starts playing. You want the <em>latest</em> volume value, but you don’t want volume changes to reload the entire song.</p><h3>The Old Workarounds (A.K.A. The “It’s Complicated” Era)</h3><p>Before useEffectEvent, we had a few... <em>creative</em> solutions:</p><p><strong>Option 1: The Ref Dance</strong> 💃</p><pre>const volumeRef = useRef(volume);</pre><pre>useEffect(() =&gt; {<br>  volumeRef.current = volume;<br>}, [volume]);</pre><pre>useEffect(() =&gt; {<br>  const player = createAudioPlayer();<br>  player.load(songId);<br>  player.onReady(() =&gt; {<br>    player.setVolume(volumeRef.current);<br>    player.play();<br>  });<br>  return () =&gt; player.cleanup();<br>}, [songId]);</pre><p>It works, but… why do we need two useEffects just to read a prop? This feels like using a sledgehammer to crack a nut.</p><p><strong>Option 2: Just Add It to Dependencies</strong> 🤷</p><pre>useEffect(() =&gt; {<br>  const player = createAudioPlayer();<br>  player.load(songId);<br>  player.onReady(() =&gt; {<br>    player.setVolume(volume);<br>    player.play();<br>  });<br>  return () =&gt; player.cleanup();<br>}, [songId, volume]); // Now it reloads the song on every volume tweak 😢</pre><p>Cool, no warnings! Except now your users have to restart the song from the beginning every time they adjust the volume. NOT COOL.</p><p><strong>Option 3: The ESLint Ignore Comment</strong> 🙈</p><pre>useEffect(() =&gt; {<br>  const player = createAudioPlayer();<br>  player.load(songId);<br>  player.onReady(() =&gt; {<br>    player.setVolume(volume);<br>    player.play();<br>  });<br>  return () =&gt; player.cleanup();<br>  // eslint-disable-next-line react-hooks/exhaustive-deps<br>}, [songId]);</pre><p>The “I know what I’m doing” .</p><h3>Enter useEffectEvent: The Hero We Deserve 🦸</h3><p>useEffectEvent is like that friend who finally understands you don&#39;t want to restart your entire vacation every time you change your shirt. It lets you extract non-reactive logic from your Effects into something called an <em>Effect Event</em>.</p><p>Think of it as a function that:</p><ul><li>Always reads the latest props and state (no stale closures!)</li><li>Doesn’t trigger the Effect to re-run when those values change</li><li>Makes the ESLint warning gods happy</li></ul><p>Here’s the syntax:</p><pre>const onSomething = useEffectEvent(callback);</pre><p>That’s it. That’s the tweet.</p><h3>How to Use It: The Music Player Redemption Arc 🎬</h3><p>Okay, deep breath. Let’s fix our music player with useEffectEvent. I promise it&#39;s simpler than it looks:</p><pre>import { useEffectEvent, useEffect } from &#39;react&#39;;<br><br>function MusicPlayer({ songId, volume }) {<br>  // Step 1: Wrap the stuff that needs latest values in useEffectEvent<br>  const onSongReady = useEffectEvent(() =&gt; {<br>    player.setVolume(volume);  // Always gets the latest volume!<br>    player.play();<br>  });<br><br>// Step 2: Use it inside your normal useEffect<br>  useEffect(() =&gt; {<br>    const player = createAudioPlayer();<br>    player.load(songId);<br>    player.onReady(() =&gt; {<br>      onSongReady(); // Just call it like a regular function<br>    });<br>    <br>    return () =&gt; player.cleanup();<br>  }, [songId]); // Look ma, no volume in the array!<br><br>// ...<br>}</pre><p><strong>Breaking it down in plain English:</strong></p><p>Think of useEffectEvent as a special box where you can put code that needs to read fresh values, but shouldn&#39;t trigger re-runs.</p><ol><li><strong>You create the box</strong> with useEffectEvent(() =&gt; { ... })</li><li><strong>You put your logic inside</strong> (the stuff that reads volume)</li><li><strong>You call it from your Effect</strong> whenever you need it</li><li><strong>React handles the magic</strong> — it always runs with the latest values, but doesn’t make your Effect re-run</li></ol><p>That’s literally it. You’re just moving some code into a special function and calling it. No complex patterns, no weird tricks.</p><p><strong>The secret sauce:</strong> When volume changes, React doesn&#39;t re-run your Effect (no song reload). But when you call onSongReady(), it automatically sees the new volume. It&#39;s like React is taking a fresh snapshot every time you call it!</p><h3>Real-Life Scenario: The Analytics Tracking Saga 📊</h3><p>Let’s get even more real. Say you’re building an e-commerce site and need to track page visits along with the number of items in the shopping cart:</p><h3>The Problem (Before useEffectEvent)</h3><pre>function Page({ url }) {<br>  const { items } = useContext(ShoppingCartContext);<br>  const numberOfItems = items.length;<br><br>useEffect(() =&gt; {<br>    logVisit(url, numberOfItems);<br>  }, [url, numberOfItems]); // 😱 Logs every time cart changes!<br>  <br>  // ...<br>}</pre><p><strong>The Issue:</strong> Every time a user adds or removes an item from their cart, you’re logging a new page visit. Your analytics dashboard thinks your users are having seizures, clicking the same page 47 times in a minute.</p><p>That’s not just wrong — it’s expensive if you’re paying per API call!</p><h3>The Solution (With useEffectEvent)</h3><pre>import { useEffect, useContext, useEffectEvent } from &#39;react&#39;;<br><br>function Page({ url }) {<br>  const { items } = useContext(ShoppingCartContext);<br>  const numberOfItems = items.length;<br><br>// Extract the logging logic into an Effect Event<br>  const onNavigate = useEffectEvent((visitedUrl) =&gt; {<br>    logVisit(visitedUrl, numberOfItems);<br>  });<br><br>useEffect(() =&gt; {<br>    onNavigate(url);<br>  }, [url]); // Only track actual navigation!<br>  <br>  // ...<br>}</pre><p><strong>The Magic:</strong></p><ul><li>Effect only runs when url changes (actual page navigation)</li><li>onNavigate always reads the <em>latest</em> numberOfItems</li><li>You log page visits with the current cart count</li><li>No false positives, no wasted API calls, no confused analytics</li></ul><p>You can even pass url as an argument to onNavigate to keep it reactive while accessing non-reactive values inside. React&#39;s got your back!</p><h3>Where Else Can You Use This Bad Boy? 🚀</h3><p>useEffectEvent isn&#39;t a one-trick pony. Here are some scenarios where it absolutely shines:</p><h3>1. WebSocket Connections with User Preferences</h3><p>Setting up WebSocket listeners that need current user settings without reconnecting:</p><pre>function StockTicker({ stockSymbol, notificationSound, alertThreshold }) {<br>  const onPriceUpdate = useEffectEvent((price) =&gt; {<br>    if (price &gt; alertThreshold) {<br>      playSound(notificationSound);<br>      showAlert(`${stockSymbol} hit $${price}!`);<br>    }<br>  });<br><br>useEffect(() =&gt; {<br>    const ws = new WebSocket(&#39;wss://stocks.api.com&#39;);<br>    ws.onmessage = (event) =&gt; onPriceUpdate(event.data.price);<br>    ws.send(JSON.stringify({ subscribe: stockSymbol }));<br>    <br>    return () =&gt; ws.close();<br>  }, [stockSymbol]); // Sound/threshold changes don&#39;t cause reconnection!<br>}</pre><h3>2. Geolocation Tracking with Dynamic Precision</h3><p>When tracking location but UI preferences shouldn’t restart the watcher:</p><pre>function MapTracker({ showTrail, accuracyLevel }) {<br>  const onLocationUpdate = useEffectEvent((position) =&gt; {<br>    updateMap(position, showTrail, accuracyLevel);<br>  });<br><br>useEffect(() =&gt; {<br>    const watchId = navigator.geolocation.watchPosition(onLocationUpdate);<br>    return () =&gt; navigator.geolocation.clearWatch(watchId);<br>  }, []); // UI preferences don&#39;t restart GPS tracking!<br>}</pre><h3>3. Auto-Save with User Settings</h3><p>When you want to auto-save based on content changes but use latest save preferences:</p><pre>function DocumentEditor({ documentId, content, autoSaveDelay, compressionLevel }) {<br>  const onSave = useEffectEvent(() =&gt; {<br>    saveDocument(documentId, content, { <br>      compression: compressionLevel <br>    });<br>  });<br><br>useEffect(() =&gt; {<br>    const timer = setTimeout(onSave, autoSaveDelay);<br>    return () =&gt; clearTimeout(timer);<br>  }, [content]); // Only debounce on content change, use latest settings!<br>}</pre><h3>4. Game Loop with Dynamic Difficulty</h3><p>When animation frames need to read the latest game state without restarting the loop:</p><pre>function GameCanvas({ isPaused, difficulty, playerSpeed }) {<br>  const onFrame = useEffectEvent((timestamp) =&gt; {<br>    if (!isPaused) {<br>      updateGameState(timestamp, difficulty, playerSpeed);<br>      renderFrame();<br>    }<br>  });<br><br>useEffect(() =&gt; {<br>    let rafId = requestAnimationFrame(onFrame);<br>    return () =&gt; cancelAnimationFrame(rafId);<br>  }, []); // Difficulty/speed changes don&#39;t restart the game loop!<br>}</pre><h3>5. Form Validation with Changing Rules</h3><p>Validating on specific field changes while using the latest validation rules:</p><pre>function SignupForm({ email, validationRules, showDetailedErrors }) {<br>  const onValidate = useEffectEvent(() =&gt; {<br>    const errors = validateEmail(email, validationRules);<br>    if (showDetailedErrors) {<br>      displayDetailedErrors(errors);<br>    } else {<br>      displaySimpleErrors(errors);<br>    }<br>  });<br><br>useEffect(() =&gt; {<br>    const timer = setTimeout(onValidate, 300);<br>    return () =&gt; clearTimeout(timer);<br>  }, [email]); // Only validate on email change, use latest rules/display prefs!<br>}</pre><h3>Important Caveats (Because No Hook is Perfect) ⚠️</h3><p>Before you rush off to refactor your entire codebase, here are some ground rules:</p><ol><li><strong>Effect Events are for Effects only</strong>: Don’t call them in event handlers or pass them to other components. They’re like Effect-exclusive VIP passes.</li><li><strong>Not a “get out of dependencies free” card</strong>: Don’t use useEffectEvent just to avoid thinking about dependencies. If something <em>should</em> trigger your Effect, keep it in the dependency array. This hook is for when you genuinely want to read latest values without re-running.</li><li><strong>Still experimental</strong>: This is the big one — useEffectEvent isn&#39;t in a stable React release yet. It&#39;s experimental, which means the API might change, or your manager might give you the side-eye for using it in production. Choose wisely!</li></ol><h3>The Bottom Line 🎯</h3><p>useEffectEvent solves a real problem we&#39;ve all faced: wanting to react to some changes but not others, while always reading the latest values. It&#39;s elegant, it&#39;s purposeful, and it makes our code clearer.</p><p>Before: A maze of refs, extra Effects, or dependency arrays that make Effects run way too often.</p><p>After: Clean, intentional code that does exactly what we mean.</p><p>Is it a game-changer? For certain use cases, absolutely. Will it replace useEffect? No—they&#39;re teammates, not competitors.</p><p>Once this experimental hook graduates to a stable release, it’ll be a fantastic addition to our React toolkit. Until then, we can admire it from afar (or live on the edge and try it in side projects).</p><p>Now go forth and Effect Event responsibly! 🚀</p><p><em>Have you been wrestling with useEffect dependency arrays? What’s your most creative workaround? Drop a comment — I’d love to hear your war stories!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0090af857853" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporal API: JavaScript’s New Date Superhero — Say Goodbye to Date Nightmares!]]></title>
            <link>https://medium.com/@skarka90/temporal-api-javascripts-new-date-superhero-say-goodbye-to-date-nightmares-a994902844dd?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/a994902844dd</guid>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 06:47:46 GMT</pubDate>
            <atom:updated>2025-06-14T06:47:46.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Temporal API: JavaScript’s New Date Superhero — Say Goodbye to Date Nightmares!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mlwryn7wFy9Jj8bBUEVzOw.png" /></figure><p>Hey, fellow devs! Ever spent hours debugging a date-related bug only to realize JavaScript’s <em>Date</em> object is gaslighting you? Yeah, we’ve all been there, screaming into the void while trying to figure out why adding a day lands you in the wrong month. Fear not, because the Temporal API is here to save your sanity, and it’s about to make <em>Date</em> look like that ex you never want to see again. Let’s dive into why Temporal is the hero we’ve been waiting for.</p><h3>🕒 What is Temporal API and Why It Was Introduced</h3><p>Picture this: you’re trying to schedule a meeting across timezones, but Date is like, “Here’s UTC or local time, pick one, loser.” JavaScript’s Date object is a historical mistake, a relic from the days when Netscape thought copying Java’s java.util.Date was a vibe. Spoiler: it wasn’t. It’s like texting with a rotary phone—slow, clunky, and you’re one wrong move from starting over.</p><p>The Date object’s sins are many:</p><ul><li><strong>Confusing Methods</strong>: Too many ways to do the same thing, half of which lead to bugs.</li><li><strong>Timezone Hell</strong>: Only UTC or local time, no arbitrary timezones or “no timezone” concept.</li><li><strong>Gregorian-Only Club</strong>: No support for other calendars like Hebrew or Chinese.</li><li><strong>Mutating Madness</strong>: Setters that change your date behind your back.</li><li><strong>Parsing Nightmares</strong>: Inconsistent string parsing that varies by browser.</li></ul><p>Enter the Temporal API, JavaScript’s shiny new solution, designed to replace Date entirely. It’s a namespace (think Math, not a constructor) packed with over 200 methods across classes like Temporal.PlainDate, Temporal.ZonedDateTime, and Temporal.Now. Why was it born? To give us:</p><ul><li><strong>Proper Timezone Handling</strong>: Work with any IANA timezone, no hacks needed.</li><li><strong>Immutability</strong>: No more accidental date mutations—finally, a healthy relationship!</li><li><strong>Accuracy</strong>: Precise calculations, even across daylight saving time (DST) changes.</li><li><strong>Calendar Support</strong>: Handles non-Gregorian calendars for global apps.</li><li><strong>Consistent Parsing</strong>: Uses RFC 9557 (ISO 8601-based) for reliable string formats.</li></ul><p>Temporal is like swapping your rotary phone for a smartphone—suddenly, everything just works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*q0-BmTl6kCDEdgBp6XLBVA.gif" /></figure><h3>🧱 The Pre-Temporal Struggle</h3><p>Before Temporal, we were stuck in the dark ages, wrestling with <em>Date</em> or begging third-party libraries for mercy. Moment.js was the OG, but it’s a bundle-size hog and mutable like <em>Date</em>. Luxon brought immutability and better timezone support, while date-fns offered a functional approach. But let’s be real: adding dependencies just to make dates bearable felt like duct-taping a sinking ship.</p><p>Working with <em>Date</em> was pure pain, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*MvBUfGGI1xItp_YG0xnivg.gif" /></figure><p>Need to add a day across a DST change? Good luck. Want to parse a date string consistently? Hope your browser’s feeling generous. These libraries were our lifeboats, but they came with learning curves and bloat. Temporal? It’s built into JavaScript, standardized, and ready to make you forget those dark days.</p><h3>🔧 Temporal API Methods vs Date Object (Side-by-Side Battle)</h3><p>Let’s pit Temporal against Date in a cage match for common operations. Spoiler: Date gets knocked out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f0da3b8e179ade89b8ba8033073d227/href">https://medium.com/media/3f0da3b8e179ade89b8ba8033073d227/href</a></iframe><h3>Examples in Action</h3><p><strong>Get Current Date/Time:</strong></p><pre>// Date: Local timezone, vague output<br>const dateNow = new Date();<br>console.log(dateNow); // 2025-06-14T11:06:00.000Z (or local equivalent)<br><br>// Temporal: Precise, timezone-aware<br>const temporalNow = Temporal.Now.zonedDateTimeISO();<br>console.log(temporalNow.toString()); // 2025-06-14T11:06:00+05:30[Asia/Kolkata]</pre><p><strong>Create Specific Date:</strong></p><pre>// Date: 0-based months, ugh<br>const date = new Date(2025, 5, 14); // June, not May!<br>console.log(date); // 2025-06-14T00:00:00.000Z<br><br>// Temporal: Intuitive and clear<br>const temporalDate = Temporal.PlainDate.from({ year: 2025, month: 6, day: 14 });<br>console.log(temporalDate.toString()); // 2025-06-14</pre><p><strong>Add One Day:</strong></p><pre>// Date: Mutates, risky<br>date.setDate(date.getDate() + 1);<br>console.log(date); // 2025-06-15T00:00:00.000Z (original date changed!)<br><br>// Temporal: Immutable, safe<br>const newTemporalDate = temporalDate.add({ days: 1 });<br>console.log(newTemporalDate.toString()); // 2025-06-15</pre><p><strong>Timezone Conversion:</strong></p><pre>// Date: Clunky and string-based<br>const nyDate = date.toLocaleString(&#39;en-US&#39;, { timeZone: &#39;America/New_York&#39; });<br>console.log(nyDate); // 6/14/2025, 12:00:00 AM (string, not a date object)<br><br>// Temporal: Clean and precise<br>const nyTemporal = temporalNow.withTimeZone(&#39;America/New_York&#39;);<br>console.log(nyTemporal.toString()); // 2025-06-14T01:36:00-04:00[America/New_York]</pre><p><strong>Why Not Both?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*4mHzIU_LW5s0eND8J94KOA.gif" /></figure><p>Okay, maybe not. <em>Date</em> is like that friend who means well but always messes up. Temporal is your new BFF.</p><h3>🔨 Mini App Tutorial: Timezone Converter</h3><p>Let’s build a simple timezone converter to see Temporal in action. This mini-app takes an event’s date and time in one timezone and converts it to another. Follow along, and you’ll be amazed at how easy this is compared to Date.</p><h4>Step 1: Set Up Inputs</h4><p>Imagine you’re scheduling a meeting on June 14, 2025, at 10:00 AM in New York, and you need the time in London.</p><pre>const year = 2025;<br>const month = 6;<br>const day = 14;<br>const hour = 10;<br>const minute = 0;<br>const second = 0;<br>const originalTimeZone = &#39;America/New_York&#39;;<br>const targetTimeZone = &#39;Europe/London&#39;;</pre><h4>Step 2: Create a ZonedDateTime</h4><p>Use Temporal.ZonedDateTime.from to create a date-time object with the original timezone.</p><pre>const event = Temporal.ZonedDateTime.from({<br>  timeZone: originalTimeZone,<br>  year,<br>  month,<br>  day,<br>  hour,<br>  minute,<br>  second<br>});</pre><h4>Step 3: Convert to Target Timezone</h4><p>Use withTimeZone to convert to the target timezone.</p><pre>const eventInTarget = event.withTimeZone(targetTimeZone);</pre><p><strong>Step 4: Display Results</strong></p><p>Show both times in a human-readable format.</p><pre>console.log(`Event in ${originalTimeZone}: ${event.toString()}`);<br>console.log(`Event in ${targetTimeZone}: ${eventInTarget.toString()}`);<br>// Output:<br>// Event in America/New_York: 2025-06-14T10:00:00-04:00[America/New_York]<br>// Event in Europe/London: 2025-06-14T15:00:00+01:00[Europe/London]</pre><h4>Step 5: Aha Moment!</h4><p>Notice how Temporal handles DST automatically? No manual offset calculations or praying your browser parses correctly. This is why Temporal is a lifesaver.</p><p>Try it yourself! Copy this code into your console (with the polyfill if needed) and play around with different timezones. You’ll never go back to Date.</p><h4>😂 More Memes for Your Soul</h4><p>When you realize Temporal.ZonedDateTime handles timezones like a pro:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*doV8XlxuUiAoFMhuWhn8vA.gif" /></figure><h4>📦 Browser Support and Polyfill</h4><p>As of June 2025, Temporal is still experimental, with limited browser support. According to Can I Use, it’s not fully supported in major browsers like Chrome, Firefox, or Safari, but experimental implementations exist (e.g., Firefox 139, Safari Technical Preview with flags). For production, you’ll likely need a polyfill.</p><p>Install the official polyfill via npm:</p><pre>npm install @js-temporal/polyfill</pre><p>Then import it:</p><pre>import { Temporal } from &#39;@js-temporal/polyfill&#39;;</pre><p>This lets you use Temporal in any browser, but keep an eye on MDN’s Temporal docs for updates on native support.</p><h3>⚠️ Drawbacks of Temporal</h3><p>Temporal is awesome, but it’s not perfect. Here’s the tea:</p><ul><li><strong>Experimental Status</strong>: The API might change, so your perfectly crafted code could break. Fun, right?</li><li><strong>Bundle Size Bloat</strong>: The polyfill adds weight to your app, which might make your bundle cry if you’re obsessed with performance.</li><li><strong>Learning Curve</strong>: If you’re cozy with Date’s quirks, learning Temporal’s 200+ methods might feel like studying for a PhD.</li><li><strong>Overkill for Simple Apps</strong>: Need a birthday reminder? Date is probably fine. Temporal’s like bringing a tank to a pillow fight for basic tasks.</li></ul><p>Still, for anything remotely complex, Temporal’s benefits outweigh these gripes.</p><h3>Conclusion</h3><p>The Temporal API is JavaScript’s long-overdue answer to the Date object’s chaos. With its intuitive methods, immutability, and timezone superpowers, it’s like finding out your old flip phone can be upgraded to a shiny new iPhone. Whether you’re building global apps or just tired of Date’s nonsense, Temporal is your new go-to.</p><p>So, ditch Date, embrace Temporal, and never look back. Your future self will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a994902844dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Docker: A Comprehensive Guide]]></title>
            <link>https://medium.com/@skarka90/getting-started-with-docker-a-comprehensive-guide-75a529d09134?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a529d09134</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 20:34:19 GMT</pubDate>
            <atom:updated>2025-04-06T20:34:19.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qTTVpy1BLGBY9jr7OcoLw.png" /></figure><blockquote>What is Docker?</blockquote><p>Docker is an open-source platform that automates the deployment, scaling, and management of applications through containerization. Unlike traditional virtual machines that virtualize an entire operating system, Docker containers virtualize only the application layer, making them lightweight, portable, and efficient.</p><blockquote>Why Use Docker?</blockquote><p>Docker solves the infamous “it works on my machine” problem by packaging applications with all their dependencies into standardized units called containers. Here’s why you should consider using Docker:</p><ol><li><strong>Consistency</strong>: Ensures your application runs the same way across all environments (development, testing, production)</li><li><strong>Isolation</strong>: Each container runs in isolation, preventing conflicts between applications</li><li><strong>Efficiency</strong>: Containers share the host OS kernel, making them more lightweight than virtual machines</li><li><strong>Portability</strong>: Docker containers run consistently across any platform that supports Docker</li><li><strong>Scalability</strong>: Easily scale applications by spinning up additional containers</li><li><strong>Version Control</strong>: Track changes to your Docker images, similar to code versioning</li><li><strong>Rapid Deployment</strong>: Quickly deploy applications with all dependencies pre-configured</li></ol><blockquote>Key Docker Concepts</blockquote><h4>Docker Image</h4><p>A Docker image is a lightweight, standalone, executable package that includes everything needed to run an application: code, runtime, libraries, environment variables, and configuration files. Think of it as a template or blueprint for creating containers.</p><h4>Docker Container</h4><p>A container is a running instance of a Docker image. It&#39;s an isolated environment with its own filesystem, networking, and isolated process tree. Unlike virtual machines, containers share the host system&#39;s kernel, making them more efficient.</p><h4>Dockerfile</h4><p>A Dockerfile is a text document containing a series of instructions that Docker uses to automatically build an image. It&#39;s essentially a recipe for creating a Docker image.</p><h4>Docker Hub</h4><p>Docker Hub is a cloud-based registry service where you can find, store, and share Docker images. It&#39;s like GitHub for Docker images.</p><blockquote>Creating Your First Docker Container: Node.js Backend Application</blockquote><p>Let’s walk through the process of containerizing a simple Node.js backend application.</p><blockquote>Prerequisites</blockquote><ul><li><a href="https://docs.docker.com/get-docker/">Docker</a> installed on your machine</li><li>Basic knowledge of Node.js.</li></ul><h4>Step 1: Create a Simple Node.js Application</h4><p>First, let’s create a directory for our project and initialize a new Node.js application:</p><pre>mkdir docker-nodejs-example<br>cd docker-nodejs-example<br>npm init -y<br>npm install express</pre><p>Now, create a file named app.js with the following content:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;Hello from Docker container!&#39;);<br>});<br><br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><h3>Step 2: Create a .dockerignore File</h3><p>Before creating our Dockerfile, let’s create a .dockerignore file to exclude unnecessary files from the build context:</p><pre>node_modules<br>npm-debug.log<br>.git<br>.gitignore<br>.env<br>.DS_Store<br>README.md</pre><p>This file tells Docker to ignore the specified files and directories when copying files to the container. Benefits include:</p><ul><li><strong>Smaller build context</strong>: Speeds up the build process</li><li><strong>Reduced image size</strong>: Results in smaller, more efficient containers</li><li><strong>Improved security</strong>: Prevents sensitive information from being included in your image</li><li><strong>Prevents caching issues</strong>: Avoids including local development files that might conflict with container setup</li></ul><h4>Step 3: Create a Dockerfile</h4><p>Next, create a file named Dockerfile (with no extension) in the root of your project:</p><pre># Use the official Node.js 18 alpine image as the base image<br>FROM node:18-alpine<br><br># Set the working directory inside the container<br>WORKDIR /app<br><br># Copy package.json and package-lock.json to the working directory<br>COPY package*.json ./<br><br># Install dependencies<br>RUN npm install<br><br># Copy the rest of the application code<br>COPY . .<br><br># Expose the port the app will run on<br>EXPOSE 3000<br><br># Command to run the application<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><h3>Step 4: Understanding the Dockerfile Commands</h3><p>Let’s break down each instruction in the Dockerfile:</p><ul><li><strong>FROM node:18-alpine</strong>: Specifies the base image to use. In this case, we’re using the official node:18-alpine image.</li><li><strong>WORKDIR /app</strong>: Sets the working directory inside the container to /app. All subsequent commands will be executed in this directory.</li><li>*<em>COPY package</em>.json ./**: Copies the package.json and package-lock.json files to the working directory. We copy these files first to take advantage of Docker’s layer caching mechanism.</li><li><strong>RUN npm install</strong>: Executes the command to install the dependencies defined in package.json.</li><li><strong>COPY . .</strong>: Copies the rest of the application code to the working directory. The .dockerignore file will prevent unnecessary files from being copied.</li><li><strong>EXPOSE 3000</strong>: Informs Docker that the container will listen on port 3000 at runtime. This is more of a documentation feature and doesn’t actually publish the port.</li><li><strong>CMD [“node”, “app.js”]</strong>: Specifies the command to run when the container starts. This will start our Node.js application.</li></ul><h3>Step 5: Build the Docker Image</h3><p>Now, let’s build the Docker image:</p><pre>docker build -t nodejs-app .</pre><p>Breaking down this command:</p><ul><li>docker build: The command to build a Docker image</li><li>-t nodejs-app: Tags the image with the name &quot;nodejs-app&quot;</li><li>.: Specifies the build context (the current directory)</li></ul><p>This command reads the Dockerfile in the current directory and creates a Docker image according to the instructions.</p><h3>Step 6: Run the Docker Container</h3><p>With our image built, we can now run a container based on that image:</p><pre>docker run -p 3000:3000 nodejs-app</pre><p>Breaking down this command:</p><ul><li>docker run: The command to create and start a container</li><li>-p 3000:3000: Maps port 3000 on the host to port 3000 on the container</li><li>nodejs-app: The name of the image to use</li></ul><p>Visit http://localhost:3000 in your browser, and you should see the message &quot;Hello from Docker container!&quot;</p><blockquote>Docker Compose: Managing Multi-Container Applications</blockquote><p>For more complex applications that require multiple containers (like a web app with a database), you can use Docker Compose to define and run multi-container Docker applications.</p><p>Create a file named docker-compose.yml</p><pre>version: &#39;3&#39;<br>services:<br>  app:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - NODE_ENV=production<br>    depends_on:<br>      - db<br>  db:<br>    image: mongo<br>    ports:<br>      - &quot;27017:27017&quot;<br>    volumes:<br>      - mongodb_data:/data/db<br><br>volumes:<br>  mongodb_data:</pre><p>To start the application using Docker Compose:</p><pre>docker-compose up</pre><blockquote>Best Practices for Docker</blockquote><ol><li><strong>Use Official Images</strong>: When possible, base your images on official Docker images.</li><li><strong>Minimize Layers</strong>: Combine commands to reduce the number of layers in your image.</li><li><strong>Multi-Stage Builds</strong>: Use multi-stage builds to create smaller production images.</li><li><strong>Don’t Run as Root</strong>: For security, avoid running containers as the root user.</li><li><strong>Use .dockerignore</strong>: Create a .dockerignore file to exclude unnecessary files from the build context.</li><li><strong>Cache Dependencies</strong>: Structure your Dockerfile to leverage Docker’s cache effectively.</li><li><strong>One Process per Container</strong>: Design containers to run a single process.</li><li><strong>Specify Version Tags</strong>: Use specific version tags for base images instead of ‘latest’ for predictability.</li><li><strong>Scan for Security Vulnerabilities</strong>: Regularly scan your Docker images for known vulnerabilities.</li></ol><blockquote>Conclusion</blockquote><p>Docker has become an essential tool in modern software development. By containerizing applications, you can ensure consistency across environments, simplify deployments, and improve resource utilization. The basic workflow involves creating a Dockerfile, building an image, and running containers based on that image.</p><p>As you get more comfortable with Docker, you can explore more advanced features like Docker Compose for multi-container applications, Docker Swarm or Kubernetes for orchestration, and CI/CD integration for automated deployments.</p><p>Happy containerizing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75a529d09134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the CAP Theorem: A Comprehensive Guide with Real-World Applications]]></title>
            <link>https://medium.com/@skarka90/understanding-the-cap-theorem-a-comprehensive-guide-with-real-world-applications-af54649b76fc?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/af54649b76fc</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 11:59:55 GMT</pubDate>
            <atom:updated>2024-08-03T19:35:41.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoK28brS_q3F6zw9wCUEpQ.png" /></figure><p>In the ever-evolving landscape of distributed systems, the CAP theorem stands as a cornerstone principle that guides architects and developers in making crucial design decisions. Proposed by computer scientist Eric Brewer in 2000 and later proven by <strong>Seth Gilbert</strong> and <strong>Nancy Lynch</strong> in 2002, this theorem has profoundly influenced how we approach the challenges of building large-scale, distributed applications. In this comprehensive guide, we’ll delve deep into the CAP theorem, explore its implications, and examine real-world scenarios where it plays a pivotal role.</p><h3>What is the CAP Theorem?</h3><p>The CAP theorem, also known as <strong>Brewer’s theorem</strong>, posits that in a distributed data store, it is impossible to simultaneously guarantee all three of the following properties:</p><ol><li><strong>Consistency (C)</strong>: All nodes in the system see the same data at the same time. In other words, a read operation will return the most recent write operation’s value, regardless of which node receives the request.</li><li><strong>Availability (A)</strong>: Every request to the system receives a response, without guarantee that it contains the most recent version of the data. The system remains operational and responsive at all times.</li><li><strong>Partition Tolerance (P)</strong>: The system continues to operate despite network partitions or failures that prevent some nodes from communicating with others.</li></ol><p>According to the theorem, a distributed system can only guarantee two out of these three properties at any given time.</p><h3>Understanding the CAP Properties in Depth</h3><h4>Consistency</h4><p>In the context of the CAP theorem, consistency refers to linearizability or strong consistency. This means that once a <strong>write</strong> operation is completed, all subsequent <strong>read</strong> operations should reflect that write, regardless of which node in the distributed system handles the read request.</p><p><strong>Example</strong>: In a consistent system, if user A updates their profile picture, user B should see the new picture immediately after the update, no matter which server they connect to.</p><p><strong>Challenges</strong>: Achieving strong consistency often requires synchronization mechanisms that can introduce latency and potentially impact availability during network issues.</p><h4>Availability</h4><p>Availability ensures that every request to a non-failing node in the system receives a response, without the guarantee that it contains the most recent data. This property is crucial for systems that need to remain operational under all circumstances.</p><p><strong>Example</strong>: An e-commerce platform that prioritizes availability would allow users to browse products and make purchases even if some parts of the system are experiencing issues.</p><p><strong>Challenges</strong>: Maintaining high availability can sometimes come at the cost of consistency, as the system might serve stale data to keep functioning during network partitions.</p><h4>Partition Tolerance</h4><p>Partition tolerance is the ability of a system to continue operating despite network partitions. A network partition occurs when network failures prevent some nodes in the distributed system from communicating with others.</p><p><strong>Example</strong>: In a globally distributed database, if the transatlantic link goes down, creating a partition between European and American data centers, the system should continue to function on both continents.</p><p><strong>Challenges</strong>: Designing for partition tolerance often involves complex strategies for data replication and conflict resolution.</p><h3>The CAP Trade-offs: Choosing Your Priorities</h3><p>Given the impossibility of simultaneously achieving all three CAP properties, system designers must choose which two properties to prioritize based on their specific use case:</p><ol><li><strong>CP (Consistency and Partition Tolerance)</strong>: Systems that choose CP sacrifice availability in favor of ensuring data consistency across all operational nodes. These systems may become unavailable during a network partition but will never return stale or inconsistent data. <br><strong>Use Case</strong>: Financial systems or inventory management where data accuracy is critical.</li><li><strong>AP (Availability and Partition Tolerance)</strong>: AP systems prioritize availability and can operate during network partitions, but may return stale or inconsistent data. These systems often employ eventual consistency models to reconcile data over time. <br><strong>Use Case</strong>: Social media platforms, and content delivery networks where immediate access to data is more important than perfect consistency.</li><li><strong>CA (Consistency and Availability)</strong>: While theoretically possible in a system that never experiences network partitions, CA is generally not considered a practical choice for distributed systems operating over networks. In reality, all distributed systems must be partition-tolerant to some degree. <br><strong>Use Case</strong>: Traditional relational databases in a single-node setup (not distributed).</li></ol><h3>Real-World Example: E-commerce Platform</h3><p>Let’s consider a large-scale e-commerce platform to illustrate how the CAP theorem influences system design in practice.</p><h4>Scenario:</h4><p>You’re the lead architect for a global e-commerce platform that handles millions of transactions daily. The platform needs to manage product inventory, user shopping carts, and order processing across multiple data centers worldwide.</p><h3>CAP Considerations:</h3><ol><li><strong>Product Inventory Management (CP Approach)</strong>: For managing product inventory, you might choose a CP system to ensure that stock levels are always accurate across all nodes.</li></ol><ul><li><strong>Implementation</strong>: Use a distributed database with strong consistency guarantees, such as PostgreSQL or MySQL.</li><li><strong>Pros</strong>: Prevents overselling products, and ensures accurate stock information for customers.</li><li><strong>Cons</strong>: During network partitions, some regions might temporarily lose access to inventory data, potentially halting sales.</li></ul><p>2.<strong> Shopping Cart Service (AP Approach)</strong>: For managing user shopping carts, an AP system might be more appropriate to ensure users can always add or remove items from their carts.</p><ul><li><strong>Implementation</strong>: Use a distributed NoSQL database like Apache Cassandra with eventual consistency.</li><li><strong>Pros</strong>: Users can always interact with their shopping carts, even during network issues.</li><li><strong>Cons</strong>: In rare cases, users might see temporary inconsistencies in their cart contents across devices.</li></ul><p>3.<strong> Order Processing (Hybrid Approach)</strong>: For order processing, a hybrid approach might be necessary, using different strategies for different parts of the process.</p><ul><li><strong>Implementation</strong>:</li><li>Use a CP system for critical operations like payment processing and inventory deduction.</li><li>Use an AP system for order status updates and non-critical order details.</li><li><strong>Pros</strong>: Ensures financial accuracy while maintaining high availability for most user interactions.</li><li><strong>Cons</strong>: Increases system complexity and requires careful design to handle edge cases.</li></ul><h3>Real-World Trade-offs:</h3><ol><li><strong>Inventory Accuracy vs. Sales Opportunity</strong>: By choosing a CP system for inventory, you ensure accurate stock levels but risk losing sales during network partitions. This trade-off is often acceptable to prevent overselling and the resulting customer dissatisfaction.</li><li><strong>User Experience vs. Perfect Consistency</strong>: The AP approach for shopping carts prioritizes user experience, ensuring customers can always interact with their carts. The potential for temporary inconsistencies is usually an acceptable trade-off for improved availability.</li><li><strong>System Complexity vs. Optimized Performance</strong>: The hybrid approach for order processing allows for optimized handling of different aspects of the order lifecycle. However, it increases system complexity, requiring more sophisticated monitoring and management.</li></ol><h3>Conclusion</h3><p>The CAP theorem remains a fundamental concept in distributed systems design, providing a framework for understanding the inherent trade-offs in building large-scale, resilient applications. By carefully considering the specific requirements of each component in a system, architects can make informed decisions about how to balance consistency, availability, and partition tolerance.</p><p>In our e-commerce example, we saw how different parts of the system might prioritize different CAP properties based on their specific needs.</p><p>As you design and build distributed systems, remember that the CAP theorem is not about limitations, but about making informed choices. By understanding these fundamental principles, you can create robust, scalable systems that effectively meet the needs of your users and your business.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af54649b76fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Guide to Hydration and Hydration Errors in Next.js]]></title>
            <link>https://medium.com/@skarka90/the-ultimate-guide-to-hydration-and-hydration-errors-in-next-js-ae9b4bc74ee2?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae9b4bc74ee2</guid>
            <category><![CDATA[errors-and-omissions]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[next-js-developer]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 10:09:20 GMT</pubDate>
            <atom:updated>2024-07-07T10:09:20.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_ticadsofJ7kt5DgdSdZg.jpeg" /></figure><blockquote><strong>Introduction</strong></blockquote><p>Next.js has revolutionized how we build React applications by offering powerful features like server-side rendering (SSR), static site generation (SSG), and automatic code splitting. At the heart of Next.js’s rendering strategy lies a crucial concept: hydration. Understanding hydration and how to handle related errors is essential for any developer working with Next.js. This comprehensive guide will delve deep into the world of hydration, ensuring you have all the knowledge you need to build robust, high-performance Next.js applications.</p><blockquote><strong>What is Hydration?</strong></blockquote><p><em>Hydration is the process of taking static HTML generated on the server and making it interactive on the client side by attaching event listeners and states.</em></p><p>Imagine you’re at a food store. You see a packet of ready-to-eat noodles — it has all the ingredients, but it’s not quite edible yet. To make it edible, you need to add hot water. This process of adding hot water to make the noodles ready is similar to what hydration does in Next.js.</p><p>In technical terms:</p><ol><li>The server generates static HTML.</li><li>This HTML is sent to the client (browser) for fast initial render.</li><li>JavaScript bundles are then loaded in the browser.</li><li>Next.js “hydrates” the static HTML by attaching event handlers and reconciling the server-rendered HTML with the client-side React component tree.</li></ol><blockquote><strong>The Hydration Process in Detail</strong></blockquote><ol><li><strong>Server-Side Rendering</strong>: When a user requests a page, Next.js generates the initial HTML on the server. This includes the basic structure and content of your React components.</li><li><strong>Initial HTML Delivery</strong>: This pre-rendered HTML is sent to the browser. At this point, the user can see the content, but it’s not interactive.</li><li><strong>JavaScript Loading</strong>: Next.js then sends the necessary JavaScript files to the browser. This includes your React components and the Next.js runtime.</li><li><strong>React Bootstrapping</strong>: Once the JavaScript is loaded, React starts up in the browser.</li><li><strong>Reconciliation</strong>: React compares the DOM created from the server HTML with the virtual DOM it would create by rendering the components on the client. This step ensures that the client-side React tree matches the server-rendered HTML.</li><li><strong>Event Handlers Attachment</strong>: React attaches all necessary event handlers to the DOM elements. This is what makes your page interactive.</li></ol><p>Here’s a simplified code example to illustrate:</p><pre>// This component will be rendered on both server and client<br>function Button() {<br>  const [count, setCount] = React.useState(0);<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      Clicked {count} times<br>    &lt;/button&gt;<br>  );<br>}<br><br>// On the server, this renders as static HTML<br>// &lt;button&gt;Clicked 0 times&lt;/button&gt;<br><br>// After hydration on the client, it becomes interactive<br>// The onClick handler is attached, and state updates will work</pre><blockquote><strong>Why is Hydration Important?</strong></blockquote><p>Hydration is crucial for several reasons:</p><ol><li><strong>Performance</strong>: It allows for quick initial page loads (thanks to server-side rendering) while still providing the full interactivity of a React app.</li><li><strong>SEO</strong>: Search engines can easily crawl the initial HTML, improving your site’s search engine optimization.</li><li><strong>User Experience</strong>: Users see content quickly and get an interactive experience shortly after, providing the best of both worlds.</li><li><strong>Progressive Enhancement</strong>: It supports progressive enhancement, where the basic content is available even if JavaScript fails to load or execute.</li></ol><blockquote><strong>Hydration Errors: What They Are and Why They Happen</strong></blockquote><p>Hydration errors occur when there’s a mismatch between the HTML generated on the server and what React expects to render on the client during the reconciliation process.</p><p>When React hydrates the server-rendered content, it expects the client-side render to produce the exact same HTML structure. If there’s any difference, React will throw a hydration error.</p><p>These errors usually appear in the console with messages like:</p><pre>Warning: Text content did not match. Server: &quot;Hello,&quot; Client: &quot;Hello, James&quot;</pre><p>Or</p><pre>Warning: Expected server HTML to contain a matching &lt;div&gt; in &lt;body&gt;.</pre><blockquote><strong>Common Causes of Hydration Errors</strong></blockquote><ol><li><strong>Inconsistent Rendering</strong>: When components render differently on the server and client.</li></ol><pre>function InconsistentComponent() {<br>  // This will generate different content on server and client<br>  const randomNumber = Math.random();<br>  return &lt;div&gt;{randomNumber}&lt;/div&gt;;<br>}</pre><p>2. <strong>Browser-only APIs</strong>: Using APIs that only exist in the browser during server-side rendering.</p><pre>function BrowserOnlyComponent() {<br>  // This will throw an error on the server<br>  const windowWidth = window.innerWidth;<br>  return &lt;div&gt;Window width: {windowWidth}&lt;/div&gt;;<br>}</pre><p>3. <strong>Time-dependent Rendering</strong>: Components that render based on the current time can cause issues.</p><pre>function TimeComponent() {<br>  // This will likely be different between server and client<br>  const currentHour = new Date().getHours();<br>  return &lt;div&gt;Current hour: {currentHour}&lt;/div&gt;;<br>}</pre><p>4. <strong>Environment-specific Code</strong>: Code that behaves differently based on the environment (server vs. client).</p><pre>function EnvironmentSpecificComponent() {<br>  const isServer = typeof window === &#39;undefined&#39;;<br>  return &lt;div&gt;{isServer ? &#39;Server&#39; : &#39;Client&#39;}&lt;/div&gt;;<br>}</pre><blockquote><strong>How to Fix Hydration Errors</strong></blockquote><ol><li><strong>Use useEffect for Client-side Code</strong>:</li></ol><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function SafeComponent() {<br>  const [windowWidth, setWindowWidth] = useState(0);<br>  <br>  useEffect(() =&gt; {<br>    setWindowWidth(window.innerWidth);<br>  }, []);<br><br>  return &lt;div&gt;Window width: {windowWidth}&lt;/div&gt;;<br>}</pre><p>2. <strong>Check for Browser Environment:</strong></p><pre>function SafeComponent() {<br>  const [isBrowser, setIsBrowser] = useState(false);<br><br>  useEffect(() =&gt; {<br>    setIsBrowser(true);<br>  }, []);<br><br>  return &lt;div&gt;{isBrowser ? &#39;In browser&#39; : &#39;On server&#39;}&lt;/div&gt;;<br>}</pre><p>3. <strong>Use Stable Values for Initial Render</strong>:</p><pre>function TimeComponent() {<br>  const [currentHour, setCurrentHour] = useState(0);<br><br>  useEffect(() =&gt; {<br>    setCurrentHour(new Date().getHours());<br>  }, []);<br><br>  return &lt;div&gt;Current hour: {currentHour}&lt;/div&gt;;<br>}</pre><blockquote><strong>Best Practices for Avoiding Hydration Errors</strong></blockquote><ul><li><strong>Keep Components Pure</strong>: Ensure your components produce the same output for a given input, regardless of the environment.</li><li><strong>Avoid Direct DOM Manipulation</strong>: Let React handle DOM updates to prevent inconsistencies between server and client renders.</li><li><strong>Be Cautious with Third-Party Libraries</strong>: Ensure any libraries you use support SSR or use them only on the client-side.</li><li><strong>Use Next.js’s Image Component</strong>: For images, use the next/image component, which handles many edge cases and optimizations for you.</li><li><strong>Implement Proper Loading States</strong>: Use loading states for data that’s not immediately available to prevent render mismatches.</li></ul><blockquote><strong>Conclusion</strong></blockquote><p>Hydration is a key process in Next.js that brings your static HTML to life in the browser. Here’s what to remember:</p><ol><li>Hydration makes server-rendered pages interactive.</li><li>It can cause errors when server and client renders don’t match.</li><li>Common causes include using browser-only APIs too early and data mismatches.</li><li>To avoid errors, keep renders consistent.</li></ol><p>By understanding hydration, you can build faster, more reliable Next.js applications. Keep your server and client renders consistent, and you’ll avoid most hydration headaches. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae9b4bc74ee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CCAvenue Integration with Node Js]]></title>
            <link>https://medium.com/@skarka90/ccavenue-integration-with-node-js-74e8c7843310?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e8c7843310</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ccavenue]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 18:29:21 GMT</pubDate>
            <atom:updated>2023-12-22T08:13:10.347Z</atom:updated>
            <content:encoded><![CDATA[<p>Payment integration is one of the most crucial and important parts of any application we build. Additionally, we need to be very conscious about security. To save time and avoid reinventing the wheel, there are many payment gateways available, such as Paytm, Bill desk, CCAvenue, etc. Among these, many have stopped onboarding new merchants due to RBI guidelines. However, I found that CCAvenue is still allowing new merchants. The problem with CCAvenue is that their documentation is very vague. The first time I integrated CCAvenue, I had to waste days and weeks. So, I decided to write a blog that will help you in case you are stuck.</p><p>Note: Before starting implementation I am assuming that you have anactivated CCAvenue account,merchant Id,working key and a access code</p><h3>Flow of request and response</h3><p><strong>Step 1</strong>: First, we hit the ccAvenueRequest URL.</p><p><strong>Step 2</strong>: The server returns an encrypted response.</p><p><strong>Step 3</strong>: With this encrypted response and access key provided by the CCAvenue, we make a request to the CCAvenue.</p><p><strong>Step 4</strong>: Payment page render</p><p><strong>Step 5</strong>: After the customer makes the payment, ccAvenue hits the response URL and sends an encrypted request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*KJ6nV1A5QsxEXrSzUh13YQ.jpeg" /></figure><h3>Main Components</h3><ol><li>A request handler</li><li>A response handler</li><li>A function to encrypt</li><li>A function to decrypt</li></ol><h3>Code For the components</h3><h4>Request handler</h4><pre>var http = require(&#39;http&#39;),<br>    fs = require(&#39;fs&#39;),<br>    ccav = require(&#39;./ccavutil.js&#39;),<br>    crypto = require(&#39;crypto&#39;),<br>    qs = require(&#39;querystring&#39;);<br><br><br>exports.postReq = function(request,response){<br><br>    var body = &#39;&#39;,<br>	workingKey = &#39;XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&#39;,	//Put in the 32-Bit key shared by CCAvenues.<br>	accessCode = &#39;XXXXXXXXXXXXXXXXXXX&#39;,			//Put in the Access Code shared by CCAvenues.<br>	encRequest = &#39;&#39;,<br>   <br>    //Generate Md5 hash for the key and then convert in base64 string<br>    var md5 = crypto.createHash(&#39;md5&#39;).update(workingKey).digest();<br>    var keyBase64 = Buffer.from(md5).toString(&#39;base64&#39;);<br><br>    //Initializing Vector and then convert in base64 string<br>    var ivBase64 = Buffer.from([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,0x0e, 0x0f]).toString(&#39;base64&#39;);<br><br>	body += requst.payment_string;<br>	encRequest = ccav.encrypt(body, keyBase64, ivBase64);<br>    <br>   return res.status(200); <br>};</pre><p><strong>Note:The request body should be exactly in this format</strong></p><pre>&quot;payment_string&quot;:&quot;merchant_id=XXXXX&amp;order_id=0001&amp;currency=INR&amp;amount=6000.00&amp;redirect_url=http:/ccavResponse&amp;cancel_url=ccavResponse&amp;language=EN&quot;</pre><p>And the mandatory fileds are</p><p><strong>merchant_id</strong>(Numeric) : Merchant Id is a unique identifier generated by CCAvenue for each activated merchant.</p><p><strong>order_id</strong>(Alphanumeric) : This ID is used by merchants to identify the order. Ensure that you send a unique id with each request. CCAvenue will not check the uniqueness of this order id. As it generates a unique payment reference number for each order which is sent by the merchant.</p><p><strong>currency</strong>(Alphabet(3)) : Currency in which you want to process the transaction. INR — Indian Rupee USD — United States Dollar SGD — Singapore Dollar GBP — Pound Sterling EUR — Euro, official currency of Eurozone</p><p><strong>amount</strong>(Numeric) : Order amount</p><p><strong>redirect_url</strong>(Alphanumeric) : CCAvenue will post the status of the order along with the parameters to this URL. If you do not send this value, order status will be sent back to the URL configured in dynamic event notifications module in your MARS account. If there is no URL configured in the MARS account, PG will display the status of the order on the CCAvenue confirmation page.</p><p><strong>cancel_url</strong>(Alphanumeric) :CCAvenue will redirect the customer to this URL if the customer cancels the transaction on the billing page.</p><p><strong>language</strong>(Alphabet(5)) : CCAvenue billing page is multi-lingual. Currently we are displaying the page in English (Code — EN).</p><p>If we need to pass some of our customized parameter the CCAvenue give us <strong>merchant_param1</strong> to <strong>merchant_param5</strong> we can send upto 5 custom param in case we want to pass additional information like userId for our DataBase operation</p><p>After you get the encrypted token form your server make a <strong>POST </strong>request to this url</p><p><a href="https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction&amp;Merchant_Id=XXXXXX&amp;encRequest=token">https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction&amp;Merchant_Id=XXXXXX&amp;encRequest=token</a></p><p><strong>Note: Put your merchant id and the token you get from the server</strong></p><h4>Response handler</h4><pre>var http = require(&#39;http&#39;),<br>    fs = require(&#39;fs&#39;),<br>    ccav = require(&#39;./ccavutil.js&#39;),<br>    crypto = require(&#39;crypto&#39;),<br>    qs = require(&#39;querystring&#39;);<br><br>exports.postRes = function(request,response){<br>	ccavResponse=&#39;&#39;,	<br>	workingKey = &#39;XXXXXXXXXXXXXXXXXXXX&#39;,	//Put in the 32-Bit key shared by CCAvenues.<br><br>	<br>    //Generate Md5 hash for the key and then convert in base64 string<br>    var md5 = crypto.createHash(&#39;md5&#39;).update(workingKey).digest();<br>    var keyBase64 = Buffer.from(md5).toString(&#39;base64&#39;);<br><br>    //Initializing Vector and then convert in base64 string<br>    var ivBase64 = Buffer.from([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,0x0e, 0x0f]).toString(&#39;base64&#39;);<br>    <br>    ccavResponse = decrypt(request.body.encResp, keyBase64, ivBase64);<br><br>    // your logic here <br><br>	<br>};</pre><p><strong>Structure of the dycrypt response by ccAvenue</strong></p><pre>{&quot;order_id=1692702458009934_2711981&amp;tracking_id=112980871927&amp;bank_ref_no=XXXXXXXXXXXXXXXXX&amp;order_status=Success&amp;failure_message=&amp;payment_mode=Wallet&amp;card_name=Paytm&amp;status_code=null&amp;status_message=Txn Success&amp;currency=INR&amp;amount=1.00&amp;billing_name=Customer Name&amp;billing_address=Everest house&amp;billing_city=Kolkata&amp;billing_state=West Bengal&amp;billing_zip=700085&amp;billing_country=India&amp;billing_tel=801XXXXX&amp;billing_email=customer@gmail.com&amp;delivery_name=customer_name&amp;delivery_address=house&amp;delivery_city=Kolkata&amp;delivery_state=West Bengal&amp;delivery_zip=700085&amp;delivery_country=India&amp;delivery_tel=801XXXXX&amp;merchant_param1=&amp;merchant_param2=&amp;merchant_param3=&amp;merchant_param4=&amp;merchant_param5=&amp;vault=N&amp;offer_type=null&amp;offer_code=null&amp;discount_value=0.0&amp;mer_amount=1.00&amp;eci_value=null&amp;retry=N&amp;response_code=0&amp;billing_notes=&amp;trans_date=22/08/2023 16:38:33&amp;bin_country=&quot;}</pre><h4>Function to encrypt</h4><pre>    exports.encrypt = function(plainText, keyBase64, ivBase64) {<br><br>    const key = Buffer.from(keyBase64, &#39;base64&#39;);<br>    const iv = Buffer.from(ivBase64, &#39;base64&#39;);<br><br>    const cipher = crypto.createCipheriv(getAlgorithm(keyBase64), key, iv);<br>    let encrypted = cipher.update(plainText, &#39;utf8&#39;, &#39;hex&#39;)<br>    encrypted += cipher.final(&#39;hex&#39;);<br>    return encrypted;<br>}</pre><h4>Function to dycryption</h4><pre>exports.decrypt = function(messagebase64, keyBase64, ivBase64) {<br><br>    const key = Buffer.from(keyBase64, &#39;base64&#39;);<br>    const iv = Buffer.from(ivBase64, &#39;base64&#39;);<br><br>    const decipher = crypto.createDecipheriv(getAlgorithm(keyBase64), key, iv);<br>    let decrypted = decipher.update(messagebase64, &#39;hex&#39;);<br>    decrypted += decipher.final();<br>    return decrypted;<br>}</pre><h4>Util Function for getting Algorithm</h4><pre>function getAlgorithm(keyBase64) {<br>    var key = Buffer.from(keyBase64, &#39;base64&#39;);<br>    switch (key.length) {<br>        case 16:<br>            return &#39;aes-128-cbc&#39;;<br>        case 32:<br>            return &#39;aes-256-cbc&#39;;<br><br>    }<br>    throw new Error(&#39;Invalid key length: &#39; + key.length);<br>}</pre><p>And lastly, you need to create two endpoints: one for CCAvenue response, another for CCAvenue request, and another for cancel (if you want to handle cancel separately).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sm8hWlYbSRvQsBoavFDDhg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e8c7843310" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is GraphQL going to replace REST?]]></title>
            <link>https://medium.com/@skarka90/is-graphql-going-to-replace-rest-80dd00ee75de?source=rss-4fdc48f59362------2</link>
            <guid isPermaLink="false">https://medium.com/p/80dd00ee75de</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Arka Sheikh]]></dc:creator>
            <pubDate>Sun, 01 Oct 2023 10:25:48 GMT</pubDate>
            <atom:updated>2023-10-01T10:25:48.278Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s find out…</p><p>GraphQL is a query language for APIs that was developed by <em>Facebook</em> in 2012 and later open-sourced in 2015. It was created to address specific challenges faced by the company’s mobile app development teams. It offers a more flexible way to request and receive data from a server compared to traditional REST APIs. It allows clients to request exactly the data they need, which can lead to more efficient and faster interactions, especially in scenarios where over-fetching or under-fetching of data is a concern.</p><p>Tech giants like <em>PayPal, Netflix, Shopify, Airbnb, and Github</em> have already adopted GraphQL.</p><p>Here are some pros and cons of GraphQL:</p><p><strong>PROS</strong>:</p><ul><li>Makes development easier and faster.</li><li>Has only one single endpoint, so developers don’t need to manage multiple endpoints like in REST.</li><li>With GraphQL, versioning of APIs is often not necessary because clients can request only the data they need. This can lead to smoother transitions when making changes to the API.</li><li>GraphQL uses a strongly typed schema to define the types and relationships of data. This can provide better tooling, including auto-generation of documentation and client libraries.</li><li>GraphQL can be integrated with real-time subscriptions, allowing for live updates to data.</li></ul><p><strong>CONS</strong>:</p><ul><li>Setting up a GraphQL server can be more complex than a REST API, especially if you have complex data relationships or need to optimize for performance.</li><li>Caching in GraphQL can be more challenging compared to REST, as the response structure can vary based on the query. Implementing efficient caching strategies requires careful consideration.</li><li>While GraphQL tooling has come a long way, it may not be as mature or standardized as REST tooling, which has been around for a much longer time.</li><li>Developers and teams unfamiliar with GraphQL may face a learning curve when transitioning from REST to GraphQL.</li><li>File upload is currently not supported with Apollo version 4.</li></ul><p>In <em>REST</em>, as we have been developing for a long time, we get familiar with the server setup. Additionally, it supports multipart form data, i.e., file uploading. Also, most of the third-party payment and other APIs still use REST. So, if we are planning to code our complete application in GraphQL, we still need to create a few REST endpoints. Last but not least, REST has a large developer community which is lacking in the case of GraphQL.</p><p>I conclude by considering all the facts that both REST and GraphQL will coexist. GraphQL is particularly well-suited for applications with complex and diverse data requirements, while REST may be a better fit for simpler, more standardized APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggQwYjhf-05YBUR3SCTPvQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80dd00ee75de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>