<?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 Anmol Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Anmol Choudhary on Medium]]></description>
        <link>https://medium.com/@3anmol3?source=rss-998e4032693d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lpTo3WW5b1bEz8Y-</url>
            <title>Stories by Anmol Choudhary on Medium</title>
            <link>https://medium.com/@3anmol3?source=rss-998e4032693d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:35:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@3anmol3/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[Never Copy a Decoded Message]]></title>
            <link>https://medium.com/@3anmol3/never-copy-a-decoded-message-17bcf8d23adf?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/17bcf8d23adf</guid>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[structuredclone]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototype]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 09:22:11 GMT</pubDate>
            <atom:updated>2026-09-15T09:22:11.923Z</atom:updated>
            <content:encoded><![CDATA[<p>Fields at their default value vanish. 64-bit numbers turn into objects, or strings, or NaN. Copying a decoded protobuf message breaks it in four different ways — here is which, why, and the two options that fix all of them.</p><p>You decode a protobuf message, copy it, and data goes missing. Usually it looks like one of these:</p><ul><li>Fields you know are populated read as undefined — specifically the ones whose value is 0, &quot;&quot; or false.</li><li>A 64-bit number arrives as { low, high, unsigned }, and arithmetic on it gives NaN.</li><li>Or it arrives as a string. Arithmetic still works, so nothing looks wrong until something calls .toFixed() and throws.</li></ul><p>Nothing throws at the point of failure and nothing warns. If you log the message before the copy and every field is correct.</p><p>The decode isn’t wrong. The copy is.</p><h3>The fix, if that’s all you came for</h3><pre>const TO_OBJECT_OPTIONS = { defaults: true, longs: Number };<br>const data = M.toObject(M.decode(buf), TO_OBJECT_OPTIONS);</pre><p>Convert at the decode site, before the message travels anywhere. defaults: true writes every field as a real own property, including the ones sitting at zero. longs: Number turns 64-bit fields into actual numbers. toObject walks nested messages too, so this applies all the way down.</p><p>The part that catches people: <strong>toObject() without those options does not fix it.</strong> Both option defaults work against you — defaults is false, so unset fields are still left out, and longs keeps the Long type as-is. You convert the container and leave the contents exactly as broken.</p><pre>structuredClone(M.toObject(msg));<br>// indexValue : { low: 2150075, high: 0, unsigned: false }<br>// prevClose  : undefined</pre><p>One caveat before you ship it: longs: Number loses precision above 253. If a field can genuinely exceed that — a nanosecond timestamp, a large id — use longs: String and parse it deliberately.</p><h3>Why fields disappear</h3><p>Generated protobuf code puts proto3 defaults on the prototype:</p><pre>Message.prototype.indexname = &quot;&quot;;<br>Message.prototype.prevClose = $util.Long ? $util.Long.fromBits(0,0,false) : 0;</pre><p>A field sitting at its default isn’t on the wire, so the decoder never assigns it. The message reads it through the prototype chain instead:</p><pre>const msg = M.decode(buf);<br>Object.keys(msg);                  // [ &#39;indexname&#39;, &#39;indexValue&#39; ]<br>msg.prevClose;                     // 0      ← via the prototype<br>Object.hasOwn(msg, &#39;prevClose&#39;);  // false</pre><p>A dozen fields on the message, two own properties. Copying in JavaScript means own enumerable properties — so spread, Object.assign, JSON and structured clone all drop the same fields. This half of the problem is everywhere.</p><h3>Why numbers become objects</h3><p>A 64-bit integer doesn’t fit in a JavaScript number, so protobufjs decodes one into a Long: an object carrying low, high and unsigned, with all of the arithmetic on its prototype.</p><p>This half is narrower. Spread and Object.assign copy the <em>reference</em>, so the Long arrives with its prototype intact and still behaves like a number. Structured clone doesn’t copy references — it rebuilds the value, and a rebuilt object has no prototype.</p><pre>const cloned = structuredClone(msg);<br>cloned.indexValue;        // { low: 2150075, high: 0, unsigned: false }<br>cloned.indexValue / 100;  // NaN</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_2p_spFZSZiJRf8ml8C5GA.png" /></figure><p>Only the own properties make the trip. The prototype — and everything that lived on it — does not.</p><h3>Which copy breaks what</h3><p>Same message, same two fields, four common operations:</p><pre>copy                           int64 field              arithmetic       at default<br>-----------------------------  -----------------------  ---------------  ----------<br>structuredClone / postMessage  { low, high, unsigned }  NaN              undefined<br>{ ...msg }                     Long                     works            undefined<br>Object.assign({}, msg)         Long                     works            undefined<br>JSON round-trip                &quot;2150075&quot; (string)       works (coerced)  undefined</pre><p>The postMessage row is the loudest, which is why this is often filed as a Web Worker problem. It isn’t — a worker just happens to copy, and structured clone is the one operation that triggers both halves at once. The same goes for anything else built on it: BroadcastChannel, MessageChannel, IndexedDB, history.pushState.</p><p>The JSON row is the sneakiest. protobufjs generates a toJSON on the prototype, so JSON.stringify routes through it and emits longs as strings. So it looks fine — until typeof is string, .toFixed() throws, === against a number fails, and a sort goes lexicographic.</p><p>The one thing every row shares is the last column.</p><h3>Why it takes so long to find</h3><p><strong>It’s silent.</strong> Nothing throws and nothing warns. A number turns into NaN, or quietly into a string, several layers downstream of the cause.</p><p><strong>It’s partial.</strong> Fields that were on the wire survive in some form. Fields at their default vanish. Strings and enums come through perfectly. So it reads like bad data rather than broken plumbing, and you go looking at the server.</p><p><strong>It’s invisible where you would look.</strong> Log the message before the copy and every field is correct, because the prototype is still attached and Long still knows how to print itself. The damage happens in the copy, between the log line and the reader.</p><h3>The general shape</h3><p>None of this is really about protobuf.</p><p>Copying in JavaScript means own enumerable properties. Structured clone goes further and discards prototypes outright. So any value whose usefulness lives somewhere other than its own properties — a class instance, a wrapper type, a getter, anything with a valueOf you quietly depend on — survives a copy as a hollow version of itself.</p><p>Decoded messages, ORM rows, model instances, anything handed to you by a library: before you copy one, ask which parts are own properties. If you can’t answer quickly, don’t copy the object you happen to be holding. Build a plain one on purpose and pass that around instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17bcf8d23adf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Centering Before Measuring]]></title>
            <link>https://medium.com/@3anmol3/centering-before-measuring-dfa773db6e20?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa773db6e20</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-virtualization]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 08:07:49 GMT</pubDate>
            <atom:updated>2026-09-14T08:07:49.414Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to server-render a virtualized list that arrives already scrolled to the right row — by writing the browser’s own centering rule as CSS and letting it fill in the one number the server doesn’t have.</h3><p>Some lists shouldn’t open at the top. A chat opens at the last unread message. A log viewer opens on the line you clicked. A data grid opens on the row you selected. The row you care about belongs in the middle of the screen.</p><p>On the client that’s one line:</p><pre>virtualizer.scrollToIndex(targetIndex, { align: &#39;center&#39; });</pre><p>On the server it isn’t one line. It isn’t possible at all — and that gap is the flash your users see: the list paints at row zero, then jumps.</p><p>Here’s why. The list is <strong>virtualized</strong>, so only the rows near the screen are rendered. It’s also <strong>server-rendered</strong>, so the HTML ships with its data already in it. Both are normal on their own. Together they’re a problem: to center row <em>N</em> you need to know how tall the viewport is, and the server has no viewport.</p><h3>Four ways to lose</h3><p><strong>Ship every row.</strong> The HTML fills up with rows nobody will see, and it’s still scrolled to the top. You paid the cost and kept the bug.</p><p><strong>Skip SSR for the list.</strong> Render the shell on the server, the rows on the client. Now the HTML arrives with a header, controls, and no rows — the page looks ready before it is. Worse, anything that reads HTML without running JavaScript sees an empty list. Most link-preview and social scrapers don’t run JS at all, and Google does but on a slower second pass, so the content you want indexed shows up late, if ever. On a page whose whole value is its rows, that’s a lot to give up.</p><p><strong>Guess the viewport height.</strong> Right on one monitor. Everyone else gets a jump, and the worse the guess, the bigger the jump.</p><p><strong>Live with the flash.</strong> Measure on the client, then scroll. Most apps do this. On a list built around one row being in one place, it looks cheap.</p><h3>Let CSS hold the number you don’t have</h3><p>Each of those tries to work out the scroll position on the server, and each fails on the same missing number.</p><p>But CSS already has a way to write down a value the browser fills in later. That’s what a percentage is. 50% on a positioned box means half the height of the box around it. The server doesn’t need to know what that comes to. It just writes it down.</p><p>So don’t scroll the list. <strong>Position</strong> it, and let the browser supply the half of the sum it alone knows.</p><h3>What scrollToIndex actually does</h3><p>Here is the real code, from @tanstack/virtual-core 3.17.0:</p><pre>getOffsetForAlignment = (toOffset, align, itemSize = 0) =&gt; {<br>  // `size` is the measured height of the scroll port.<br>  const size = this.getSize();<br>  if (align === &quot;center&quot;) {<br>    toOffset += (itemSize - size) / 2;<br>  }<br>  const maxOffset = this.getMaxScrollOffset();<br>  return Math.max(Math.min(maxOffset, toOffset), 0);<br>};</pre><p>toOffset starts as the row’s top. Write rowCenterOffset for the middle of the row, and it comes out as:</p><pre>rowCenterOffset = i × rowHeight + rowHeight / 2<br>scrollTop = clamp( rowCenterOffset − viewport/2 ,  0 ,  contentHeight − viewport )</pre><p>Only one of those is unknown on the server. Row height is a constant, the target row’s index comes from the data, and the content height is just the row count times the row height. The viewport is the only gap — and it appears only as viewport and viewport/2.</p><p>Now the swap. Scrolling a box down by <em>S</em> looks exactly the same as moving its contents up by <em>S</em>. So take the rows out of normal flow and set top to the negative of that scroll position. Flipping the sign flips the min and max too:</p><pre>top = −scrollTop<br>    = min( 0 ,  max( viewport − contentHeight ,  viewport/2 − rowCenterOffset ) )</pre><p>Inside the scroll port, viewport is 100% and viewport/2 is 50%. Now the server can print it:</p><pre>const getSsrCenterTop = ({ centerVirtualIndex, rowHeight, contentHeight }) =&gt; {<br>  const rowCenterOffset = centerVirtualIndex * rowHeight + rowHeight / 2;<br>  return `min(0px, max(calc(100% - ${contentHeight}px), calc(50% - ${rowCenterOffset}px)))`;<br>};</pre><p>That’s the whole trick. The browser fills in its half, and both sides land on the same row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATR56GtjnQ5QyyVGZVLhSQ.png" /></figure><p>The server knows how far down the block its target row sits. The browser knows how tall the window is. Neither can center the row alone.</p><h3>The two limits</h3><p>The min and max aren’t decoration — they’re the browser’s own scroll limits. min(0px, …) means you can’t scroll above the first row. max(calc(100% - contentHeight), …) means you can’t scroll past the last one.</p><p>In that order they also handle the short list. If the content is shorter than the viewport, 100% - contentHeight is positive, the inner max returns it, and the outer min pulls it back to 0 — pinned to the top, where a short list belongs. Swap the order and short lists float.</p><h3>Send 41 rows, not all of them</h3><p>Positioning is solved, but the virtualizer still can’t help on the server: with no element to measure, its visible range is empty, so no rows reach the HTML at all. The server picks a band around the target row instead:</p><pre>const getSsrWindowRange = ({ centerVirtualIndex, totalRowCount, halfWindowRows }) =&gt; {<br>  if (centerVirtualIndex &lt; 0) {<br>    return { startIndex: 0, endIndex: Math.min(totalRowCount, halfWindowRows * 2 + 1) };<br>  }<br>  return {<br>    startIndex: Math.max(0, centerVirtualIndex - halfWindowRows),<br>    endIndex: Math.min(totalRowCount, centerVirtualIndex + halfWindowRows + 1),<br>  };<br>};</pre><p>With a half-window of 20 that’s 41 rows, however long the list is.</p><p>Near either end the band goes lopsided — fewer rows above the target than below. That doesn’t matter, because the top expression measures from the target row’s position in the <em>full</em> list, not from the first row rendered. For that to hold, each row has to carry its real position:</p><pre>return { key: index, index, start: index * ROW_HEIGHT, size: ROW_HEIGHT };</pre><p>Same shape the virtualizer produces, same coordinates. That’s what makes the handover free.</p><h3>The handover</h3><p>At some point the real virtualizer takes over. The flag deciding which one renders has to start false on the server <em>and</em> on the client’s first render, or hydration breaks:</p><pre>const [isMeasured, setIsMeasured] = useState(false);<br>const rowItems = isMeasured ? virtualizer.getVirtualItems() : getSsrRowItems();</pre><p>A layout effect flips it before paint. The rows start coming from the virtualizer, the block goes back into normal flow, and scrollToIndex sets a real scrollTop.</p><p><strong>Nothing moves.</strong> Row <em>i</em> was drawn at i × ROW_HEIGHT before the flip and after it. Only two things change: which rows are mounted, and what does the offsetting.</p><p>Two ordering bugs are easy to hit, and both fail quietly.</p><p><strong>Flip before you center.</strong> Layout effects run in order, all of them before paint. The flip triggers a re-render React flushes right away, and the centering effect — keyed on isMeasured — runs after it. Put them the other way round and scrollToIndex fires while the rows are still out of flow, where there is no scroll height to work against. It runs and does nothing.</p><p><strong>clientHeight can be 0 on first paint</strong>, when a flex or grid parent hasn’t sized yet. Same no-op, same silence. A ResizeObserver retries until it lands or the user scrolls.</p><h3>What it costs</h3><ul><li><strong>Fixed row height.</strong> The whole thing rests on start = index × rowHeight being computable without measuring. Variable heights, no expression.</li><li><strong>The server has to know the target row.</strong> Fine when it comes from the data — last unread, selected row, first changed hunk. Not fine when only the client knows it.</li><li><strong>One more positioning mode</strong> to keep in your head, alive for a single frame.</li></ul><p>In return: the HTML arrives with the right rows in it, positioned correctly, and the first paint puts the target row in the middle of the screen. There is no frame where it isn’t.</p><h3>The part worth keeping</h3><p>Fixed rows and a server-known target are specific. The habit isn’t.</p><p>When one number in your layout math is only knowable in the browser, stop trying to compute the answer on the server. Write the expression, leave that number as a percentage, and let the browser finish it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa773db6e20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Dropped Moment.js, Slashed Our Client Payload, and Fixed DST Bugs Forever]]></title>
            <link>https://medium.com/@3anmol3/how-i-dropped-moment-js-slashed-our-client-payload-and-fixed-dst-bugs-forever-36130e99ae2e?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/36130e99ae2e</guid>
            <category><![CDATA[temporal-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript-temporal-api]]></category>
            <category><![CDATA[momentjs]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 05:59:58 GMT</pubDate>
            <atom:updated>2026-03-18T05:59:58.562Z</atom:updated>
            <content:encoded><![CDATA[<p>A deep dive into ECMAScript 2026’s Temporal API, and why you should never type new Date() again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uoJa6fPOqTi6DKqcBk1h2A.png" /></figure><p><strong><em>TL;DR:</em></strong><em> In this article, you will learn how to replace bloated third-party date libraries (like Moment.js or date-fns) with JavaScript’s new native Temporal API. We’ll build a mental model for separating “Exact Time” from “Wall-Clock Time,” implement DST-safe calendar math, and explore how to safely migrate legacy </em><em>Date objects in a modern Next.js/Node.js stack—all while improving client bundle sizes and rendering performance.</em></p><h3>The Scenario: The Midnight Panic</h3><p>It was 2:30 AM on a Sunday, and our automated CI/CD pipeline orchestration system had just failed catastrophically.</p><p>Our Next.js dashboard was throwing hydration errors, and the Node.js backend was logging transactions out of order. The culprit? A Daylight Saving Time (DST) “spring-forward” boundary. Our code was trying to schedule a server scale-down event at 2:30 AM — a time that, physically, <em>did not exist</em> that day because the clock had jumped straight from 1:59 AM to 3:00 AM.</p><h3>The Failed Attempt: The Library Era</h3><p>Historically, the JavaScript Date object has been the source of profound developer misery. Ported directly from a flawed java.util.Date class in 1995 over a 10-day sprint by Brendan Eich, it was actually deprecated in Java just two years later. Yet, due to the web’s golden rule of backward compatibility, JavaScript developers have been stuck with it for three decades.</p><p>To survive the Date object’s mutability and lack of global timezone support, my team did what everyone else did: we imported massive userland libraries. But relying on Moment.js and its timezone extensions meant shipping hundreds of kilobytes of IANA timezone databases over the wire. This crushed our React app’s time-to-interactive metrics on mobile. Worse, Moment’s mutable architecture constantly caused cascading state failures in our unidirectional data flows.</p><h3>The Breakthrough: The Temporal API</h3><p>On March 13, 2026, the Temporal API officially achieved Stage 4 consensus in TC39, cementing its place in the ES2026 specification. Championed by engineers at Bloomberg — who desperately needed nanosecond precision for high-frequency financial logs — Temporal completely rebuilds time management in JavaScript.</p><p>It is immutable, 1-indexed, timezone-aware, and completely native. Here is how it changes everything.</p><h3>1. The Core Philosophy: Immutability &amp; Sanity</h3><p>Temporal is a top-level global namespace, not a class. If you try to run new Temporal(), the engine will immediately throw a runtime exception.</p><p>The biggest architectural shift is <strong>absolute immutability</strong>. With the legacy Date object, calling a mutator like .setMonth() altered the object in place, which is a nightmare in React state management. Temporal returns a brand new object every time.</p><p>Furthermore, Temporal finally destroys the mathematically inconsistent zero-indexed month anomaly. January is Month 1. December is Month 12.</p><pre>// ❌ The Legacy Nightmare<br>const myDate = new Date(2026, 0, 31); // January 31, 2026<br>myDate.setMonth(1); // Add a month... wait, it silently overflows to March 3rd?!<br><br>// ✅ The Temporal Breakthrough<br>const safeDate = Temporal.PlainDate.from(&#39;2026-01-31&#39;);<br>const nextMonth = safeDate.add({ months: 1 }); <br>// Returns: 2026-02-28 (Intelligently clamps to the valid boundary!)</pre><p><em>(Lines 6–8 demonstrate Temporal’s native overflow clamping. Instead of blindly rolling over to March, it calculates the maximum valid boundary for February and clamps the value securely.)</em></p><h3>2. Exact Time vs. Wall-Clock Time</h3><p>The primary reason our pipeline failed at 2:30 AM was that we mixed absolute physical time with localized human time. Temporal forces you to strictly categorize these concepts to prevent unforced errors.</p><h4>The Physics of Exact Time: Temporal.Instant</h4><p>An Instant represents a unique, unalterable point in the universe, tracked with nanosecond precision via a native BigInt. It has no concept of timezones, years, or hours.</p><pre>// Grabbing the exact physical moment for a high-frequency database log<br>const exactNow = Temporal.Now.instant();<br><br>// Accessing the BigInt nanosecond value (no floating-point precision loss)<br>const nano = exactNow.epochNanoseconds;</pre><h4>The Abstraction of Wall-Clock Time: “Plain” Classes</h4><p>Wall-clock time is what humans experience. If you schedule a recurring calendar event for 8:00 AM, it should <em>always</em> happen at 8:00 AM local time, regardless of whether a politician changes DST rules.</p><p>Temporal introduces Plain classes (PlainDateTime, PlainDate, PlainTime, PlainYearMonth, PlainMonthDay).</p><pre>// Perfect for saving a user&#39;s Date of Birth<br>// Omits timezone/time completely, preventing off-by-one-day rendering bugs<br>const birthday = Temporal.PlainDate.from(&#39;1990-10-31&#39;);</pre><h4>Bridging the Gap: Temporal.ZonedDateTime</h4><p>When you need to project an exact physical instant into a localized format, you use the bridge: ZonedDateTime. It seamlessly fuses a Temporal.Instant with an IANA timezone identifier (like Europe/London).</p><p><em>(Note: For complex, multi-step orchestration workflows where you need to coordinate ZonedDateTime math across globally distributed microservices, consider moving the heavy lifting to a shared utility file.)</em></p><h3>3. Solving the DST Gap and Overlap</h3><p>Let’s revisit my 2:30 AM pipeline crash. When a territory observes a “spring-forward” transition, it creates a chronological gap. Temporal handles this deterministically.</p><p>If you attempt to schedule an execution during a non-existent time (the gap), Temporal automatically shifts the execution forward by the exact duration of the gap. If you hit a “fall-back” overlap (where 1:30 AM happens twice), it defaults to the earlier of the two physical instants.</p><h3>4. Parsing, Data Interchange, and Formatting</h3><p>Legacy Date.parse() was notoriously lenient and acted differently depending on the browser engine. Temporal strictly enforces the <strong>RFC 9557</strong> specification. If a string deviates from the accepted grammar, it throws a RangeError.</p><p>It also offloads human-readable formatting entirely to Intl.DateTimeFormat.</p><pre>const zdt = Temporal.Now.zonedDateTimeISO();<br><br>// The performance-optimized way to format arrays of Temporal objects<br>// Instantiate the formatter ONCE outside your loop to prevent localization DB lookups<br>const dtf = new Intl.DateTimeFormat(&#39;en-US&#39;, {<br>  dateStyle: &#39;full&#39;,<br>  timeStyle: &#39;short&#39;,<br>  timeZone: &#39;America/New_York&#39;<br>});<br><br>const humanReadable = dtf.format(zdt);</pre><h3>Trade-offs and Architectural Considerations</h3><p>While Temporal is a monumental leap forward, adopting it requires understanding its operational footprint:</p><ul><li><strong>Pros:</strong> Total elimination of external date libraries means massive bundle size reductions. Thread-safety in concurrent environments. DST-safe arithmetic. Native support for non-Gregorian calendars (Hebrew, Islamic, Chinese) with dynamic reference year canonicalization.</li><li><strong>Cons (Memory Implications):</strong> Because Temporal is strictly immutable, complex algorithms that execute thousands of date modifications in a tight loop will allocate a new object on the heap for every single operation. This increases Garbage Collection (GC) pressure compared to mutating a single legacy Date object in place.</li><li><strong>Learning Curve:</strong> The shift from .clone().add() (Moment.js style) to strict functional typing (.add({ days: 1 })) and explicit RFC 9557 serialization requires a paradigm shift for junior developers accustomed to loose string parsing.</li><li><strong>Ecosystem Readiness:</strong> As of early 2026, it is natively available in Chrome/Edge 144, Firefox 139, and Node.js v26. TypeScript 6.0 provides full ambient types. If you need to support older environments, you will still need to ship @js-temporal/polyfill, which temporarily mitigates the bundle-size benefits.</li></ul><h3>The Migration Path</h3><p>You don’t have to rewrite your entire monolithic codebase overnight. TC39 included migration bridges:</p><pre>// Upgrading legacy Date to Temporal<br>const legacy = new Date();<br>const modernInstant = legacy.toTemporalInstant();<br><br>// Downgrading Temporal to legacy Date (for old charting libraries)<br>const backToLegacy = new Date(modernInstant.epochMilliseconds);</pre><h3>Wrapping Up</h3><p>The Temporal API fundamentally restructures temporal management. It removes a historically vulnerable vector for data corruption and race conditions, drastically improves parsing efficiencies, and allows us to finally retire Moment.js and its massive timezone data payloads.</p><p>Have you started refactoring your legacy Date objects into Temporal yet, or are you waiting for your polyfills to clear out first? Let me know in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36130e99ae2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Eliminated AI Custom Integrations and Built a Web-Native Agent with Web MCP]]></title>
            <link>https://medium.com/@3anmol3/how-i-eliminated-ai-custom-integrations-and-built-a-web-native-agent-with-web-mcp-d96d908a36ba?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d96d908a36ba</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[web-mcp]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Mon, 02 Mar 2026 08:21:29 GMT</pubDate>
            <atom:updated>2026-03-02T08:21:29.152Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How adopting the Model Context Protocol saved us from vendor lock-in, slashed our token costs, and future-proofed our multi-agent architecture.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUuGx6TRKgWPMXiWSOEo8A.png" /></figure><p><strong><em>TL;DR:</em></strong><em> In this article, we’ll explore how to abandon brittle, vendor-specific AI tool integrations and build a robust, scalable agent architecture using the Model Context Protocol (MCP) over HTTP/SSE. You’ll learn how to construct a Web MCP server in TypeScript, connect it to a React frontend, and navigate the architectural trade-offs of stateful AI connections.</em></p><h3>The Scenario: The Integration Treadmill</h3><p>A year ago, our team was riding the generative AI wave. We built an incredible orchestration layer that connected our internal enterprise data to OpenAI’s models. We wrote custom Python scripts to scrape web data, handcrafted JSON schemas for tool-calling, and injected it all into the prompt context.</p><p>Then, Anthropic released a new Claude model that blew our existing metrics out of the water.</p><p>The mandate came down to switch. Suddenly, we realized our fatal flaw: our entire tool execution logic, data connectors, and API schemas were deeply coupled to OpenAI’s specific formatting. We spent weeks rewriting the integration layer. When Google’s Gemini updated shortly after, the cycle threatened to repeat. We were trapped in an unsustainable engineering burden, building bespoke bridges to isolated AI islands.</p><h3>The Failed Attempt: The Context Bottleneck</h3><p>Our initial “fix” was to abstract our internal APIs into massive JSON definitions and load them <em>all</em> into the model’s context window upfront. We called it our “universal toolchain.”</p><p>It was a disaster. As the number of connected tools grew, our prompt payload exploded. The intermediate tool results consumed so many tokens that we squeezed out the actual user context. Inference speeds tanked. Operational costs skyrocketed. We hit the notorious “context bottleneck” — our agents were drowning in their own instruction manuals.</p><h3>The Breakthrough: Web MCP</h3><p>Enter the Model Context Protocol (MCP), recently donated to the Agentic AI Foundation. Think of it as the “USB-C for AI.” MCP strictly decouples your data sources from the language model. Instead of hardcoding tool definitions into your prompts, you build an MCP Server that exposes standardized capabilities (Resources, Prompts, and Tools) to an MCP Client.</p><p>Initially, MCP relied heavily on local standard input/output (STDIO) connections — great for local IDEs like Cursor, but useless for web applications. The true paradigm shift for web developers is <strong>Web MCP</strong>, which utilizes Streamable HTTP and Server-Sent Events (SSE).</p><p>Let’s look at how to build one.</p><h3>Building a Web MCP Server in TypeScript</h3><p>We are going to build a remote MCP server using Express.js. This server will expose a tool to fetch and format web data, acting as a bridge between a frontend client and the AI.</p><p><em>Note: For production stability in the Node ecosystem, we rely heavily on strict typing and validation.</em></p><h4>1. Initialization and The Logging Trap</h4><p>Before we define tools, we need to set up the transport. A critical edge case when writing dual-purpose MCP servers (ones that might run via STDIO or HTTP) is standard output logging. If you use console.log(), you will corrupt the JSON-RPC payload in STDIO environments.</p><p>As a standard, we always implement a dedicated logger like Pino, configured to route all application traces to stderr or an external file, keeping stdout strictly pristine.</p><pre>import express from &quot;express&quot;;<br>import { McpServer } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;;<br>import { SSEServerTransport } from &quot;@modelcontextprotocol/sdk/server/sse.js&quot;;<br>import { z } from &quot;zod&quot;;<br>import pino from &quot;pino&quot;;<br><br>// Route logs to stderr to protect potential STDIO JSON-RPC streams<br>const logger = pino(pino.destination(2)); <br><br>const app = express();<br>app.use(express.json());<br><br>const server = new McpServer({<br>  name: &quot;enterprise-data-mcp&quot;,<br>  version: &quot;1.0.0&quot;,<br>});</pre><h4>2. Defining Tools with Zod</h4><p>Here’s where MCP shines. Instead of teaching the LLM how to parse our internal API nuances, we wrap it in a cleanly defined tool using Zod. The LLM reads the .describe() chains to figure out exactly how to use the function autonomously.</p><pre>server.tool(<br>  &quot;fetch_customer_data&quot;,<br>  {<br>    customerId: z.string().describe(&quot;The UUID of the customer to lookup.&quot;),<br>    includeHistory: z.boolean().default(false).describe(&quot;Include past purchase history.&quot;)<br>  },<br>  async (args) =&gt; {<br>    try {<br>      logger.info(`Executing customer lookup for: ${args.customerId}`);<br>      <br>      // Lines 11-12: Your complex internal logic/API calls go here.<br>      // The LLM doesn&#39;t need to know about auth headers or pagination.<br>      const data = await internalDb.customers.findById(args.customerId); <br>      <br>      return {<br>        content: [{ type: &quot;text&quot;, text: JSON.stringify(data) }],<br>      };<br>    } catch (error: any) {<br>      logger.error({ err: error }, &quot;Tool execution failed&quot;);<br>      return {<br>        content: [{ type: &quot;text&quot;, text: `Lookup failed: ${error.message}` }],<br>        isError: true, // Native MCP flag signals failure context back to the LLM<br>      };<br>    }<br>  }<br>);</pre><h4>3. Binding the SSE Transport</h4><p>To make this accessible to a web client, we expose two routes: a GET /sse for the persistent unidirectional stream, and a POST /messages for the client to trigger actions.</p><pre>let transport: SSEServerTransport | undefined;<br><br>app.get(&quot;/sse&quot;, async (req, res) =&gt; {<br>  logger.info(&quot;New SSE connection requested&quot;);<br>  <br>  // Point client POST requests to our /messages endpoint<br>  transport = new SSEServerTransport(&quot;/messages&quot;, res);<br>  await server.connect(transport);<br>});<br><br>app.post(&quot;/messages&quot;, async (req, res) =&gt; {<br>  if (!transport) {<br>    return res.status(400).send(&quot;SSE not established.&quot;);<br>  }<br>  <br>  try {<br>    // Relay incoming JSON-RPC payloads to the transport layer<br>    await transport.handlePostMessage(req, res);<br>  } catch (err) {<br>     logger.error({ err }, &quot;Transport error&quot;);<br>  }<br>});<br><br>app.listen(3001, () =&gt; logger.info(&quot;Web MCP Server live on 3001&quot;));</pre><h3>The Frontend: Declarative Integration with React</h3><p>Historically, managing an SSE connection lifecycle in a React application meant wrestling with useEffect, connection backoff logic, and messy state.</p><p>Using the use-mcp library, we abstract that entirely into a declarative hook.</p><pre>import React, { useState } from &#39;react&#39;;<br>import { useMcp } from &#39;use-mcp/react&#39;;<br><br>export default function AgentDashboard() {<br>  const [customerId, setCustomerId] = useState(&quot;&quot;);<br>  <br>  // The hook automatically handles negotiation and tool discovery<br>  const { state, tools, callTool } = useMcp({<br>    url: &#39;http://localhost:3001/sse&#39;<br>  });<br><br>  const handleLookup = async () =&gt; {<br>    if (state !== &#39;ready&#39;) return;<br>    <br>    try {<br>      // Execute the dynamically discovered tool<br>      const result = await callTool(&#39;fetch_customer_data&#39;, { customerId });<br>      console.log(&quot;Structured Context:&quot;, result);<br>    } catch (error) {<br>      console.error(&quot;Network or execution failure:&quot;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;p-4&quot;&gt;<br>      &lt;h3&gt;Connection: {state}&lt;/h3&gt;<br>      {/* UI logic based on connection state */}<br>      {state === &#39;ready&#39; &amp;&amp; (<br>        &lt;div className=&quot;flex gap-2 mt-4&quot;&gt;<br>          &lt;input <br>            value={customerId} <br>            onChange={(e) =&gt; setCustomerId(e.target.value)} <br>            placeholder=&quot;Enter UUID&quot; <br>          /&gt;<br>          &lt;button onClick={handleLookup}&gt;Lookup via Agent&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Trade-offs and Production Realities</h3><p>Web MCP is powerful, but it isn’t a silver bullet. If you are pushing this to production, you must account for the following:</p><h4>1. Performance: The Stateful Bottleneck</h4><p>SSE creates a persistent, stateful connection. In a massive enterprise deployment processing millions of requests, maintaining thousands of open HTTP connections creates substantial overhead for traditional load balancers.</p><ul><li><strong>The Trade-off:</strong> You gain real-time, low-latency agent streaming, but you sacrifice the easy scalability of stateless REST functions. If you are building a serverless architecture, you will need to carefully monitor connection limits or explore connection pooling/queueing systems (like utilizing Redis-backed buffers) to handle high-concurrency tool execution.</li></ul><h4>2. Security: The Human-in-the-Loop (HITL) Mandate</h4><p>Giving an autonomous LLM write-access to your database is architectural suicide without safeguards.</p><ul><li><strong>The Standard:</strong> The MCP specification demands strict OAuth 2.1 protocols and Dynamic Client Registration (DCR). More importantly, for any tool that <em>mutates</em> state (POST/PUT/DELETE), your frontend UI must aggressively intercept the JSON-RPC request and render a confirmation dialogue. The user must approve the payload before it ever hits your Express server.</li></ul><h4>3. MCP vs. Custom REST + Prompt Engineering</h4><p>Why not just stick to standard REST APIs and better prompt engineering?</p><ul><li><strong>Memory &amp; Big O:</strong> Standard REST APIs return bulky JSON, flooding the token window and increasing processing latency (O(N) where N is token count). MCP reference servers (like the mcp-server-fetch-typescript) utilize built-in markdown conversion and heuristic stripping. They intelligently parse DOMs and strip boilerplate <em>before</em> it hits the LLM, keeping the context window dense with actual value.</li><li><strong>Interoperability:</strong> Write the MCP server once, and it natively plugs into Claude Desktop, Cursor, and any custom Next.js frontend, without rewriting a single parsing instruction.</li></ul><h3>Conclusion</h3><p>The shift from isolated conversational models to interconnected, agentic ecosystems is already underway. At events like the Machine Learning Developer Summit happening right now in Bangalore, the focus is entirely on scaling LLMOps and multi-agent governance.</p><p>By adopting the Model Context Protocol, we step off the integration treadmill. We stop writing brittle scripts for specific models and start building standardized, robust data capabilities that any LLM can utilize.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d96d908a36ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Copy-Pasting Code: Architecting Frontend Apps When 80% of Your Codebase is Identical]]></title>
            <link>https://medium.com/@3anmol3/stop-copy-pasting-code-architecting-frontend-apps-when-80-of-your-codebase-is-identical-a5514d3ea5a6?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5514d3ea5a6</guid>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 10:47:15 GMT</pubDate>
            <atom:updated>2026-02-22T10:47:15.467Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TL;DR:</strong> Scaling multiple white-labeled or regional frontend applications usually leads to a maintenance nightmare of duplicated code. In this article, we’ll explore the transition from the chaotic “hard-fork” approach to structured Polyrepos (with private registries and Yalc) and unified Monorepos (using Turborepo/Nx). You’ll learn how to share 80% of your business logic seamlessly while keeping your CI/CD pipelines blazingly fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGphxCggLle8SLUpswGHIw.png" /></figure><h3>The Architectural Imperative: The 80/20 Trap</h3><p>As enterprise frontend applications evolve, organizations inevitably hit a specific scaling wall. You start with one successful application. Then, the business needs a white-labeled portal for a massive client, or a distinct regional variant.</p><p>Suddenly, you realize that <strong>80% of the new application is identical to the first</strong> — sharing the same core business logic, design system, network adapters, and authentication flows. Only <strong>20% diverges</strong> into bespoke features, distinct brand aesthetics, and specialized routing.</p><h3>The Struggle: The Copy-Paste Nightmare</h3><p>The initial, naive approach is the “hard fork.” You duplicate the base repository, slap a new logo on it, and deploy. It feels incredibly fast on day one.</p><p>Fast forward six months. Your team is now managing five distinct repositories. Every security patch, performance optimization, or UI component tweak must be manually ported, PR’d, and tested across all five codebases. Empirical data shows that this duplicated structure results in up to <strong>15x more defects</strong> and drastically slower cycle times. You aren’t engineering anymore; you are full-time copy-pasters trapped in maintenance hell.</p><p>To escape, we need to treat code-sharing as a foundational architectural pattern. Here are the three senior-level strategies to solve this, along with their distinct trade-offs.</p><h3>Solution 1: The Polyrepo + Private Registry Approach</h3><p>The historical standard for distributed development is the polyrepo architecture. You extract the shared 80% of your code into its own repository, publish it as a private package, and have your 20% bespoke apps consume it via standard package managers.</p><h4>How to Implement It</h4><ol><li><strong>The Registry:</strong> Host your shared UI and logic packages on GitHub Packages, AWS CodeArtifact, or a self-hosted Verdaccio instance. Scope them to your organization (e.g., @my-org/core-ui).</li><li><strong>The Local Dev Fix (Yalc):</strong> Standard npm link relies on symlinks, which frequently break modern bundlers and cause React &quot;invalid hook call&quot; errors. Instead, use <strong>Yalc</strong>. It acts as a local package store, physically copying the files to perfectly mimic a real NPM installation without the symlink friction.</li><li><strong>Automated Synchronization:</strong> Use Dependabot or Renovate. When your shared core pipeline publishes v2.1.0, the bot automatically traverses your individual project repos and opens PRs to bump the version.</li></ol><h4>The Trade-offs</h4><ul><li><strong>Pros:</strong> Ultimate team autonomy and strict blast-radius isolation. If a contractor breaks the build in the Marketing Site repo, the Enterprise Dashboard repo is entirely unaffected. You can also grant external access to a single app without exposing the core IP.</li><li><strong>Cons (The Maintenance Tax):</strong> <em>Version Drift.</em> Over time, App A might sit on v2.0 of your shared library while App B languishes on v1.4. Cross-cutting refactors require opening PRs across multiple repositories, destroying rapid iteration.</li></ul><h3>Solution 2: The Monorepo Breakthrough</h3><p>To eliminate the asynchronous friction of package publishing, the industry has heavily pivoted to the Monorepo architecture. You consolidate all applications and shared packages into a single Git repository, utilizing workspace symlinks (via pnpm or NPM Workspaces).</p><h4>The Mechanics of Atomic Collaboration</h4><p>The superpower of the monorepo is the <strong>atomic commit</strong>. If you introduce a breaking change to a shared core library, you can update all consuming Next.js applications in that exact same Pull Request. Version drift is mathematically impossible. Furthermore, your IDE can instantly surface TypeScript type errors across distant applications the second you modify a shared interface.</p><h4>Orchestration is Mandatory</h4><p>A naive monorepo will crush your CI/CD pipeline. If you change a typo in App A’s CSS, you do not want your CI rebuilding App B, App C, and the core library. You need an orchestrator:</p><ul><li><strong>Turborepo (The Velocity Engine):</strong> Built on Go, Turbo focuses on blazing-fast execution and caching. It’s the optimal choice for small-to-medium teams heavily utilizing Next.js.</li><li><strong>Nx (Enterprise Governance):</strong> Best for teams of 50+ developers. It enforces strict architectural boundaries (preventing App A from accidentally importing App B’s logic) and offers powerful code generation to maintain consistency.</li></ul><h4>Code Presentation: Intelligent Caching</h4><p>Here is a simplified turbo.json highlighting how we prevent CI bottlenecks:</p><pre>{<br>  &quot;$schema&quot;: &quot;https://turbo.build/schema.json&quot;,<br>  &quot;pipeline&quot;: {<br>    &quot;build&quot;: {<br>      // Line 6: App builds strictly depend on their dependencies&#39; builds finishing first.<br>      &quot;dependsOn&quot;: [&quot;^build&quot;],<br>      &quot;outputs&quot;: [&quot;.next/**&quot;, &quot;dist/**&quot;]<br>    },<br>    &quot;test&quot;: {<br>      // Line 11: Tests can run in parallel, completely independent of other tasks.<br>      &quot;dependsOn&quot;: []<br>    }<br>  }<br>}</pre><p><em>Note: By leveraging Vercel Remote Caching or Nx Cloud with setups like the above, if Developer A builds the massive shared core locally, Developer B — and the CI pipeline — instantly downloads the cached artifact instead of recompiling it.</em></p><h3>Solution 3: Composable Software (Bit.dev)</h3><p>If your organization refuses to adopt a Monorepo but hates the friction of a Polyrepo, component-driven development via <strong>Bit.dev</strong> offers a fascinating middle ground.</p><p>Bit virtualizes the repository. You maintain your 80% shared logic as independent Bit components hosted on the Bit Cloud. Your bespoke applications function as lightweight “App Shells.”</p><p>If you need to modify a shared component from within App A, you simply run bit import. Bit seamlessly clones that specific component’s source code and dependency graph directly into your local workspace. You modify it, test it, and run bit export to bump the version globally. Ripple CI then automatically runs tests on every downstream app that consumes that component, ensuring global stability without a monolithic Git repository.</p><h3>What NOT to do: The Micro-Frontend Anti-Pattern</h3><p>Micro-frontends (MFEs) via Webpack Module Federation are incredibly popular right now, but they are an <strong>anti-pattern for 80% overlap scenarios</strong>.</p><p>MFEs are designed for <em>domain segregation</em> (e.g., Team A builds the checkout, Team B builds the video player). If App A and App B are essentially clones with identical business logic, forcing them to integrate at runtime introduces massive network latency, complex state synchronization issues, and the risk of downloading duplicate dependencies. Stick to build-time integrations (Monorepos or Bit) for high-overlap architectures to preserve TypeScript safety and performance.</p><h3>The Final Verdict</h3><p>Your architectural choice defines your feature velocity.</p><ol><li><strong>If you prioritize strict isolation and use external contractors:</strong> Go Polyrepo, but aggressively automate your updates with Renovate and mandate Yalc for local dev.</li><li><strong>If you prioritize iteration speed and atomic refactoring:</strong> Adopt a Monorepo. Use Turborepo if you are a Next.js-heavy team wanting zero-config caching, or Nx if you need enterprise-grade dependency governance.</li><li><strong>If you want maximum modularity without centralized CI/CD:</strong> Investigate Bit for a truly composable architecture.</li></ol><p>Stop copying and pasting. Architect for scale, abstract your core, and let your build tools do the heavy lifting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5514d3ea5a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop “Chatting” With Your Code: A Strategic Framework for Agentic AI in 2026]]></title>
            <link>https://medium.com/@3anmol3/stop-chatting-with-your-code-a-strategic-framework-for-agentic-ai-in-2026-50fa56a33764?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/50fa56a33764</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 05:23:04 GMT</pubDate>
            <atom:updated>2026-02-15T07:40:17.953Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Moving beyond autocomplete: How to architect autonomous engineering loops, master “Context Engineering,” and maximize Return on Context.</strong></p><p><strong><em>TL;DR:</em></strong><em> The era of AI as a “smart autocomplete” is ending. 2026 will be defined by </em><strong><em>Agentic Workflows</em></strong><em> — autonomous loops where AI plans, tests, and executes code. This article outlines a blueprint for this shift, moving from RAG to “Context Engineering,” implementing adversarial TDD agent teams, and treating Figma designs as executable unit tests.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxpU3bkq1kGooTwcvXFPAA.png" /><figcaption>AI Generated Image</figcaption></figure><p>If you’ve been coding in the last two years, you know the drill. You open your IDE, you hit Tab for an autocomplete suggestion, or you open a chat window to ask, &quot;How do I center a div in 2025?&quot;</p><p>This is <strong>AI Assistance</strong>. It’s helpful, but it keeps <em>you</em> in the driver’s seat. You are the bottleneck.</p><p>The industry is currently undergoing a massive structural shift toward <strong>Agentic AI</strong>. An agent doesn’t just answer a question; it pursues a goal. It perceives, reasons, plans, executes, and — crucially — recovers from errors.</p><p>In this deep dive, we’re going to look at how high-performing engineering teams are operationalizing this shift. We aren’t talking about typing faster; we’re talking about <strong>Return on Context (RoC)</strong> — a new metric measuring how much engineering value you get per token consumed.</p><p>Here is the strategic framework for the Agentic Software Development Lifecycle (SDLC).</p><h3>1. The “Silent Reviewer”: Shift Left or Go Home</h3><p>The most expensive bugs aren’t in your code; they are in your requirements. We’ve all been there: a Product Manager writes a vague ticket, it sits in the backlog for two weeks, and you spend three days building the wrong thing because “handle gracefully” was open to interpretation.</p><p>In an Agentic workflow, we introduce the <strong>Silent Reviewer</strong>.</p><p>This is an agent integrated directly into your ticketing system (Jira/Linear). It doesn’t write code; it “lints” requirements. It uses linguistic analysis to flag ambiguity markers and compares the ticket against a vector database of past tickets that had high “rework rates.”</p><p><strong>The Ambiguity Check:</strong> If a ticket says “Ensure the dashboard loads fast,” the Silent Reviewer intercepts it before it reaches the sprint backlog.</p><blockquote><strong><em>Agent Output:</em></strong><em> “Ambiguity Detected: ‘Fast’ is not a quantifiable acceptance criterion. Based on historical SLA breaches, do you mean: A) Under 200ms (API response)? B) Under 1.5s (Largest Contentful Paint)? Please clarify to generate valid Gherkin syntax.”</em></blockquote><p>By calculating an <strong>Acceptance Risk Score</strong> (0–100), we can flag tickets that need human conversation, letting the straightforward ones flow directly to the coding agents.</p><h3>2. The Agentic TDD Loop: Adversarial Collaboration</h3><p>This is where the magic happens. Research shows that single-turn prompts (“Write a function that does X”) are prone to hallucination. To fix this, we don’t ask one AI to do the job. We hire a team.</p><p>We utilize a <strong>Role-Based Agent System</strong> with adversarial goals.</p><h4>The Setup</h4><p>We pit two agents against each other:</p><ol><li><strong>@test-writer ( The QA Persona):</strong> Its only job is to break things. It reads the requirements and writes a <em>failing</em> test.</li><li><strong>@coder (The Builder):</strong> It cannot start until a failing test exists (Red State). Its goal is to write the minimum code to pass the test (Green State).</li></ol><h4>The Implementation</h4><p>This solves the “Self-Delusion” problem where an LLM writes a soft test to pass its own bad code. Here is a simplified logic flow for the harness:</p><pre># Pseudo-code for the Agentic TDD Loop<br><br>def run_agentic_loop(feature_request):<br>    # Step 1: The Adversary<br>    test_file = agent_qa.generate_test(feature_request)<br>    <br>    test_result = run_test_suite(test_file)<br>    if test_result.passed:<br>        raise Error(&quot;Test passed before code was written! QA Agent failed.&quot;)<br><br>    # Step 2: The Builder (Looping until green)<br>    attempts = 0<br>    while not test_result.passed and attempts &lt; 5:<br>        # The coder sees the FAILURE log, not just the request<br>        code_diff = agent_coder.write_code(<br>            request=feature_request, <br>            error_log=test_result.logs<br>        )<br>        apply_diff(code_diff)<br>        test_result = run_test_suite(test_file)<br>        attempts += 1<br><br>    return test_result.passed</pre><p>This loop creates a self-healing mechanism. If the @coder hallucinates a library method, the test fails, the error log is fed back into the context, and the agent corrects itself in the next iteration.</p><h3>3. Context Engineering vs. RAG</h3><p>Stop using standard RAG (Retrieval-Augmented Generation) for active coding.</p><p>RAG is great for “How does the billing API work?” It is terrible for “Refactor the User class.” RAG relies on semantic similarity, which creates <strong>Context Amnesia</strong>. It might find the class definition, but miss the 40 files that import that class, leading to a broken build.</p><h4>The Solution: The Implementation Plan</h4><p>Instead of hoping the AI “remembers” what it’s doing, we force it to maintain an episodic memory file, usually implementation_plan.md, inside the repo.</p><p><strong>The Rule:</strong> The agent must update this file <em>before</em> it writes code.</p><pre># implementation_plan.md (Live Agent Context)<br><br>## Goal: Migrate to TypeScript<br><br>### Status<br>- [x] Create tsconfig.json<br>- [x] Rename index.js to index.ts<br>- [ ] Fix type errors in Auth module &lt;-- Current Focus<br>- [ ] Update CI pipeline<br><br>### Context Notes<br>- Note: The Auth module uses a legacy hashing function that needs a @ts-ignore for now.</pre><p>By pinning this file in the context window, the agent knows exactly where it is, what it has done, and what is left, even if the session crashes or the context window resets. This creates a high <strong>Return on Context</strong> — we aren’t wasting tokens re-explaining the goal every turn.</p><h3>4. Visual Fidelity: Figma as the Unit Test</h3><p>In 2026, “Visual Drift” (where the site looks nothing like the Figma file) is a solved problem, but not by using pixel-matching.</p><p>Pixel matching is brittle. If a font renders 1% differently on Linux vs. Mac, the test fails.</p><p>We use <strong>Visual AI</strong> (tools like Applitools or Percy) combined with a “Figma as Truth” workflow. The agent pulls the specific frame from the Figma API and compares it to the DOM snapshot using semantic understanding, not pixel grids.</p><p>If the button is blue in Figma but green in code, the agent generates a <strong>Drift Report</strong>. Future-state agents can even auto-generate the CSS fix to match the Figma tokens.</p><h3>5. The “Senior” Reality Check: Trade-offs &amp; Risks</h3><p>As with any architecture, there is no free lunch. Operationalizing Agentic AI comes with specific senior-level concerns:</p><ol><li><strong>The Infinite Loop:</strong> Agents can get stuck in “repair loops” — fixing a bug, causing a new one, fixing that, and breaking the first one again. You <em>must</em> implement “Circuit Breakers” (max loop limits) and “Human-in-the-Loop” checkpoints.</li><li><strong>The Agentic Insider Threat:</strong> If you give an agent write access to your repo and it ingests a poisoned dependency or a malicious prompt from a PR comment, you have effectively automated a security breach. We need <strong>Security Champion Agents</strong> — dedicated agents that run on every PR specifically to Red Team the code generated by other agents.</li><li><strong>Cost:</strong> Agency is capital intensive. A “chat” costs pennies. A TDD loop that runs for 45 minutes, spins up containers, and retries 15 times costs real money.</li></ol><h3>Summary</h3><p>The developers who thrive in 2026 won’t be the ones who can write the fastest React component. They will be the ones who can <strong>Architect the Harness</strong> — the structure of files, tests, and permissions that allows autonomous agents to do the work safely.</p><p><strong>Next Step:</strong> Don’t try to build the whole system at once. Start with <strong>Phase 1</strong>: Implement an implementation_plan.md rule in your current AI interactions. Force the AI to plan its work in a markdown list before it generates a single line of code. You&#39;ll feel the difference immediately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50fa56a33764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the “Loading Chunk Failed” Error in Next.js: Immediate Fixes & Long-Term Strategy]]></title>
            <link>https://medium.com/@3anmol3/solving-the-loading-chunk-failed-error-in-next-js-immediate-fixes-long-term-strategy-f562a8070892?source=rss-998e4032693d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f562a8070892</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Anmol Choudhary]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 07:22:22 GMT</pubDate>
            <atom:updated>2026-02-07T07:22:22.155Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to gracefully handle lazy-loading failures with a client-side safety net, and why your infrastructure might be the real culprit.</strong></p><p><strong><em>TL;DR:</em></strong><em> We are going to build a global error boundary hook that detects stale JavaScript chunks and safely reloads the page. Then, we’ll discuss why moving your static assets to S3/CDN is the actual architectural cure to prevent this from happening in the first place.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJp83tllKrDv0F1thzABkA.png" /><figcaption>AI Generated Image</figcaption></figure><h3>The Scenario: The “Zombie” Tab</h3><p>Picture this: You just deployed a shiny new version of your Next.js application.</p><p>Meanwhile, a user has had your dashboard open in a background tab for three hours. They click a button that navigates to a new route or opens a modal. This action triggers a lazy-loaded dynamic import (e.g., import(&#39;./HeavyComponent&#39;)).</p><p>Suddenly, the app crashes white. The console screams:</p><pre>Loading chunk 6977 failed. <br>(error: https://company.com/_next/static/chunks/app/login-fo1de3.js)</pre><h4>The Immediate Problem</h4><p>When you built your new deployment, Webpack/Turbo generated new hash-named JavaScript files (chunks) and deleted the old ones from your server. The user’s browser, however, is still running the <em>old</em> index.html referencing the <em>old</em> chunks. When it tries to fetch chunk-6977, your server returns a 404.</p><p>To fix this <strong>right now</strong>, we need a client-side safety net.</p><h3>The Client-Side Fix: A Safety-Valved Error Listener</h3><p>A common “quick fix” is to simply reload the page on any error. <strong>Do not do this.</strong> If the error is persistent (e.g., a firewall issue), you will trap your user in an infinite reload loop.</p><p>We need a solution that is <strong>resilient</strong> (handles both Events and Promises) and <strong>safe</strong> (limits retries).</p><h4>1. The Strategy</h4><p>We will use sessionStorage to track retries. It persists across page reloads but clears when the tab is closed.</p><ul><li><strong>Catch the error:</strong> Identify chunk loading failures specifically.</li><li><strong>Check the count:</strong> Have we reloaded &lt; 3 times?</li><li><strong>Reload:</strong> If yes, reload. If no, let the app crash so the user knows something is actually wrong.</li></ul><h4>2. The Implementation</h4><p>Here is the robust hook you can drop into your _app.tsx or root layout:</p><pre>const handleChunkLoadingError = useCallback(() =&gt; {<br>  const reloadCountKey = &#39;chunk-error-reload-count&#39;;<br>  const maxReloadAttempts = 3;<br><br>  const handleError = (event: ErrorEvent | PromiseRejectionEvent) =&gt; {<br>    // Normalize the error message<br>    const errorMessage = event instanceof ErrorEvent<br>      ? event.message<br>      : event.reason?.message || String(event.reason || &#39;&#39;);<br><br>    // 1. Check for standard Webpack &quot;Loading chunk X failed&quot;<br>    // 2. Check for &quot;ChunkLoadError&quot;<br>    // 3. Check for Next.js static file 404s<br>    const isChunkError =<br>      /Loading chunk [\d]+ failed/.test(errorMessage) ||<br>      /ChunkLoadError/.test(errorMessage) ||<br>      (event instanceof ErrorEvent &amp;&amp;<br>        event.filename &amp;&amp;<br>        /_next\/static\/chunks/.test(event.filename) &amp;&amp;<br>        /\.js$/.test(event.filename));<br><br>    if (isChunkError) {<br>       const currentCount = parseInt(<br>          sessionStorage.getItem(reloadCountKey) || &#39;0&#39;, <br>          10<br>       );<br><br>       if (currentCount &lt; maxReloadAttempts) {<br>          sessionStorage.setItem(reloadCountKey, String(currentCount + 1));<br>          window.location.reload();<br>       } else {<br>          // STOP! We have tried 3 times. <br>          // Clear count for future sessions.<br>          sessionStorage.removeItem(reloadCountKey); <br>       }<br>    }<br>  };<br><br>  // Listen for sync errors AND unhandled promise rejections<br>  window.addEventListener(&#39;error&#39;, handleError);<br>  window.addEventListener(&#39;unhandledrejection&#39;, handleError);<br><br>  return () =&gt; {<br>    window.removeEventListener(&#39;error&#39;, handleError);<br>    window.removeEventListener(&#39;unhandledrejection&#39;, handleError);<br>  };<br>}, []);</pre><h4>3. The “Success” Reset</h4><p>If a reload <em>works</em>, we need to reset the counter. We wait 10 seconds to ensure the page is stable.</p><pre>// Clear reload count on successful page load<br>const clearReloadCountOnSuccess = () =&gt; {<br>  setTimeout(() =&gt; {<br>    if (document.readyState === &#39;complete&#39;) {<br>      sessionStorage.removeItem(reloadCountKey);<br>    }<br>  }, 10000); <br>};</pre><h3>The “Real” Fix: Infrastructure vs. Band-aids</h3><p>While the code above is an excellent safety net, it is effectively a <strong>band-aid</strong>. It solves the symptom (the crash), but not the root cause (the missing file).</p><p>In a mature engineering environment, users should almost <em>never</em> encounter a 404 on a JavaScript asset, even during a deployment.</p><h4>The Architectural Solution: Immutable Assets on S3/CDN</h4><p>The root cause is that your deployment process is likely <strong>overwriting or deleting</strong> the previous build’s assets.</p><ol><li><strong>Deployment A</strong> creates chunk-123.js.</li><li><strong>Deployment B</strong> deletes chunk-123.js and creates chunk-456.js.</li><li>User on <strong>Deployment A</strong> requests chunk-123.js -&gt; <strong>404 Error</strong>.</li></ol><p><strong>The Fix:</strong> Configure your build pipeline to upload your .next/static folder to an object storage service like AWS S3 or Google Cloud Storage, served via a CDN (CloudFront/Cloudflare).</p><p>Crucially, <strong>do not delete old files immediately.</strong></p><p>If you keep previous build assets available for 7 days (or indefinitely), the “Zombie Tab” user will request chunk-123.js, and the CDN will happily serve it. They continue using the old version of the app seamlessly until they naturally refresh the page.</p><h4>So, why do we still need the code fix?</h4><p>Even with an S3/CDN architecture, you still need the handleChunkLoadingError hook. Why?</p><ol><li><strong>CDN Propagation Delays:</strong> There is often a gap between the HTML updating and the assets propagating to edge locations.</li><li><strong>Network Flukes:</strong> Mobile networks often drop requests, leading to ChunkLoadError even if the file exists.</li><li><strong>Aggressive Caching:</strong> Browser extensions or strict corporate proxies can sometimes block script loading.</li></ol><h3>Summary</h3><ul><li><strong>Level 1 (The Band-aid):</strong> Implement the handleChunkLoadingError hook to catch crashes and auto-reload safely.</li><li><strong>Level 2 (The Cure):</strong> Host your static assets on S3/CDN and keep old versions accessible to support users who haven’t refreshed yet.</li></ul><p>By combining both, you ensure a rock-solid user experience that handles both deployment transitions and network instability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f562a8070892" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>