<?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 Nikhil Modi on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Modi on Medium]]></description>
        <link>https://medium.com/@nikhilkumarmodi?source=rss-644723183996------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DLR616H9VQuXrAvxHacotA.jpeg</url>
            <title>Stories by Nikhil Modi on Medium</title>
            <link>https://medium.com/@nikhilkumarmodi?source=rss-644723183996------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:02:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikhilkumarmodi/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[Why Your React 16 SSR Might Be a Lie (And Nobody Warns You)]]></title>
            <link>https://medium.com/@nikhilkumarmodi/why-your-react-16-ssr-might-be-a-lie-and-nobody-warns-you-533581ee4afa?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/533581ee4afa</guid>
            <category><![CDATA[hydration]]></category>
            <category><![CDATA[react-16]]></category>
            <category><![CDATA[client-side-rendering]]></category>
            <category><![CDATA[loadable-component]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 17:10:03 GMT</pubDate>
            <atom:updated>2026-08-02T17:37:45.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>A field guide to the silent failure modes of server-rendering a code-split React app — for teams where jumping straight to React 18 or 19 isn’t on the table yet.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMUz6CjtdxWn0jLuh86B4w.png" /></figure><p>Here’s a sentence that sounds reassuring right up until you check the raw network response:</p><blockquote>“Our application is server-side rendered.”</blockquote><p>We said that about a production dashboard in a large, years-old React 16 app. Node.js was firing off the server-side API calls. ReactDOMServer.renderToString() was executing without a single thrown error. The page loaded fast in the browser. Every internal signal said <strong>SSR is working.</strong></p><p><a href="https://claude.ai/public/artifacts/432c54b5-a9ed-4bc9-8828-5fc16c8ff32a"><strong>Click here to read for free</strong></a></p><p>It wasn’t. Not in the way that actually matters.</p><p>This is the story of how that application went from a <em>silent, fake</em> SSR state, through a genuinely broken hydration attempt, to a system that finally does what “server-side rendered” is supposed to mean — including three bugs along the way that never once threw an error, and one deployment mistake that took the whole site down.</p><p>If you maintain a large production React 16/17 codebase and code-splitting + SSR is on your plate, this is the guide I wish had existed before we started.</p><h3>Part 1 — The Code-Splitting Trap: Silent null Renders</h3><p>To keep the initial JS bundle lean, an app like this leans hard on code-splitting: dozens of routes and widgets, each lazy-loaded as its own chunk via React.lazy() or a dynamic import().</p><p>That’s the right instinct for the browser. It’s a trap on the server.</p><p><strong>The constraint:</strong> renderToString() is 100% synchronous. It cannot pause execution, await a Promise, or resume once a chunk has finished loading.</p><pre>const Dashboard = React.lazy(() =&gt; import(&#39;./Dashboard&#39;))<br><br>// On the server:<br>renderToString(<br>  &lt;Suspense fallback={null}&gt;<br>    &lt;Dashboard /&gt;<br>  &lt;/Suspense&gt;<br>)</pre><p>When Node hits &lt;Dashboard /&gt;, the chunk&#39;s module almost certainly isn&#39;t sitting in memory yet — import() just kicked off an asynchronous load. React has no way to wait for it, so it falls straight through to the Suspense fallback. In our case: null.</p><pre>┌─────────────────────────────────────────────────┐<br>│              THE SILENT NULL RENDER              │<br>├─────────────────────────────────────────────────┤<br>│ 1. renderToString() hits &lt;Dashboard/&gt;            │<br>│ 2. Triggers import(&#39;./Dashboard&#39;)  ──▶ Promise   │<br>│ 3. React CANNOT await mid-render                 │<br>│ 4. Falls back to &lt;Suspense fallback&gt;             │<br>│ 5. Server response: 200 OK, &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;│<br>└─────────────────────────────────────────────────┘</pre><p>The result: a 200 OK, well-formed HTML, zero thrown errors — and the one thing you actually wanted rendered is just gone. You&#39;re burning a full Node.js render pass, real API calls included, to ship an empty shell. That&#39;s not SSR. That&#39;s CSR with a more expensive server bill.</p><h3>The partial-rollout crash</h3><p>The fix for the above is a library built specifically for this problem — in a React 16/17 codebase, the standard answer is @loadable/component. It pairs a Babel plugin that annotates lazy imports, a wrapper that resolves chunks <em>synchronously</em> on the server via a build-time manifest, and a ChunkExtractor that tracks exactly which components a given render touched.</p><p>The annotation is opt-in, per component:</p><pre>const Dashboard = Loadable({<br>  loader: /* #__LOADABLE__ */ () =&gt; import(&#39;./Dashboard&#39;),<br>  loading: () =&gt; null<br>})</pre><p>Miss the comment on a component that gets rendered inside a tracked tree, and the library doesn’t skip it quietly — it throws a hard invariant (“SSR requires the babel plugin”). In a codebase with years of accumulated lazy-loaded widgets, annotating everything in one PR wasn’t realistic. So we scoped chunk-tracking to <strong>one route</strong> first, and left every other route rendering the old way until its turn came.</p><p>Reasonable plan. Here’s the mistake in the execution — the template logic deciding whether to inject the tracked script tags needed a default value for the “not tracking this route” case, and didn’t get one.</p><p>The one route we’d wired up set that value. <strong>Every other route on the site hadn’t — and every other route started 500ing.</strong> One line fixed it (default the value to false alongside its sibling flags). The bigger lesson: when you scope a new code path to &quot;just this route for now,&quot; go find every template and shared middleware that path touches, and make sure the <em>unscoped</em> case has an explicit, safe default.</p><h3>Part 2 — Real Hydration Isn’t Automatic</h3><p>Once chunk-tracking was correctly scoped, the natural next question was the client bootstrap: ReactDOM.render() throws away the server&#39;s markup and rebuilds from scratch. ReactDOM.hydrate() is supposed to reuse it.</p><p>Switching to hydrate() alone does <strong>not</strong> fix a race condition that&#39;s still very much alive:</p><pre>┌──────────────────────────────────────────────────┐<br>│               THE HYDRATION HANDOFF                │<br>├──────────────────────────────────────────────────┤<br>│ 1. Server sends HTML   ──▶ real content, populated │<br>│ 2. Browser parses HTML ──▶ starts painting          │<br>│ 3. Browser requests chunk JS (in parallel)          │<br>│ 4. hydrate() fires the MOMENT app.js is ready       │<br>│ 5. If the chunk isn&#39;t loaded yet ──▶ mismatch,      │<br>│    React discards the DOM, re-renders client-side   │<br>└──────────────────────────────────────────────────┘</pre><p>For hydration to be seamless, the client’s first render pass has to produce the <em>exact same tree</em> the server already sent. If the JS chunk for a specific route hasn’t finished downloading by the time hydrate() runs, React has no choice — it throws away perfectly good server-rendered markup and falls back to rendering client-side, flash included.</p><p>This is exactly why ChunkExtractor matters beyond just fixing the server: its job is also to inject &lt;script&gt; tags for precisely the chunks a given render touched, so the browser starts fetching them <em>immediately</em>, in parallel with everything else — ideally finishing before hydrate() ever runs.</p><h3>Why not just use React 18 or 19?</h3><p>A fair question. React 18 shipped renderToPipeableStream, which <em>can</em> suspend mid-render on the server and stream a fallback that gets swapped out later — a real, native answer to this exact problem. If you&#39;re starting fresh, use that.</p><p>Rendering model</p><ul><li><strong>React 16/17:</strong> Fully synchronous (renderToString)</li><li><strong>React 18:</strong> Streaming / concurrent (renderToPipeableStream)</li><li><strong>React 19:</strong> Streaming, refined further</li></ul><p>Lazy imports during SSR</p><ul><li><strong>React 16/17:</strong> ❌ Silent fallback / null</li><li><strong>React 18:</strong> ✅ Native Suspense streaming support</li><li><strong>React 19:</strong> ✅ Same, plus use() for reading promises directly during render</li></ul><p>Asset loading control</p><ul><li><strong>React 16/17:</strong> Manual, via a chunk-tracking library</li><li><strong>React 18:</strong> Automatic via streaming boundaries</li><li><strong>React 19:</strong> Explicit preload/preinit/preconnect APIs for finer control</li></ul><p>Code-splitting fix required</p><ul><li><strong>React 16/17:</strong> Build-time manifest + synchronous require() (@loadable/component)</li><li><strong>React 18:</strong> Works largely out of the box</li><li><strong>React 19:</strong> Works out of the box, with more control</li></ul><p>For an existing, large, revenue-critical app, “just upgrade to React 18” is rarely a one-line change — it usually means a build-tool upgrade, revalidating state-management middleware, and re-testing every route. That’s a real, deliberate migration project, not a patch. Which is exactly why the fix below is a <em>legacy-compatible</em> one, not a rewrite.</p><h3>Part 3 — The Fix: Synchronous Requires and Chunk Manifests</h3><p>@loadable/component bridges webpack&#39;s async build output and Node&#39;s synchronous runtime by solving both sides of the problem.</p><p><strong>Server-side:</strong> instead of treating a component’s import() as an async network call, it consults a build-time stats file (loadable-stats.json) that maps every annotated component to its physical file on disk, then pulls it in with Node&#39;s native, synchronous require():</p><pre>import { ChunkExtractor } from &#39;@loadable/server&#39;<br><br>const extractor = new ChunkExtractor({<br>  statsFile: path.resolve(&#39;dist/loadable-stats.json&#39;),<br>  entrypoints: []<br>})<br>const markup = renderToString(<br>  extractor.collectChunks(&lt;Dashboard /&gt;)   // walks the tree, records every chunk touched<br>)<br>const scriptTags = extractor.getScriptTags()  // &lt;script&gt; tags for exactly those chunks</pre><p>renderToString() now has synchronous access to the real component, so it outputs the fully-populated HTML — no more silent null.</p><pre>Server renderToString() ──▶ Synchronous require(/build/Dashboard.js&#39;}) ──▶ Full HTML Output!</pre><p><strong>Client-side:</strong> before the response goes out, ChunkExtractor inspects which components were actually touched during that render and injects their &lt;script&gt; tags directly into the response:</p><pre>&lt;!-- injected automatically into the server&#39;s HTML --&gt;<br>&lt;script src=&quot;/static/js/Dashboard.chunk.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;/static/js/app.js&quot;&gt;&lt;/script&gt;</pre><p>The browser downloads Dashboard.chunk.js in parallel with app.js, so by the time hydrate() fires, the component&#39;s code is already sitting in memory — hydration reuses the server&#39;s DOM instantly, with zero flash and zero re-render.</p><h3>Part 4 — The Fixes Nobody’s Getting-Started Guide Mentions</h3><p>The architecture above is the part every @loadable/component tutorial covers. Here&#39;s what none of them warned us about.</p><h3>4.1 The CSS Chunking Bug</h3><p>With the JS pipeline working, a handful of components rendered with <strong>completely correct markup and zero visual styling</strong> — no background, no padding, no border radius. The DOM was right. The class names were right. The stylesheet just never showed up in the browser’s loaded styles.</p><p>The cause: a standard webpack splitChunks rule, meant to deduplicate code shared across lazy chunks, with no test restricting it to JavaScript:</p><pre>// ❌ Applies to CSS too — that&#39;s the bug<br>optimization: {<br>  splitChunks: {<br>    cacheGroups: {<br>      default: {<br>        minChunks: 2,<br>        priority: -20<br>      }<br>    }<br>  }<br>}</pre><p>Because this cache group has no test, webpack applies it to the CSS modules your extraction plugin (e.g. mini-css-extract-plugin) is <em>also</em> processing. Any stylesheet reachable from two or more lazy chunks gets swept into an anonymous, auto-named shared bundle — completely disconnected from the chunk it was written for.</p><p>ChunkExtractor has no idea this bundle exists. It only tracks <strong>named chunk groups</strong>, one per annotated import(). An auto-generated shared chunk isn&#39;t tied to any specific component, so it&#39;s never attributed to the render that needed it, and the injected &lt;script&gt; tags never reference it.</p><p>Two separate fixes, and missing either leaves you exactly where you started:</p><pre>// ✅ Fix 1 — scope the cache group to JS only<br>default: {<br>  test: /\.m?jsx?$/,<br>  minChunks: 2,<br>  priority: -20<br>}</pre><pre>// ✅ Fix 2 — most integration guides only show this line...<br>const scriptTags = extractor.getScriptTags()<br><br>// ...and skip the one that actually delivers your styles<br>const styleTags = extractor.getStyleTags()</pre><p>Even with the CSS correctly attributed after fix 1, nothing was ever asking for it until we added the second call. The symptom — correct markup, no styling — points a debugger at CSS specificity. The actual bug is a request that was never made.</p><h3>4.2 The Bug Hiding Behind “It’s Just Loading”</h3><p>This is the one we’re most glad we found, because it’s not specific to @loadable/component at all — it&#39;s a fact about React itself.</p><p>We moved several above-the-fold data fetches (things a user needs the instant the page loads) from client-only useEffect calls into the server&#39;s existing data pipeline. Reasonable, standard optimization. One section of the page still didn&#39;t show up server-side — not unstyled, structurally <em>absent</em>, as if it didn&#39;t exist.</p><p>We’d already confirmed the data was correctly present in the server-rendered state payload. So this wasn’t a data problem. Something was deciding not to render the section, and that decision was wrong.</p><pre>function useFeatureGate() {<br>  const [enabled, setEnabled] = useState(false)   // starts false, always<br>  const { isEligible } = useSelector(/* ... */)<br><br>  useEffect(() =&gt; {<br>    setEnabled(computeEligibility(isEligible))    // only runs client-side<br>  }, [isEligible])<br><br>  return enabled<br>}<br><br>function SummarySection() {<br>  const showSection = useFeatureGate()<br>  return showSection ? &lt;Metrics /&gt; : null<br>}</pre><p>useEffect never runs during server-side rendering — not &quot;runs late,&quot; genuinely does not run, by design. renderToString() calls the component, reads its output for the <em>current</em> state, and moves on. It never reaches the point where the effect would flip that flag.</p><p>So on the server, enabled is permanently stuck at its initial value. Every request. Regardless of what the real eligibility check would have returned. The component isn&#39;t broken — it&#39;s correctly rendering null, because as far as it&#39;s concerned during that render, the flag genuinely says &quot;don&#39;t show this.&quot;</p><p><strong>The generalized version of this bug:</strong> any component whose visibility depends on state that’s <em>only</em> ever corrected inside a useEffect — a feature flag computed on mount, an &quot;is this ready yet&quot; check, anything shaped like useState(initialGuess) plus an effect that corrects it — will silently never render correctly during SSR. No error. No warning.</p><p>The fix, once you see the shape, is close to a one-liner: don’t lag the decision behind an effect if its inputs are already available synchronously.</p><pre>function computeEligibility({ isEligible }) {<br>  return Boolean(isEligible)   // pure, no lifecycle needed<br>}<br><br>function SummarySection() {<br>  const { isEligible } = useSelector(/* ... */)<br>  const showSection = computeEligibility({ isEligible })<br>  return showSection ? &lt;Metrics /&gt; : null<br>}</pre><p>No useState, no useEffect, no lag between &quot;the inputs are ready&quot; and &quot;the decision reflects them&quot; — because there&#39;s no lag to begin with. Identical behavior on server and client.</p><h3>4.3 Moving Data Server-Side Isn’t the Whole Fix</h3><p>Worth stating plainly, because it’s easy to assume the opposite: <strong>fetching data server-side and rendering it correctly are two separate problems</strong>, and fixing one doesn’t fix the other. We’d hit 4.2’s bug independently of the data-fetching work — a component whose <em>decision to render</em> was broken regardless of whether its data was ready. If we’d only moved the fetch server-side and stopped there, we’d have shipped correctly-fetched data into a section that still, silently, never appeared — and likely concluded the fetch itself was still broken. Verify both halves separately.</p><h3>Summary Checklist</h3><ul><li><strong>Plain </strong><strong>React.lazy()/dynamic </strong><strong>import() doesn&#39;t work for SSR on React 16/17.</strong> It fails silently — the server renders your Suspense fallback, not your content, no error thrown. @loadable/component&#39;s manifest + synchronous require() approach is the standard legacy-compatible fix; React 18+&#39;s streaming SSR solves this natively if you&#39;re not constrained to an older version.</li><li><strong>A route-scoped rollout still executes shared code paths.</strong> Audit every template and default value the <em>unscoped</em> case relies on — a half-migrated feature will break the routes it wasn’t meant to touch yet.</li><li><strong>Correct markup with missing styles, in an SSR context, is a different bug than a CSS problem.</strong> Check whether the stylesheet was requested by the browser at all before touching a single class name — an unscoped splitChunks rule sweeping CSS into an orphaned shared chunk is a very normal way for this to happen.</li><li><strong>A </strong><strong>useEffect deciding whether something renders means it will never render correctly on the server.</strong> No error, no warning — it silently always takes the initial-state branch. Compute the decision as a plain function during render instead.</li><li><strong>Fixing a data fetch and fixing a component’s decision to render are two different bugs.</strong> Verify both independently.</li></ul><p>None of this required abandoning React 16. It required going and checking — with the raw network response, with JavaScript disabled, with the embedded server state — instead of trusting a page that loaded fine and looked right.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=533581ee4afa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering JavaScript Proxy & Reflect: The Doorman Pattern for Safer, Smarter Objects]]></title>
            <link>https://medium.com/@nikhilkumarmodi/mastering-javascript-proxy-reflect-the-doorman-pattern-for-safer-smarter-objects-425bb1de12a3?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/425bb1de12a3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[input-validation]]></category>
            <category><![CDATA[js-interview-questions]]></category>
            <category><![CDATA[proxy-reflect]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 18:43:55 GMT</pubDate>
            <atom:updated>2025-08-04T18:43:55.389Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yG8D4aYRPQd4QA638aOcOA.png" /></figure><blockquote><em>Ever wished JavaScript objects came with built-in </em><strong><em>guards</em></strong><em>, </em><strong><em>rules</em></strong><em>, and </em><strong><em>access control</em></strong><em>? Meet your new favorite duo: </em><strong><em>Proxy</em></strong><em> and </em><strong><em>Reflect</em></strong><em>.</em></blockquote><p>In this article, you’ll learn:</p><p>✅ A simple <strong>real-world analogy</strong> to make Proxy + Reflect unforgettable<br> ✅ How to <strong>validate</strong> and <strong>control access</strong> to object properties<br> ✅ Real-world <strong>use cases</strong> (including a day-to-day practical example)<br> ✅ Beginner-friendly <strong>code walkthroughs</strong></p><h3>🧠 Real-World Analogy: The “Doorman Pattern”</h3><p>Imagine your JavaScript object is a <strong>private building</strong> — say your house.</p><p>Now ask yourself:</p><blockquote><em>Would you let just anyone walk in and </em><strong><em>rearrange your furniture</em></strong><em>, </em><strong><em>add random rooms</em></strong><em>, or </em><strong><em>store garbage in the kitchen</em></strong><em>?</em></blockquote><p>Of course not. That’s why we hire a <strong>doorman</strong>.</p><p>This is exactly what a <strong>Proxy</strong> does:</p><p>🕵️‍♂️ It intercepts every attempt to get or set a property<br> 🚨 It applies <strong>custom rules</strong> before allowing any operation<br> 🛡️ It protects the original object from bad or unexpected behavior</p><h3>💡 JavaScript Proxy: Your Custom Gatekeeper</h3><pre>const proxy = new Proxy(target, handler)</pre><p>Where:</p><ul><li>target is the original object</li><li>handler is an object with <strong>intercepting functions</strong> like get, set, has, etc.</li></ul><h3>🔍 Basic Example: Guarding an Object</h3><p>Let’s guard a simple user object:</p><pre>const user = { name: &#39;Nikhil&#39;, age: 29}<br><br>const handler = {<br>  get(target, prop) {<br>    if (prop in target) return Reflect.get(target, prop)<br>    console.warn(`${prop} does not exist`)<br>    return false<br>  },<br>  set(target, prop, value) {<br>    if (!(prop in target)) {<br>      throw new Error(`Can&#39;t add new property: ${prop}`)<br>    }<br>    if (prop === &#39;age&#39; &amp;&amp; (typeof value !== &#39;number&#39; || value &lt;= 0)) {<br>      throw new Error(`Invalid age: ${value}`)<br>    }<br>    return Reflect.set(target, prop, value)<br>  }<br>}<br>const guardedUser = new Proxy(user, handler)</pre><h3>🧪 Usage:</h3><pre>guardedUser.age = 25          // ✅ Works<br>guardedUser.age = -5          // ❌ Error<br>guardedUser.status = &#39;admin&#39;  // ❌ Error<br>console.log(guardedUser.name) // ✅ Nikhil<br>console.log(guardedUser.role) // ⚠️ Warns &amp; returns false</pre><h3>🤔 What’s Reflect and Why Should You Use It?</h3><p>If Proxy is the <strong>Doorman</strong>, then Reflect is the <strong>Rulebook</strong>.</p><p>You could write:</p><pre>target[prop] = value</pre><p>But using:</p><pre>Reflect.set(target, prop, value)</pre><p>…ensures that your set/get follows <strong>native JavaScript behavior</strong>, including return values and error handling.</p><p>📘 <strong>Why it matters:</strong> Reflect methods reduce edge cases, especially when dealing with prototype chains, classes, or deep proxies.</p><h3>👨‍🔧 Day-to-Day Example: Validated User Profiles</h3><p>Imagine you’re building a front-end form, and you want to:</p><ol><li>Prevent random fields being added</li><li>Ensure fName and lName are strings</li><li>Validate age as a number &gt; 0</li></ol><p>Here’s how a Proxy can help:</p><pre>const userProfile = {<br>  fName: &quot;Alice&quot;,<br>  lName: &quot;Smith&quot;,<br>  age: 30<br>}<br><br>const userProfileHandler = {<br>  get(target, property) {<br>    if (!(property in target)) {<br>      console.warn(`Property &#39;${property}&#39; does not exist`)<br>      return false<br>    }<br>    return Reflect.get(target, property)<br>  },<br>  set(target, property, value) {<br>    if (!(property in target)) {<br>      throw new Error(`❌ Property &#39;${property}&#39; cannot be added`)<br>    }<br>    switch (property) {<br>      case &#39;fName&#39;:<br>      case &#39;lName&#39;:<br>        if (typeof value !== &#39;string&#39;) {<br>          throw new Error(`${property} must be a string`)<br>        }<br>        break<br>      case &#39;age&#39;:<br>        if (typeof value !== &#39;number&#39; || value &lt;= 0) {<br>          throw new Error(`Age must be a number &gt; 0`)<br>        }<br>        break<br>    }<br>    return Reflect.set(target, property, value)<br>  }<br>}<br>const validatedUser = new Proxy(userProfile, userProfileHandler)</pre><h3>🧪 Usage:</h3><pre>validatedUser.fName = &quot;Bob&quot;         // ✅ Works<br>validatedUser.age = 25              // ✅ Works<br>validatedUser.status = &quot;active&quot;     // ❌ Error: Cannot add property<br>validatedUser.age = -1              // ❌ Error: Invalid age<br>console.log(validatedUser.x)        // ⚠️ Warning: Property does not exist</pre><h3>🧠 Key Takeaways</h3><p>Concept What It Does 🔒 Proxy Intercepts object interactions like get, set, delete, has, etc. 📘 Reflect Performs default low-level operations the &quot;safe way&quot; 🧼 Clean Code Keeps data separate from validation/business logic 🛡️ Safer Apps Blocks invalid, malicious, or unexpected changes</p><h3>✅ When Should You Use Proxy &amp; Reflect?</h3><p><strong>Great for:</strong></p><ul><li>🧪 Input validation</li><li>🧠 Smart defaults or lazy evaluation</li><li>📊 Logging and analytics</li><li>🔐 Permission enforcement</li><li>🌀 Reactive programming (Vue 3 uses Proxy under the hood!)</li></ul><h3>📌 Final Thought: Powerful, Predictable, Protected</h3><p>Using Proxy + Reflect gives you <em>fine-grained control</em> over how your data behaves.</p><p>They’re not just for framework authors — they’re tools <strong>you</strong> can use right now to:</p><ul><li>Prevent bugs</li><li>Add guardrails</li><li>Write cleaner, more predictable code</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=425bb1de12a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding the Browser Rendering Pipeline: Code to Pixels]]></title>
            <link>https://medium.com/@nikhilkumarmodi/understanding-the-browser-rendering-pipeline-from-code-to-pixels-a067c1aae40f?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/a067c1aae40f</guid>
            <category><![CDATA[reflow]]></category>
            <category><![CDATA[render-tree]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[layout]]></category>
            <category><![CDATA[composite]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 15:30:19 GMT</pubDate>
            <atom:updated>2025-07-16T15:31:34.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3BgflJLLrKABZ5BCXnegw.png" /></figure><p>When you type a 🌐 URL in your 🧭 browser and press ⏎ Enter, a complex sequence of ⚙️ events is triggered under the hood. This process converts raw 📝 HTML, 🎨 CSS, and 📜 JavaScript into the 👀 visual interface you see on your screen. For 🧑‍💻 frontend engineers and 🧑‍💼 system analysts alike, understanding the <strong>browser rendering pipeline</strong> is crucial to optimizing ⚡ performance, debugging 🧩 layout issues, and mastering the 🕸️ web platform.</p><p>Let’s break down the rendering process into 🔑 six key stages:</p><h3>1. Parse 📝 HTML → 🌲 DOM (Document Object Model)</h3><p>The 🧭 browser starts by parsing the 📝 HTML document. As it encounters elements (&lt;html&gt;, &lt;head&gt;, &lt;body&gt;, etc.), it builds a <strong>DOM tree</strong> 🌳—a hierarchical representation of the structure of the web page.</p><ul><li>Every 🏷️ tag becomes a node in the tree.</li><li>If a &lt;script&gt; tag with src is encountered, parsing is paused until that script is downloaded and executed (unless defer or async is used).</li><li>💬 Comments, space ⬜, and malformed tags are handled as per the HTML5 spec.</li></ul><p><strong>The DOM</strong> is a live, interactive structure — 📜 JavaScript can read 🔍 or modify ✍️ it at any point.</p><h3>2. Parse 🎨 CSS → 📐 CSSOM (CSS Object Model)</h3><p>In parallel, the browser parses all 🎨 CSS it encounters:</p><ul><li>External stylesheets (&lt;link&gt; 🔗 tags)</li><li>Internal styles (&lt;style&gt; 🎨 blocks)</li><li>Inline styles (inside HTML 🏷️ tags)</li></ul><p>This is compiled into another object model — the <strong>CSSOM</strong>.</p><ul><li>CSSOM contains computed styles for selectors.</li><li>It transforms rules like body { font-size: 14px } into a structured format the browser understands.</li><li>Inlined styles, default user agent styles, and inherited properties are all considered here.</li></ul><p>The browser must build the CSSOM before rendering anything visually because style directly affects 📏 layout.</p><h3>3. Merge 🌲 DOM + 📐 CSSOM → 🖼️ Render Tree</h3><p>Next, the browser combines the DOM and CSSOM to create a <strong>Render Tree</strong> 🖼️.</p><p>The Render Tree contains only <strong>visible elements</strong> with <strong>calculated styles</strong>.</p><p>For example:</p><ul><li>Elements with display: none are excluded from the Render Tree.</li><li>But elements with visibility: hidden <em>are</em> included (since they occupy space).</li></ul><p>Each render tree node is called a <strong>Render Object</strong>, and it holds:</p><ul><li>The content to be displayed</li><li>Computed layout styles (font-size, color, etc.)</li></ul><blockquote>✅ Key Point: The Render Tree is what the browser uses to calculate <strong>layout and paint</strong> — not the raw DOM or CSS.</blockquote><h3>4. 📐 Layout (Reflow)</h3><p>The layout step calculates the <strong>exact position 📍 and size 📏</strong> of each render object on the screen 🖥️.</p><p>Key considerations:</p><ul><li>The <strong>CSS box model</strong> 📦 (margin ↔️, border 🔲, padding 🔳, content 📑)</li><li>📄 Text flow, wrapping, and line-breaking ➿ rules</li><li>Layout modes: block ⬛, inline ⬜, flex 🤸, grid 🧱, etc.</li><li>Viewport 🪟 size and scroll positions 🧭</li></ul><p>Text nodes are broken into <strong>line boxes</strong>. The layout engine (like Blink or Gecko) performs these calculations recursively from the root to the leaves of the tree.</p><blockquote><em>⚠️ Layout is expensive! Even small changes (e.g., adjusting width or font-size) can trigger reflows of large portions of the tree.</em></blockquote><h3>5. 🎨 Paint</h3><p>Once layout is done, the browser <strong>paints 🖌️</strong> each visual element:</p><ul><li>Drawing 🖍️ background colors, borders, text, images 🖼️, shadows 🌫️, etc.</li><li>Each render object becomes a painted set of 📸 pixels</li><li>This is done layer-by-layer 📚</li></ul><p>This work is handled by the browser’s <strong>painting engine</strong>, often leveraging a graphics library like <strong>Skia</strong> 🎨 (used in Chrome).</p><p>Painting can be parallelized and done incrementally, but it’s still costly for pages with a lot of effects.</p><p>Paint can be optimized via techniques like layer promotion 📤 and invalidation regions ❌.</p><h3>6. 🧩 Composite</h3><p>Finally, all painted layers are <strong>composited 🧩</strong> into a single bitmap 🖼️ that can be shown on screen 💻.</p><ul><li>Managed by the <strong>compositor thread 🧵</strong></li><li>Often GPU-accelerated 💨 for smooth performance</li><li>Handles z-index 📊, transforms 🔄, fixed-position 📌 elements, and more</li></ul><p>Only the changed portions of the screen (called <strong>dirty rectangles 🟫</strong>) are redrawn, improving efficiency.</p><blockquote><em>✅ Composite is the final step before pixels appear on your screen.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuBU3tASzzi7O78dESHaIg.png" /></figure><p>Understanding the browser rendering pipeline isn’t just academic 🎓 — it’s essential for optimizing ⚡ performance, writing clean layouts 🧼, and creating responsive 📱, accessible ♿ UIs. Whether you’re debugging 🪲 layout shifts or building high-performance animations 🎞️, these six steps are your foundation 🏗️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a067c1aae40f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding JavaScript’s delete Operator and Prototype Inheritance — Explained Visually]]></title>
            <link>https://medium.com/@nikhilkumarmodi/understanding-javascripts-delete-operator-and-prototype-inheritance-explained-visually-de98da04fe98?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/de98da04fe98</guid>
            <category><![CDATA[object-create]]></category>
            <category><![CDATA[hasownproperty]]></category>
            <category><![CDATA[delete-object]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[prototype-in-javascript]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Thu, 15 May 2025 19:12:50 GMT</pubDate>
            <atom:updated>2025-05-15T19:12:50.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔍 Understanding JavaScript’s delete Operator and Prototype Inheritance — Explained Visually</h3><p><em>Why doesn’t </em><em>delete work the way you think when using prototype inheritance? Let’s break it down with a </em><strong><em>unique example</em></strong><em>, easy-to-grasp analogies, and deeper insights for curious learners.</em></p><h3>🧠 What’s Going On Here?</h3><pre>const device = Object.create({ batteryLevel: 85 });<br>console.log(device.batteryLevel); // 85<br>delete device.batteryLevel;<br>console.log(device.batteryLevel); // 85 again!</pre><p>Wait… what? We called delete, but batteryLevel is still there?</p><h3>🛠️ Breaking It Down</h3><h3>Step 1: Object Creation via Prototype</h3><pre>const device = Object.create({ batteryLevel: 85 });</pre><ul><li>Object.create() creates a new object.</li><li>The argument ({ batteryLevel: 85 }) becomes the <strong>prototype</strong> of the new object.</li><li>So now, device is empty <strong>but inherits</strong> batteryLevel from its prototype.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*0hgGFIekmbTSi2j8bcjqEA.png" /></figure><h3>Step 2: Property Access via Inheritance</h3><pre>console.log(device.batteryLevel); // 85</pre><p>Here’s what happens:</p><ol><li>JavaScript checks if device has its own batteryLevel.</li><li>It doesn’t.</li><li>So JS looks into the prototype.</li><li>Found! → Returns 85.</li></ol><p>🧠 This is called <strong>Prototype Chain Lookup</strong>.</p><h3>Step 3: Using delete</h3><pre>delete device.batteryLevel;</pre><ul><li>delete only removes <strong>own properties</strong>.</li><li>batteryLevel lives on the <strong>prototype</strong>, not on device itself.</li><li>So nothing is deleted.</li></ul><pre>console.log(device.batteryLevel); // Still 85</pre><h3>🧪 Let’s Add Shadowing to the Mix</h3><pre>device.batteryLevel = 50;<br>console.log(device.batteryLevel); // 50 (own property)</pre><p>Now we’ve added a property with the <strong>same name</strong>. This is called <strong>shadowing</strong>.</p><pre>delete device.batteryLevel;<br>console.log(device.batteryLevel); // 85 (back to prototype)</pre><p>Deleting the <strong>own property</strong> reveals the one from the prototype again.</p><h3>🧠 Key Takeaways</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-MkcqheNOzAA-00CAFkfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*Qc0COR_n7LFT5mCfEifwAA.png" /></figure><h3>🧩 Deep Dive: Checking Property Existence</h3><h3>1. hasOwnProperty()</h3><p>Checks only own properties:</p><pre>console.log(device.hasOwnProperty(&#39;batteryLevel&#39;)); // false<br>device.batteryLevel = 50;<br>console.log(device.hasOwnProperty(&#39;batteryLevel&#39;)); // true</pre><h3>2. in Operator</h3><p>Checks both own and inherited properties:</p><pre>console.log(&#39;batteryLevel&#39; in device); // true</pre><h3>🧱 Modifying the Prototype Affects All Children</h3><pre>const proto = { batteryLevel: 85 };<br>const device1 = Object.create(proto);<br>const device2 = Object.create(proto);<br>proto.batteryLevel = 100;<br>console.log(device1.batteryLevel); // 100<br>console.log(device2.batteryLevel); // 100</pre><p>All children reflect the change — because they point to the same prototype.</p><h3>❌ Deleting from the Prototype</h3><pre>delete proto.batteryLevel;<br>console.log(device1.batteryLevel); // undefined<br>console.log(device2.batteryLevel); // undefined</pre><p>Prototype properties are shared — deleting from the prototype affects everyone.</p><h3>⚙️ Related Advanced Tips</h3><h3>🔄 Object.getPrototypeOf and Object.setPrototypeOf</h3><pre>Object.getPrototypeOf(device); // gets the prototype object<br>Object.setPrototypeOf(device, {}); // changes the prototype</pre><p>⚠️ Avoid frequent setPrototypeOf calls — it affects performance!</p><h3><strong>Use Cases for Prototype Inheritance:</strong></h3><ul><li><strong>Code Reusability:</strong> Sharing common properties and methods among multiple objects. This is the foundation of classical inheritance patterns in JavaScript (though modern JavaScript often favors composition).</li></ul><h3>🧱 Constructor Function &amp; Class Inheritance</h3><pre>function Phone() {<br>  this.brand = &quot;Pixel&quot;;<br>}<br>Phone.prototype.batteryLevel = 90;<br>const myPhone = new Phone();<br>console.log(myPhone.batteryLevel); // 90</pre><p>Or using ES6 class syntax:</p><pre>class Phone {<br>  constructor(brand) {<br>    this.brand = brand;<br>  }<br>  getBatteryStatus() {<br>    return `${this.brand} has 90% battery`;<br>  }<br>}</pre><h3>🔚 In Summary</h3><p>✅ Prototype inheritance allows objects to “borrow” properties from other objects.<br> ✅ delete works only on an object’s <strong>own</strong> properties.<br> ✅ If the property is inherited, delete doesn’t remove it.<br> ✅ Use shadowing to override inherited properties — then delete to expose originals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de98da04fe98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Decoding Nginx: Your Friendly Guide to the Web’s Unsung Hero ]]></title>
            <link>https://medium.com/@nikhilkumarmodi/decoding-nginx-your-friendly-guide-to-the-webs-unsung-hero-ac08143884cb?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac08143884cb</guid>
            <category><![CDATA[nginx-worker-connections]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[nginx-reverse-proxy]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[epoll]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Tue, 13 May 2025 18:02:11 GMT</pubDate>
            <atom:updated>2025-05-13T18:02:11.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Web Servers: The Old Way vs. The Nginx Way" src="https://cdn-images-1.medium.com/max/1024/1*L217PqoVsmuh8_vR1KAJmQ.jpeg" /></figure><p>Ever wondered how websites like Netflix 🎬 stream movies to millions simultaneously, or how your favorite online store 🛍️ handles a Black Friday rush without crashing 💥? Chances are, a silent, powerful workhorse named <strong>Nginx</strong> (pronounced “engine-ex”) is playing a crucial role behind the scenes.</p><p>You might not see it, but Nginx is one of the most popular pieces of software powering the internet today 🌐. In this article, we’ll demystify Nginx, explore why it’s so important, peek into how it works its magic ✨, and even touch on a few areas where it might not be the perfect fit.</p><h3>🐌 The Old Way: Why We Needed Something Better</h3><p>Imagine a busy restaurant 🍽️. In the old days of web servers, it was a bit like assigning one waiter to <em>every single customer</em> who walked in.</p><ul><li><strong>One Customer, One Waiter (Thread-per-Request):</strong> For every new visitor (request) to a website, the server would create a new dedicated helper (a “thread” or “process” 🚶‍♂️) just for that visitor.</li><li><strong>Okay for a Few, Chaos 🤯 for Many:</strong> This works fine if you only have a handful of customers. But what happens when hundreds, or thousands, arrive at once?</li><li><strong>Too Many Waiters:</strong> The restaurant (server) quickly runs out of space and resources (memory 💾, CPU 💻).</li><li><strong>Waiters Bumping Into Each Other:</strong> The manager (Operating System) spends a lot of time just trying to coordinate all these waiters (context switching 🔄), rather than them actually serving food.</li><li><strong>Slow Service &amp; Kitchen Overload:</strong> Eventually, service grinds to a halt 😩, and the restaurant might even have to close its doors (server crash 💥).</li></ul><p>This “thread-per-request” model, while straightforward, struggles with the massive scale of the modern internet.</p><h3>✨ Enter Nginx: The Super-Efficient Restaurant Manager</h3><p>Nginx took a radically different approach, more like a highly organized restaurant with a few, incredibly efficient, multi-tasking waiters managed by a smart floor manager 👨‍💼.</p><p><strong>What Exactly IS Nginx? 🤔</strong></p><p>At its core, Nginx is a high-performance web server. But its versatility is what makes it so popular. It can wear many hats 🎩:</p><ol><li><strong>🌐 Web Server:</strong> It can directly serve static content like HTML files, CSS, JavaScript, and images to your browser, and it does this incredibly fast.</li><li><strong>🛡️ Reverse Proxy:</strong> Imagine a single, public-facing receptionist for a large office building. All visitors go to the receptionist (Nginx), who then directs them to the correct department (your actual application servers). This hides the complexity of your backend and adds a layer of security.</li><li><strong>⚖️ Load Balancer:</strong> If your website gets a lot of traffic, you might have multiple application servers. Nginx can act like a traffic cop, distributing incoming requests evenly across these servers, preventing any single server from getting overwhelmed.</li><li><strong>💾 HTTP Cache:</strong> Nginx can store frequently accessed content in a temporary storage (cache). When a user requests this content again, Nginx can serve it directly from the cache, which is much faster than fetching it from the application server every time.</li></ol><h3>⚙️ The Magic: How Nginx Handles So Much Traffic</h3><p>Nginx’s secret sauce lies in its <strong>event-driven, non-blocking architecture.</strong> Let’s break that down:</p><ol><li><strong>The Master 👑 and the Workers 👷‍♀️👷‍♂️:</strong></li></ol><ul><li>When Nginx starts, a <strong>Master Process</strong> (the smart floor manager) comes to life. Its job is to read configuration files, manage permissions, and, most importantly, spawn a few highly efficient <strong>Worker Processes</strong> (the multi-tasking waiters).</li><li>Typically, Nginx creates <strong>one worker process per CPU core</strong> on your server. This is key for maximizing performance.</li><li>The Master process doesn’t handle your web requests directly; the Workers do.</li></ul><p><strong>2. Inside a Worker: Event-Driven 🔔 &amp; Non-Blocking 🚫:</strong></p><ul><li><strong>Not One Waiter Per Customer:</strong> Unlike the old model, a single Nginx worker process can handle <em>thousands</em> of client connections simultaneously.</li><li><strong>Listening for Events:</strong> Each worker listens for “events.” An event could be a new visitor arriving, a visitor sending their order (a request), or the kitchen (another part of the system, like a disk or another server) signaling that an order is ready.</li><li><strong>Sockets (The Communication Pipes):</strong></li></ul><blockquote><strong>Listen Socket:</strong> This is like the main entrance where new visitors (incoming requests) queue up.</blockquote><blockquote><strong>Connection Socket:</strong> Once a worker accepts a visitor, a dedicated pipe (connection socket) is set up for communication with that specific visitor.</blockquote><ul><li><strong>The Event Loop 🔄 (The Worker’s Brain 🧠):</strong> This is the core of the worker. It constantly checks for events on all its active connections.</li><li><strong>Non-Blocking Action:</strong> Here’s the crucial part. If a worker needs to do something that might take time (like fetching a large file from the disk 💿, or waiting for a response from another server it’s proxying to), it <em>doesn’t just stand there and wait</em>.</li><li>It tells the operating system, “Hey, let me know when this task is done.”</li><li>Then, it immediately moves on to serve another visitor whose request is ready to be processed.</li><li>When the time-consuming task is complete, the OS notifies the worker through an event, and the worker picks up where it left off for that original visitor.</li><li><strong>Efficient OS Tools (epoll/kqueue) 🛠️:</strong> Nginx uses super-efficient tools provided by the operating system (like epoll on Linux or kqueue on macOS/BSD). These tools allow a worker to monitor thousands of connections simultaneously with very little effort, telling it exactly which connections need attention without the worker having to ask each one individually.</li></ul><p>Think of it like a chess grandmaster ♟️ playing multiple opponents at once. They make a move on one board, and while that opponent thinks, they move to the next board, and so on. They’re always active, never idly waiting for one opponent.</p><h3>✅ Why is Nginx Such a Big Deal? The Benefits:</h3><p>This architecture brings massive advantages:</p><ul><li><strong>⚡ Blazing Speed:</strong> By not blocking and efficiently managing connections, Nginx responds to requests very quickly.</li><li><strong>📈 Incredible Scalability:</strong> It can handle a huge number of concurrent connections (tens of thousands, even hundreds of thousands per worker) without breaking a sweat.</li><li><strong>💰 Resource Efficiency:</strong> It uses significantly less memory and CPU compared to traditional thread-per-request servers for the same amount of traffic. This means you can serve more users with less hardware.</li><li><strong>💪 High Reliability:</strong> Its architecture is robust, and the separation of master and worker processes means configuration can often be reloaded without dropping active connections.</li><li><strong>🔧 Versatility:</strong> As mentioned, it’s not just a web server. Its roles as a reverse proxy, load balancer, and cache make it an indispensable tool in modern web stacks.</li></ul><h3>🤔 Is Nginx Perfect? Challenges and Limitations</h3><p>While Nginx is fantastic, it’s not a silver bullet for every problem:</p><ol><li><strong>🧩 Configuration Complexity (Sometimes):</strong></li></ol><ul><li>Basic Nginx configuration is relatively straightforward. However, for very complex setups with intricate routing rules, custom logic (using Lua, for instance), or advanced module configurations, the learning curve can be steep. The configuration files can become quite intricate.</li></ul><p><strong>2. 🚫 Not Ideal for Purely Application Logic (Usually):</strong></p><ul><li>Nginx excels at I/O-bound tasks (network requests, file serving). It’s not typically used to run heavy, CPU-bound application logic itself (like complex calculations 🧮 or business logic that your main application would handle).</li><li>Nginx is designed to <em>front</em> these application servers (written in Python, Ruby, Java, Node.js, etc.), handling the web traffic efficiently and passing requests to the application servers when needed.</li></ul><p><strong>3. 🕵️‍♂️ Debugging Can Be Tricker:</strong></p><ul><li>Because of its event-driven nature and multiple processes, pinpointing issues in a complex Nginx setup can sometimes be more challenging than debugging a simpler, single-process application.</li></ul><p><strong>4. 🚧 Resource Limits Still Exist:</strong></p><ul><li>While Nginx can handle a lot, it’s not magic. It still operates within the limits of the server’s RAM, CPU, and network bandwidth. Misconfiguration or extreme, unoptimized loads can still cause problems.</li></ul><p><strong>5. 📜 Limited Dynamic Content Processing Natively:</strong></p><ul><li>While Nginx can use modules like Lua for some dynamic behavior, it’s not a full-fledged application server environment like those built with PHP, Python (Django/Flask), or Node.js. It relies on proxying to these backends for rich dynamic content generation.</li></ul><h3>👍 The Takeaway</h3><p>Nginx’s event-driven, non-blocking architecture revolutionized how web servers handle traffic. Its ability to manage thousands of connections with minimal resources makes it a cornerstone of the modern, high-traffic internet.</p><p>While it has its complexities, especially for advanced use cases, its benefits in performance, scalability, and efficiency are undeniable. So, the next time you seamlessly stream a video or shop online during a sale, take a moment to appreciate the silent, powerful engine — Nginx — working hard to make your web experience smooth and fast!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac08143884cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Bare Metal to Kubernetes: A Beginner’s Journey into Modern Infrastructure]]></title>
            <link>https://medium.com/@nikhilkumarmodi/from-bare-metal-to-kubernetes-a-beginners-journey-into-modern-infrastructure-3533237a1df4?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/3533237a1df4</guid>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Mon, 12 May 2025 19:31:48 GMT</pubDate>
            <atom:updated>2025-05-12T19:31:48.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>🌱 The Evolution: From Self-Hosting to Kubernetes</h3><h3>🏠 1. The Era of Self-Hosting</h3><p>In the early days, organizations managed their own physical servers. Each application ran on a dedicated machine, leading to:</p><ul><li><strong>Underutilization</strong>: Resources were often wasted as servers operated below capacity.</li><li><strong>Scalability Issues</strong>: Scaling required purchasing and setting up new hardware.</li><li><strong>Maintenance Overhead</strong>: Hardware failures and updates demanded significant manual intervention.</li></ul><h3>☁️ 2. The Advent of Cloud Computing (AWS, Azure, GCP)</h3><p>Cloud providers introduced virtual machines (VMs), allowing multiple virtual servers on a single physical machine. Benefits included:</p><ul><li><strong>On-Demand Resources</strong>: Quick provisioning and de-provisioning of servers.</li><li><strong>Cost Efficiency</strong>: Pay-as-you-go models reduced capital expenditure.</li></ul><p><em>However</em>, managing VMs still required configuring environments, leading to inconsistencies and deployment challenges.</p><h3>🐳 3. Containerization with Docker</h3><p>Docker revolutionized application deployment by packaging applications with their dependencies into containers. Advantages:</p><ul><li><strong>Consistency</strong>: “It works on my machine” became a thing of the past.</li><li><strong>Lightweight</strong>: Containers shared the host OS kernel, reducing overhead.</li><li><strong>Rapid Deployment</strong>: Containers could be started and stopped quickly.</li></ul><p><em>Yet</em>, managing numerous containers across multiple environments became complex.</p><h3>⚙️ 4. Orchestrating Containers: Enter Kubernetes</h3><p>Developed by Google and released as open-source in 2014, Kubernetes (K8s) addressed the challenges of container management by providing:</p><ul><li><strong>Automated Deployment</strong>: Declarative configurations for deploying applications.</li><li><strong>Scaling</strong>: Automatic scaling based on demand.</li><li><strong>Self-Healing</strong>: Automatic restarts and replacements of failed containers.</li><li><strong>Load Balancing</strong>: Distributing traffic across containers.</li></ul><h3>🧱 2. Kubernetes Architecture (High-Level)</h3><pre>+-----------------------+<br>|    User (kubectl)     |<br>+----------+------------+<br>           |<br>           v<br>+----------+-------------------------------+<br>|         Control Plane (Master)           |<br>|                                          |<br>|  +-------------+   +------------------+  |<br>|  |  API Server |&lt;-&gt;| etcd (Cluster DB)|  |<br>|  +-------------+   +------------------+  |<br>|         |                                 |<br>|  +-------------+   +------------------+  |<br>|  | Controller  |   | Scheduler        |  |<br>|  +-------------+   +------------------+  |<br>+------------------------------------------++------------------------------------------+<br>|         Worker Nodes                     |<br>|                                          |<br>| +-------------+   +------------------+   |<br>| | Kubelet     |   | Kube Proxy       |   |<br>| +-------------+   +------------------+   |<br>|        |        (Manages networking)     |<br>|   +----------+                           |<br>|   |  Pods    |  → Containers             |<br>|   +----------+                           |<br>+------------------------------------------+</pre><h3>🧠 Control Plane Components</h3><ul><li><strong>API Server</strong>: The front-end of the Kubernetes control plane, handling REST operations.</li><li><strong>etcd</strong>: A consistent and highly-available key-value store for all cluster data.</li><li><strong>Scheduler</strong>: Assigns workloads to nodes based on resource availability.</li><li><strong>Controller Manager</strong>: Ensures the desired state of the cluster matches the actual state.</li></ul><h3>🖥️ Node Components</h3><ul><li><strong>Kubelet</strong>: An agent that ensures containers are running in a Pod.</li><li><strong>Kube Proxy</strong>: Maintains network rules on nodes, allowing communication to Pods.</li><li><strong>Container Runtime</strong>: Software responsible for running containers (e.g., Docker, containerd).<a href="https://spacelift.io/blog/container-orchestration-tools?utm_source=chatgpt.com">Spacelift+1Discuss the Elastic Stack+1</a></li></ul><h3>🚀 Core Functionalities of Kubernetes</h3><ul><li><strong>Pods</strong>: The smallest deployable units, encapsulating containers.</li><li><strong>Services</strong>: Abstracts access to Pods, enabling load balancing.</li><li><strong>Deployments</strong>: Manages the deployment and scaling of Pods.</li><li><strong>ConfigMaps &amp; Secrets</strong>: Manage configuration data and sensitive information.</li><li><strong>Namespaces</strong>: Provides isolation within the cluster.</li><li><strong>Ingress</strong>: Manages external access to services within the cluster.<a href="https://www.cloudzero.com/blog/kubernetes-alternatives/?utm_source=chatgpt.com">CloudZero</a></li></ul><h3>🔄 Alternatives to Kubernetes</h3><p>While Kubernetes is the dominant orchestration tool, alternatives exist:</p><ul><li><strong>Docker Swarm</strong>: Simpler setup, integrated with Docker CLI.</li><li><strong>HashiCorp Nomad</strong>: Lightweight and flexible, supports multiple workloads.</li><li><strong>Apache Mesos</strong>: Designed for large-scale deployments, though less popular now.</li><li><strong>OpenShift</strong>: Red Hat’s enterprise Kubernetes platform with additional features.</li><li><strong>Rancher</strong>: Simplifies Kubernetes cluster management.</li></ul><p>Managed services like AWS Fargate, Google Cloud Run, and Azure Container Instances offer serverless container deployment options.</p><h3>⚠️ Challenges and Limitations of Kubernetes</h3><p>Despite its strengths, Kubernetes has its challenges:</p><ul><li><strong>Complexity</strong>: Steep learning curve for newcomers.</li><li><strong>Resource Intensive</strong>: Requires significant computational resources.</li><li><strong>Security Concerns</strong>: Misconfigurations can lead to vulnerabilities.</li><li><strong>Networking Issues</strong>: Troubleshooting network problems can be intricate.</li><li><strong>Monitoring and Logging</strong>: Requires integration with external tools for comprehensive observability.</li></ul><h3>🎯 Conclusion</h3><p>Kubernetes has transformed the way applications are deployed and managed, offering scalability, resilience, and flexibility. However, it’s essential to assess your organization’s needs and resources before adopting it. For smaller teams or simpler applications, alternatives might be more appropriate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3533237a1df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️‍♂️ The Case of The Missing Index: The Secret Life of Sparse Arrays in JavaScript]]></title>
            <link>https://medium.com/@nikhilkumarmodi/%EF%B8%8F-%EF%B8%8F-the-case-of-the-missing-index-the-secret-life-of-sparse-arrays-in-javascript-71a83c2f76db?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a83c2f76db</guid>
            <category><![CDATA[sparse-array]]></category>
            <category><![CDATA[advanced-javascript]]></category>
            <category><![CDATA[javascript-arrays]]></category>
            <category><![CDATA[javascript-reduce]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 19:58:27 GMT</pubDate>
            <atom:updated>2025-07-27T08:45:34.021Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Sparse Arrays: Where Missing Indices Hide in Plain Sight" src="https://cdn-images-1.medium.com/max/1024/1*VT0YL1Xb_KC1K1_4nCA5IA.jpeg" /></figure><h3>🧩 A Puzzle Hidden in Plain Sight</h3><p>JavaScript arrays — we all use them. They’re just ordered lists, right? You push values in, pop values out, loop through them, and life goes on.</p><p>But what if I told you that <strong>some arrays are hiding secrets</strong>?</p><p>There are arrays you can <strong>see</strong> but not <strong>touch</strong>. Arrays that appear to have undefined values but actually have... <strong>nothing at all</strong>.</p><p>Welcome to the world of <strong>sparse arrays</strong>, and the mysterious i in this.</p><h3>🕳️ What is a Sparse Array?</h3><p>A <strong>sparse array</strong> is a JavaScript array with <strong>missing indices</strong> — they have <strong>holes</strong>, not undefined, but literal missing spots in the index sequence.</p><pre>const arr = [1, , 3]; // 👀 a hole at index 1</pre><p>At a glance, arr[1] looks like undefined. But it’s not the same as:</p><pre>const arr = [1, undefined, 3]; // 🧪 no hole, just a value `undefined`</pre><p><strong>The difference is crucial</strong>, and it’s one of JavaScript’s best-kept secrets.</p><h3>🕵️‍♀️ Detecting the Invisible</h3><p>This is where our hero, <strong>i in this</strong>, comes into play.</p><p>When iterating through an array, how do you know if a particular index exists or if it’s just a hole?</p><pre>const arr = [1, , 0, undefined];<br>console.log(0 in arr);  // true - index 0 exists<br>console.log(1 in arr);  // false - index 1 is a hole<br>console.log(2 in arr);  // true - index 2 exists<br>console.log(3 in arr);  // true - index 2 exists</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*8VDMhEqy_TJFuO7sCZyUtA.png" /></figure><p>The in operator <strong>detects whether an index truly exists in the array</strong>, even if the value is undefined.</p><p>This distinction between <strong>a hole and a real (but undefined) value</strong> is why built-in methods like reduce skip over holes entirely.</p><h3>🧪 Why i in this is Critical in Polyfills</h3><p>Imagine you are building your own reduce:</p><pre>Array.prototype.myReduce = function (callback, initialValue) {<br>    if (this.length === 0 &amp;&amp; initialValue === undefined) {<br>        throw new TypeError(&#39;Reduce of empty array with no initial value&#39;);<br>    }<br>    let accumulator = initialValue;<br>    for (let i = 0; i &lt; this.length; i++) {<br>        if (!(i in this)) continue;<br>        if (accumulator === undefined) {<br>            accumulator = this[i];<br>        } else {<br>            accumulator = callback(accumulator, this[i], i, this);<br>        }<br>    }<br>    return accumulator;<br>};</pre><p>Without i in this, your polyfill will mistakenly treat holes as real values — possibly breaking your logic.</p><pre>const arr = [1, , 3];<br>console.log(arr.myReduce((acc, curr) =&gt; acc + curr, 0));<br>// Without `i in this`, this would NaN or fail, because `curr` would be `undefined`</pre><h3>💀 A Tale of Two Undefineds</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iuf1f607nAcim7OU1hWWiA.png" /></figure><p>This is why checking:</p><pre>if (this[i] === undefined)</pre><p><strong>is wrong when handling sparse arrays.</strong></p><h3>💀 The Hidden Bug Lurking in Your Code</h3><p>You might not care about sparse arrays… until you do. Maybe your data comes from user input, a CSV parser, or an external API. The moment a hole sneaks into your array, your logic could crumble.</p><pre>const userScores = [100, , 200];  // Missing one entry<br>const total = userScores.reduce((sum, score) =&gt; sum + (score || 0), 0);<br>// This may work, but only because of the `|| 0` trick.<br>// If you forget it, your whole app might explode into a NaN.</pre><p>A robust system detects and handles sparse arrays <strong>correctly</strong>. That’s why polyfills and array-processing methods use i in this to stay vigilant.</p><h3>💎 The Invisible Guardian — i in this</h3><p>Whenever you loop through an array, especially in utility functions like map, filter, reduce, forEach, etc., always ask yourself:</p><blockquote><strong><em>Am I handling sparse arrays correctly?</em></strong></blockquote><p>If the answer is “I’m not sure”, it’s time to call in the guardian:</p><pre>if (i in arr)</pre><p>This tiny check is the difference between a well-behaved function and one that crashes when a ghost index shows up.</p><h3>🚀 Final Word</h3><p>JavaScript arrays aren’t just lists — they can be <strong>dense</strong> (every index exists) or <strong>sparse</strong> (some indices are holes). Knowing the difference is what separates beginner devs from JavaScript ninjas.</p><p>Next time you write an array utility, don’t just check arr[i]. Check:</p><pre>if (i in arr)</pre><p>Because in JavaScript, sometimes the most dangerous bugs are the ones you <strong>can’t see</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a83c2f76db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polyfills for map, filter, and reduce]]></title>
            <link>https://medium.com/@nikhilkumarmodi/polyfills-for-map-filter-and-reduce-c2250e4313a4?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2250e4313a4</guid>
            <category><![CDATA[polyfill-for-reduce]]></category>
            <category><![CDATA[frontend-interviews]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[polyfill-for-map]]></category>
            <category><![CDATA[polyfill-in-javascript]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Sat, 01 Mar 2025 17:47:36 GMT</pubDate>
            <atom:updated>2025-03-01T17:55:14.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*k64r8sAAI3I729VNpeWZmw.png" /></figure><h3>🚀 Why do we need polyfills?</h3><p>Before we dive into the actual polyfills, it’s important to understand <strong>why we need them in the first place</strong>.</p><p>A <strong>polyfill</strong> is a piece of code that provides modern functionality on <strong>older browsers</strong> that do not natively support it.</p><p>For example, modern browsers support map, filter, and reduce on arrays. But if you&#39;re working with older environments (like IE 8 or earlier), these methods may not exist. To ensure your code works everywhere, you can write <strong>polyfills</strong>, which essentially mimic the behavior of these methods.</p><h3>Understanding How Map, Filter, and Reduce Work</h3><h4>Example Array</h4><pre>const arr = [1, 2, 3, 4];</pre><h4>Map Example</h4><pre>const squareCallback = (item) =&gt; item * item;<br>const squaredArr = arr.map(squareCallback);// arr.map((item) =&gt; item*item)<br>console.log(squaredArr); // [1, 4, 9, 16]</pre><p>Map applies a callback to each item and returns a <strong>new array</strong>.</p><h4>Filter Example</h4><pre>const evenCallback = (item) =&gt; item % 2 === 0;<br>const evenArr = arr.filter(evenCallback); //arr.filter((item) =&gt; item%2 === 0)<br>console.log(evenArr); // [2, 4]</pre><p>Filter applies a callback and <strong>keeps only items that match the condition</strong>.</p><h4>Reduce Example</h4><pre>const sumCallback = (acc, item) =&gt; acc + item;<br>const sum = arr.reduce(sumCallback, 5); //arr.reduce((acc,item) =&gt; acc + item),5)<br>console.log(sum); // 15</pre><p>Reduce accumulates values into a <strong>single result</strong>.</p><h3>Polyfills for Map, Filter, and Reduce</h3><h4>Polyfill for Map</h4><pre>Array.prototype.myMap = function(callback) {<br>    const result = [];<br>    this.forEach((item, index, array) =&gt; {<br>        result.push(callback(item, index, array));<br>    });<br>    return result;<br>};<br><br>console.log(arr.myMap(squareCallback)); // [1, 4, 9, 16]</pre><h3>Polyfill for Filter</h3><pre>Array.prototype.myFilter = function(callback) {<br>    const result = [];<br>    this.forEach((item, index, array) =&gt; {<br>        if (callback(item, index, array)) {<br>            result.push(item);<br>        }<br>    });<br>    return result;<br>};<br><br>console.log(arr.myFilter(evenCallback)); // [2, 4]</pre><h3>Polyfill for Reduce</h3><pre>Array.prototype.myReduce = function(callback, initialValue) {<br>    let accumulator = initialValue; <br>    this.forEach((item, index) =&gt; {<br>        if (accumulator !== undefined) {<br>            accumulator = callback(accumulator, item, index, this);<br>        } else {<br>            accumulator = item; <br>        }<br>    });<br><br>    return accumulator;<br>};<br><br>console.log(arr.myReduce(sumCallback, 1));  // With initial value -&gt; 11<br>console.log(arr.myReduce(sumCallback)); // Without initial value -&gt; 10</pre><h3>Thanks for Reading! 🙏</h3><p>If you found this article helpful, please do:</p><p>✅ <strong>Like</strong> to show your support.<br>✅ <strong>Share</strong> it with your fellow developers who are preparing for interviews.<br>✅ <strong>Follow me</strong> for more articles on JavaScript, frontend interviews, and web development.</p><p>Your feedback is always welcome — feel free to comment with your thoughts, questions, or suggestions for improvement.</p><p>Happy Coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2250e4313a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Interview — Grid Light Problem]]></title>
            <link>https://medium.com/@nikhilkumarmodi/react-interview-grid-light-problem-d1352719c0dc?source=rss-644723183996------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1352719c0dc</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[react-interview-question]]></category>
            <category><![CDATA[react-interview]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Nikhil Modi]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 19:49:09 GMT</pubDate>
            <atom:updated>2025-03-01T18:18:26.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Interview — Grid Light Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*MDmF9xJJYjrLKQH2RDkvRA.png" /></figure><p>The Grid Light Problem is a React-based coding challenge that involves toggling lights in a grid based on user interaction. The objective is to allow users to select lights and then automatically remove them one by one once all have been selected. This problem tests state management, event handling, and understanding of React’s rendering behavior.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfnaCCMdkfpA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DfnaCCMdkfpA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfnaCCMdkfpA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b9238a5e3ffeba9b886bcd3d1e2aebb/href">https://medium.com/media/9b9238a5e3ffeba9b886bcd3d1e2aebb/href</a></iframe><h3>Approach</h3><p>To solve this problem, I followed these steps:</p><ol><li><strong>Define the Grid Layout</strong>: I created a 3x3 grid using a nested array structure where each cell represents a light (either active or inactive).</li><li><strong>Handle User Clicks</strong>: Clicking an active cell should highlight it and add it to the selectedItem state.</li><li><strong>Detect Completion</strong>: When all selectable lights are clicked, a removal process should begin.</li><li><strong>Implement Automatic Removal</strong>: Use setInterval to remove selected items one by one over time.</li></ol><h3>Solution</h3><p>Here is the final solution:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnifty-galileo-t4ld28&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Fnifty-galileo-t4ld28&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft4ld28%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/353ee1390d5e8a3d5a0061f12a535958/href">https://medium.com/media/353ee1390d5e8a3d5a0061f12a535958/href</a></iframe><h3>Mistakes &amp; Lessons Learned</h3><p>While implementing this solution, I encountered a few issues:</p><h4>1. Initially Used Two useState and useEffect</h4><ul><li>In my first implementation, I used two separate useState hooks and useEffect to track selection and removal.</li><li><strong>Fix</strong>: I realized I could manage everything with a single state variable (selectedItem) and remove useEffect, simplifying the logic and improving performance.</li></ul><h4>2. State Mutation Issue</h4><ul><li>Initially, I tried using prev.pop() inside setState, but this mutated the state directly.</li><li><strong>Fix</strong>: Use slice(0, -1) to create a new array instead of mutating the existing one.</li></ul><h4>3. setInterval with Stale State</h4><ul><li>Since setInterval runs asynchronously, it captured an outdated version of selectedItem.</li><li><strong>Fix</strong>: Used functional updates (setSelectedItem(prev =&gt; prev.slice(0, -1))) to ensure correct state updates.</li></ul><h4>4. Strict Mode Causing Duplicate Effects</h4><ul><li>When running in React Strict Mode, my initial implementation caused unexpected duplicate removals.</li><li><strong>Fix</strong>: I ensured that setInterval was managed correctly and cleaned up properly, preventing duplicate execution in development mode.</li></ul><p>Writing about my mistakes and learnings has been a great exercise, and I encourage others to document their experiences as well. Sharing these insights helps both beginners and experienced developers improve their craft.</p><p>If you liked the problem and want me to write a blog/provide solutions to similar problems, please hit the like button and share it with someone who is preparing for frontend interviews.</p><p>This was my first article — thanks for reading! I hope you found it useful. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1352719c0dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>