<?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 Deepak Kharah on Medium]]></title>
        <description><![CDATA[Stories by Deepak Kharah on Medium]]></description>
        <link>https://medium.com/@deepak-kharah?source=rss-533e022804d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YsK9_NYvPe2UpBSPhnc1Wg.png</url>
            <title>Stories by Deepak Kharah on Medium</title>
            <link>https://medium.com/@deepak-kharah?source=rss-533e022804d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:49:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepak-kharah/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[My Clipboard Was Leaking JSON. So I Kept It Out of Plain Text]]></title>
            <link>https://deepak-kharah.medium.com/my-clipboard-was-leaking-json-so-i-kept-it-out-of-plain-text-ea1ca252f5f9?source=rss-533e022804d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1ca252f5f9</guid>
            <category><![CDATA[clipboard]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Deepak Kharah]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 04:01:01 GMT</pubDate>
            <atom:updated>2026-07-07T04:59:18.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-AHo2LQWOklBPKlsuK96A.png" /></figure><h4><em>A private copy for your app, a readable one for everyone else, and why staying clean gets tricky the moment you leave the browser.</em></h4><blockquote><strong>tl;dr</strong></blockquote><blockquote><em>Use a custom MIME type to store internal metadata in the clipboard that only your app can interpret, while keeping the plain-text version free of internal metadata.</em></blockquote><blockquote><em>Custom MIME types may not survive in every app because of privacy restrictions. When that happens, you can encode the internal data in an HTML comment or attribute and store it in the </em>text/html <em>MIME type. This type is more likely to survive because it’s one of the standard clipboard formats.</em></blockquote><h3>A Quick Back Story</h3><p>A long time ago, I built a prototype for copying and pasting a block in a JSON-driven node editor that renders the nodes defined within it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VcnsrmzZS1sQna1RTqrgQ.png" /><figcaption>A simple JSON-driven node editor prototype</figcaption></figure><p>In this quick prototype, I overrode the default copy-and-paste behaviour using the onCopy() and onPaste() handlers. When we press cmd + c, we save the node to the clipboard. On paste, we check whether the pasted content is our node. If so, we update the UI.</p><pre>// naive prototype — copy dumps the JSON straight into text/plain,<br>// paste checks the shape to decide whether it&#39;s ours<br>function onCopy(event, blocks) {<br>  event.preventDefault();<br>  event.clipboardData.setData(&quot;text/plain&quot;, serialize(blocks));<br>}<br><br>function onPaste(event) {<br>  const text = event.clipboardData.getData(&quot;text/plain&quot;);<br>  if (!text) return; // clipboard&#39;s empty<br>  const blocks = parse(text);<br>  if (!blocks) return; // foreign paste — not ours, ignore<br>  addBlocks(blocks);<br>}</pre><p>I love building clean and thoughtful experiences. So one detail in this prototype kept bothering me: when content is pasted into another text editor, it displays the JSON of the copied node. Since this was a quick project meant to help me learn JSON-driven UI, I never spent much time thinking through a proper fix. Eventually, this project was archived and long forgotten.</p><figure><img alt="The content pasted in Google Docs: {“source”:”block-editor-demo”,”version”:1,”blocks”:[{“id”:”b_nrljzqn”,”type”:”cards”,”accent”:”teal”,”heading”:”Why it works”,”cards”:[{“title”:”Flexible”,”text”:”Rearrange anything by dragging.”},{“title”:”Composable”,”text”:”Mix and match block types.”},{“title”:”Tidy”,”text”:”Copy/paste keeps things clean.”}]}]}" src="https://cdn-images-1.medium.com/max/1024/1*LzHX6uTxzpa3Y375dIHcmQ.png" /><figcaption>Normal paste in Google Docs</figcaption></figure><p>Here’s a <a href="https://clipboard-mime-type.deepakkharah.com/#naive-block-editor">replica of that prototype</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkrctsszlaP1EE4ZrKJ8ig.png" /><figcaption>JSON-driven node editor with simple pasting</figcaption></figure><p>One day, while travelling, <strong>my mind wandered</strong> to Google Sheets. I remembered something interesting: when you copy a cell containing a formula and paste it elsewhere within the sheet, Google Sheets pastes the formula. But when you paste it outside the sheet, it pastes the value instead. I never acted on this realization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*hQhZODDg7XOQIJVI6we8Tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*vChA_hkZ3QMAXvDiYLkVpQ.png" /><figcaption>Google Sheet replicating formula between paste</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1RXtb6fHaMrjT7sAe3O4w.png" /><figcaption>No formula is pasted outside the Sheets</figcaption></figure><p>Recently, I went down the rabbit hole again on the asymmetric effort it takes to build simple, intuitive apps that just work (<em>I’ll definitely write about that thread one day</em>). Along the way, I stumbled upon a video titled “<a href="https://youtu.be/5t8dh3DSdBk?si=HygqcLxMTCDq2x4F">The Ridiculous Engineering Of Figma (ft. Figma Team)</a>” that talked about how <strong>thoughtful</strong> their products are. One example that stood out was how many iterations they went through on copy-and-paste alone, all to make sure the feature felt intuitive.</p><p>Naturally, I went and tried the mechanism and found it fascinating. Then, it hit me. Figma knows how to paste it, yet the clipboard looks clean. The clipboard is not a mess of internal data telling it how to paste. So, I spent the weekend researching and working on improving my prototype.</p><h3>Please, welcome. Custom MIME Type</h3><p>The clue was simple. Somehow, they stored more information in the copied text so that the outside world sees simple text, while they see more context for how to handle the paste. The answer was MIME types. When you copy something, you can store it in multiple formats, such as text/plain text/html, image/png, etc. You have already seen this at work. When you paste anything into a rich-text environment like Notion or any Markdown editor, you’ll notice that the formatting, such as bold, italics, and colour, stays. It is because they read the text/html data. Other apps often fall back on text/plain because it is reliable and contains only text.</p><p>I quickly built a <a href="https://clipboard-mime-type.deepakkharah.com/mime-viewer">Clipboard MIME viewer</a> and pasted the content there, and here’s an example of the MIME type data. I copied it from a webpage.</p><pre>▸ text/plain<br>Hello, world. I am really doing well.<br><br>▸ text/html<br>&lt;meta charset=&#39;utf-8&#39;&gt;&lt;strong&gt;Hello, world&lt;/strong&gt;&lt;span&gt;. I am&lt;span&gt; &lt;/span&gt;&lt;/span&gt;&lt;em&gt;really&lt;/em&gt;&lt;span&gt;&lt;span&gt; &lt;/span&gt;doing well.&lt;/span&gt;</pre><p>Now, when I paste it into Notion, it knows where to make it bold and italicized.</p><blockquote><strong><em>Fun fact:</em></strong><em> When you paste using </em><em>cmd + shift + v instead of </em><em>cmd + v, it strips all MIME types except </em><em>text/plain. So, it doesn&#39;t bring the formatting from the source.</em></blockquote><p>I headed to Google Sheets, added data and formulas, copied the cells, and analyzed the results. Voilà, they had their custom MIME type for Sheets.</p><pre>• kind=string  type=text/plain<br>• kind=string  type=text/html<br>• kind=string  type=application/x-vnd.google-docs-embedded-grid_range_clip+wrapped<br>• kind=string  type=application/x-vnd.google-docs-internal-clip-id<br>• kind=string  type=application/x-vnd.google-spreadsheet-compact-table+json</pre><p>You can try playing with <a href="https://clipboard-mime-type.deepakkharah.com/#mini-spreadsheet">a simple replica I built</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yh2uVdhnruyZDqZpcinQQg.png" /><figcaption>Simple replica of Google Sheets to demonstrate copy and paste</figcaption></figure><p>With this direction, I went ahead and <strong>wrote my custom copy-and-paste</strong> logic that introduces a private MIME type. The whole trick fits in two handlers:</p><pre>const MIME = &quot;application/x-vnd.node-editor+json&quot;;<br><br>// COPY — write two representations of the same selection.<br>function onCopy(event, nodes) {<br>  event.preventDefault();<br>  // Private channel: lossless internal JSON. Only our app looks for this.<br>  event.clipboardData.setData(MIME, JSON.stringify(blocks));<br>  // Public channel: a clean, human-readable line for everyone else.<br>  event.clipboardData.setData(&quot;text/plain&quot;, toPlainText(nodes));<br>}<br><br>// PASTE — decide ownership by the PRESENCE of the private type,<br>// never by parsing text/plain.<br>function onPaste(event) {<br>  const internal = event.clipboardData.getData(MIME);<br>  if (!internal) return; // not ours → let the browser paste text/plain<br>  event.preventDefault();<br>  addNodes(JSON.parse(internal)); // ours → rebuild the real nodes<br>}</pre><p>The outside world only ever sees text/plain. We read the full-fidelity data from a channel nobody else looks at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKdGwj_gaiVvEctuqisfdA.png" /></figure><p>Here’s <a href="https://clipboard-mime-type.deepakkharah.com/#custom-block-editor"><strong>the example you can try</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezUfqWAgnrPdSo3tERzC_A.png" /><figcaption>JSON node editor with custom MIME type pasting</figcaption></figure><p>Sooooo, is that it? For a weekend’s work, yeah, the clipboard’s clean, the block round-trips, and no other app ever sees our JSON. I was pretty pleased with myself.</p><p>Before calling it done, I started pasting that block into other apps and then other browsers. That’s when I found out clean has edges.</p><h3>Show me your cards, Figma.</h3><p>I used my clipboard MIME viewer in the companion app to view clipboard content from various sources just for fun. When I pasted from Figma, I expected to find its custom MIME type. However, that was not the case.</p><pre>• kind=string  type=text/plain<br>• kind=string  type=text/html</pre><p>They only use the <strong>standard MIME types</strong>. During research, I could not find many strong reasons why that was the case. However, an <a href="https://alexharri.com/blog/clipboard">article by Alex Harri</a> suggested that it is to allow <strong><em>cross-platform copy-paste</em></strong>.</p><p>Now, if you know me, I wouldn’t just write about something because I read it somewhere. So, I <em>briefly</em> researched it and found that even <strong>cross-pasting in Safari didn’t work that well because it is focused on privacy</strong>.</p><p>I logged in to my Figma and Google accounts in Safari to try out various scenarios. I copied the formula from Google Sheets and pasted it into my clipboard MIME viewer. To my surprise, it only displayed the two standard MIME types.</p><pre>• kind=string  type=text/plain<br>• kind=string  type=text/html</pre><p>It turns out Safari is so privacy-focused that it strips custom MIME types when content is copied between <em>two different origins</em>. I built a <a href="https://clipboard-mime-type.deepakkharah.com/mime-viewer">short script </a>that injects a clipboard MIME viewer to examine the clipboard contents and confirm Safari’s behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDYNZyKPR2pIXA5GNQVjQg.png" /><figcaption>Custom MIME viewer in Google sheets on Safari</figcaption></figure><p>Google Sheets was even stranger. Copying in Chrome and pasting into Safari sometimes rebuilt the formula and sometimes didn’t, and the result even changed from one Google account to another. My best guess is that Sheets keeps the real data on its servers and matches it back on paste, but it was inconsistent enough that I won’t pretend I fully understand it. That’s a rabbit hole for another day.</p><p>Let’s get back to Figma. Cross-browser pasting worked <em>really</em> well, so Alex’s suggested reason may be correct. I built <a href="https://clipboard-mime-type.deepakkharah.com/#figma-canvas">a small demo for you to play</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fd5zNDVv0Wrc4EBvvImPQQ.png" /></figure><p>It’s time to replicate this behaviour in our editor and test it for ourselves. I removed the custom MIME type, encoded the JSON and stored it in an HTML attribute.</p><pre>// utf-8-safe base64 (btoa is latin1-only)<br>function encodeClip(json) {<br>  const bytes = new TextEncoder().encode(json);<br>  let bin = &quot;&quot;;<br>  for (const b of bytes) bin += String.fromCharCode(b);<br>  return btoa(bin);<br>}<br><br>// an empty span whose data-* value is a comment-wrapped base64 blob —<br>// survives HTML sanitizers better than a bare attribute<br>function markerHtml(base64) {<br>  return `&lt;span data-block-clip=&quot;&lt;!--(block)${base64}(/block)--&gt;&quot;&gt;&lt;/span&gt;`;<br>}<br><br>function onCopy(event, blocks) {<br>  event.preventDefault();<br>  const payloadJson = serialize(blocks);<br>  const html = markerHtml(encodeClip(payloadJson)) + toVisualHtml(blocks);<br>  event.clipboardData.setData(&quot;text/html&quot;, html);<br>  event.clipboardData.setData(&quot;text/plain&quot;, toPlainText(blocks));<br>}</pre><p>Now, when we try copying and pasting between browsers, it works well. Here’s <a href="https://clipboard-mime-type.deepakkharah.com/#block-editor-v3">the final example</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9ECJOLJ2cFHJIR8WOVoIg.png" /></figure><p>Looking back, the <em>core</em> idea never really changed: you save the same selection twice. Once in a private format only your app understands, and once as plain text for everyone else.</p><p>What changes is where you put the private copy. Inside a single browser, a custom MIME type works perfectly.</p><p>But the moment that copy leaves for another browser, the type gets stripped, so you do what Figma does and tuck the data inside the text/html instead, because that travels everywhere.</p><p>So keep the rich copy for yourself, always leave a readable one for the world, and just remember that the farther your copy has to travel, the fewer places you have to hide it.</p><p>You can try out the demos yourself: <a href="https://clipboard-mime-type.deepakkharah.com/">https://clipboard-mime-type.deepakkharah.com/</a>, or you can use the clipboard for your own research: <a href="https://clipboard-mime-type.deepakkharah.com/mime-viewer">https://clipboard-mime-type.deepakkharah.com/mime-viewer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1ca252f5f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Re‑Export from `index.ts`? That’s the Question.]]></title>
            <link>https://deepak-kharah.medium.com/should-you-re-export-from-index-ts-thats-the-question-46337ecf53ec?source=rss-533e022804d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/46337ecf53ec</guid>
            <category><![CDATA[bundler]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript-performance]]></category>
            <dc:creator><![CDATA[Deepak Kharah]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 17:33:05 GMT</pubDate>
            <atom:updated>2025-12-28T17:33:05.471Z</atom:updated>
            <content:encoded><![CDATA[<p>It started with a simple rabbit hole. I wanted to understand which rules I can enforce in my team to ensure we consistently write performant TypeScript code. One thing led to another, and I started learning about the <strong>Barrel File</strong>.</p><p>You know those index.ts files that act as a central hub, re-exporting everything in a folder so you can have “cleaner” imports. I’ve used them in almost every project I’ve ever built. But after reading about the potential performance overhead, I couldn’t just take the internet’s word for it. I had to build it, break it, and measure it.</p><pre>utils/<br>├── formatDate.js<br>├── capitalize.js<br>├── debounce.js<br>└── index.js        ← barrel file</pre><p>I created a <strong>Next.js 15 (React 19)</strong> experiment to assess whether this architectural “best practice” was a performance bottleneck. Here is what happened when I tested 100 components.</p><h3>The Laboratory Setup</h3><p>In this experiment, I sought to isolate the “Barrel File Effect” without other confounding variables.</p><ul><li><strong>The components:</strong> I have asked Cursor to help me create 100 React components (ranging from simple JSX to complex hooks) and one index.ts file that re-exports the components.</li><li><strong>The scenario:</strong> I created a baseline that renders no components, then imported ten components of varying complexity, used them, and tested them.</li><li><strong>The variables:</strong> I tested three specific Git branches against a “No Import” baseline.<br> <strong>exporting-using-star</strong>: The “Wildcard”, where I have re-exported the components using export *.<br> <strong>exporting-using-names</strong>: The “Named Export” where I have not used the wildcard. (export { Component }). It is said that, in this case, we are helping our bundler know which components to tree-shake.<br> <strong>importing-without-barrel-files</strong>: Here, we are importing directly from the component file and not the index.ts file.</li></ul><p>For every scenario, I have built the project and used the <a href="https://nextjs.org/docs/app/guides/package-bundling#nextjs-bundle-analyzer-experimental">Next.js Bundle Analyzer (Experimental)</a> to analyze it.</p><p>Here’s the repository for you to explore: <a href="https://github.com/Deepak-Kharah/blog-barrel-files-impact-on-bundle-size">https://github.com/Deepak-Kharah/blog-barrel-files-impact-on-bundle-size</a></p><h3>The Data: Evidence of the “Barrel Tax”</h3><p>The results confirmed my suspicions: What appears clean in my code editor imposes a measurable burden on the bundler.</p><h4>Client-Side: The Weight of Unused Modules</h4><p>On the client side, although I requested only 10 components, the barrel file required the bundler to include substantially more metadata and code.</p><figure><img alt="A data table comparing the client-side bundle performance of four import strategies. No Import (Baseline): 582.81 KB uncompressed, 212.15 KB compressed, with 172 modules. Exporting using export *: 680.35 KB uncompressed, 259.58 KB compressed, and 225 modules — a 16.7% increase (+97.54 KB) from the baseline. Exporting using named exports: Identical to the wildcard approach with 680.35 KB uncompressed, 259.58 KB compressed, and 225 modules (+16.7% increase). Direct imports (no barrel): The most" src="https://cdn-images-1.medium.com/max/913/1*ncO8e5aPRotI1cekkEu8bg.png" /><figcaption>Result of size of the bundle on the client side</figcaption></figure><p><strong>The Insight:</strong> Using a barrel file (of any kind) added <strong>47 extra modules</strong> to the client bundle. Even with modern tree-shaking, the “residual” code and module resolution logic added together account for about 14.4% more than directly importing the data.</p><h4>Server-Side: The SSR Nightmare</h4><p>The impact on the server-side bundle (where Next.js handles SSR) was even more dramatic, especially with wildcard exports.</p><figure><img alt="A data table comparing four different code import approaches on server-side bundle performance in a Next.js environment. The table includes columns for Uncompressed Size, Compressed Size, Number of Modules, and Difference from Baseline. No Import (Baseline): 273.79 KB uncompressed, 107.58 KB compressed, with 216 modules." src="https://cdn-images-1.medium.com/max/913/1*5UR-xL8XGthQO_VSgmpyjg.png" /><figcaption>Result of size of the bundle on the server side</figcaption></figure><p><strong>The Insight:</strong> export * is the ultimate performance killer, bloating the server bundle by adding <strong>139 extra modules</strong>.</p><p><strong>The Named Export Anomaly:</strong> Interestingly, Named Exports reduced the <em>uncompressed</em> size but significantly increased the <em>compressed</em> size and module count (<strong>328 modules</strong>). This result suggests that, although the code is stripped, the module graph’s complexity makes the final bundle harder to compress. Honestly, I don’t know why this happened. I have to check and dig deep or analyze again for the named export.</p><p>Finally, you can look at the result of the experiment yourself. I have placed the results in the <a href="https://github.com/Deepak-Kharah/blog-barrel-files-impact-on-bundle-size/tree/main/output">output folder</a>.</p><h3>Why This Happens</h3><p>I was wondering why a modern tool like Next.js doesn’t just “fix this,” and here’s what I understand. It comes down to how <strong>Module Resolution</strong> works:</p><ol><li><strong>Module Evaluation:</strong> When you hit a barrel file, the engine executes that file. If that file says “Export A through Z,” it must at least <em>review</em> all 26 modules to verify they exist. Some articles and videos suggest this analysis still helps the bundler to strip away the unused imports unless there are any side effects (like having a console.log in the index.ts file).</li><li><strong>The “Black Box” of </strong><strong>export *:</strong> Wildcard exports are a nightmare for compilers. They can’t know what’s inside until they’ve parsed every single file. This is why the server-side bloat was so high. This is true even when we import using the import *, you can see the import size shoot up when you use the <a href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost">import cost</a> VS Code plugin.</li><li><strong>Dependency Entanglement:</strong> Barrel files turn a collection of small, independent files into one massive, interdependent blob. This makes it much harder for the bundler to “shake” the tree without accidentally breaking a leaf.</li></ol><h3>The Verdict of the experiment</h3><h4>T<strong>he “Never Again” Award: </strong><strong>export *</strong></h4><p>Never use wildcard exports in a barrel file. You’re telling the bundler, “I don’t know what’s in here, you figure it out,” and the bundler responds by charging you a <strong>70% server-side tax</strong>.</p><h4>The “Proceed with Caution”: Named Barrel Exports</h4><p>If you <em>must</em> have a barrel file for a clean API, use <strong>Named Exports</strong>. It mitigates the server-side disaster compared to wildcards, but you will still pay a <strong>~16% penalty</strong> on your client-side bundle size.</p><h4>The Gold Standard: Direct Imports</h4><p>Importing directly from the source (@/components/Component1) resulted in the leanest bundle and the lowest module count. It’s the only way to ensure that <strong>only</strong> what you use ships.</p><h3>My thoughts on this experiment</h3><p>In our case, the client side saw no difference between using a wildcard and a named export. However, I wonder if I could have told the bundler that it is safe to discard those other unused imports in the named export, like using the sideEffects attribute in the package.json file.</p><p>I haven’t tested with the optimizePackageImports yet. This experimental feature tells the Next.js compiler (SWC) to “unroll” your barrel files. It allows you to write a clean import in your code, but it transforms it into a direct import during the build process.</p><p>In your next.config.ts (or .js):</p><pre>const nextConfig = {<br>  experimental: {<br>    optimizePackageImports: [&#39;@/components&#39;], // Add your directory here<br>  },<br>};</pre><p><strong>What it actually does:</strong> It intercepts your import { Button } from &#39;@/components&#39; and converts it to import { Button } from &#39;@/components/Button&#39; before the bundler even sees it. It gives you the developer experience of a barrel file with the performance of a sniper.</p><p>The barrel file also exhibits additional issues. They are the #1 cause of “Module not found” or “Undefined” errors because File A and File B both try to import from the same index.ts. Ever noticed your “Go to Definition” (Cmd+Click) takes you to an index.ts instead of the actual code?</p><p>The barrel files are generally recommended only at the boundary of your library. If you are building a library, the final index.ts can re-export the files. However, ensure you still avoid the wildcard.</p><h3>One last thing</h3><p>This remains largely uncharted territory for me. In this article, I synthesized my thoughts and shared them to stimulate curiosity. Please take everything I said with a grain of salt. You can check the <a href="https://github.com/Deepak-Kharah/blog-barrel-files-impact-on-bundle-size">repository</a>, run your own experiment, and let me know if you have any further insights.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46337ecf53ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Browser Tabs Are Strangers. Let’s Fix That Using Broadcast Channel APIs]]></title>
            <link>https://deepak-kharah.medium.com/your-browser-tabs-are-strangers-lets-fix-that-using-broadcast-channel-apis-67a2469a8612?source=rss-533e022804d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a2469a8612</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[broadcast-channel]]></category>
            <category><![CDATA[postmessage]]></category>
            <dc:creator><![CDATA[Deepak Kharah]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 18:04:32 GMT</pubDate>
            <atom:updated>2025-12-19T18:04:32.054Z</atom:updated>
            <content:encoded><![CDATA[<p>A couple of years ago, Bjørn Staal shared an experiment on his Twitter account. He created a visualization in which multiple browser windows depict the different particle spheres interacting with one another. When you move one window, it affects all the other windows.</p><figure><img alt="Entangled by Bjørn Staal: https://x.com/_nonfigurativ_/status/1727322594570027343" src="https://cdn-images-1.medium.com/max/640/1*hyp3Tp4K5kkJUFitx4MS3g.gif" /><figcaption><a href="https://x.com/_nonfigurativ_/status/1727322594570027343">https://x.com/_nonfigurativ_/status/1727322594570027343</a></figcaption></figure><p>Bjørn used Local storage to share the application state between the browser windows. When we open the devtools, we can see that the Local storage updates when we move the window or open new browser instances.</p><figure><img alt="A devtools window showcasing how Bjørn stored the window details." src="https://cdn-images-1.medium.com/max/1017/1*4iOE8gRdmXhhRdd_6HpFpw.png" /><figcaption>Here’s how the information is stored in Local Storage</figcaption></figure><p>This experiment of sharing the application state across browser windows reminded me of a time when I had to decouple a feature so that actions in one window would be reflected in the other.</p><p>The idea was to help people with dual monitors use more screen real estate for their work, rather than splitting a single window in two and cramming all the controls into one place.</p><p>So, one window served as the <strong>central hub</strong> that performed all operations, and the other window served as the recipient. When we look closely, this setup appears to be a publish-subscribe model, where I perform an action and publish it to the appropriate recipients.</p><h3>Introducing the broadcast channel</h3><p>In my situation, I found the <strong>broadcast channel to be the perfect fit</strong>. It allows communication between different windows (well, different browsing contexts and workers) on the <strong><em>same origin</em></strong>.</p><p>It acts like a public radio frequency: one window “broadcasts” a message, and every other open window tuned into that same channel name receives it instantly. Unlike WebSockets or Server-Sent Events, this communication occurs entirely on the client, making it extremely fast with zero network latency.</p><p>A simple implementation looks like this:</p><pre>// Tab 1<br>// Connect to a channel named &#39;user_sync&#39;<br>const bc = new BroadcastChannel(&#39;user_sync&#39;);<br><br>// Send a simple object or string<br>bc.postMessage({ action: &#39;logout&#39;, userId: 123 });</pre><pre>// Tab 2<br>// Connect to the same channel<br>const bc = new BroadcastChannel(&#39;user_sync&#39;);<br><br>// Listen for messages<br>bc.onmessage = (event) =&gt; {<br> console.log(&#39;Received:&#39;, event.data);<br> // Output: { action: &#39;logout&#39;, userId: 123 }<br>};</pre><h3>Here are some practical use cases of the broadcast channel</h3><p>The whole theme of the use cases is to sync the state across the browser window. These could be a great place to start if you want to practise using the broadcast channel.</p><ol><li>When we log out in one tab, we can broadcast an AUTH_LOGOUT message to instruct all other tabs to clear their state and redirect to the login page.</li><li>When we change the theme, propagate the new theme to the different windows.</li><li>Updating the cart information in an e-commerce application.</li></ol><p>These use cases sound lucrative from a user-experience perspective, where you keep all your windows in the correct state. However, bear in mind that it comes at the cost of setting up a listener and managing actions in a separate location.</p><p>Before implementing those UX improvements, take a moment to consider whether the effort and resources are worth investing in syncing.</p><h3>Security implication</h3><p>One of the crucial aspects of the Broadcast channel API is that it works across browser contexts sharing the exact same origin. So, only browser windows running applications with the same protocol, domain and port can communicate with each other.</p><p>So, although the broadcast channel APIs work like a public radio, only you can tap into that frequency. Even your own apps across different subdomains can’t receive your messages.</p><p>This behaviour makes it secure and straightforward to use, unlike the PostMessage APIs, which require a reference to all open tabs. Here, you can simply fire-and-forget. The other browser will pick up the frequency and work itself.</p><h3>Things to keep in mind before using the broadcast channel</h3><ol><li>Keep the Channel name clear and concise. I recommend using a constant object that contains all the relevant channel names. This will prevent spell errors.</li><li>Avoid using generic names like INIT. Many libraries use them, so it’s highly likely you&#39;ll trigger their listeners and cause errors. We faced this problem with the PostMessage API, but the lesson is relevant here as well.</li><li>Always check if your broadcast channel sent the event before processing it. This check is meant to avoid ending up like the second point. If another Broadcast channel instance is using the same name, you can disregard it if it is not from your expected sender. You can do it by adding a source property in the event data.</li><li>Make sure you close the channel when you are done, or when you exit the page. You can call the .close() method on the Broadcast channel API during unmount to prevent memory leaks, since browsers keep subscriptions active for extended periods.</li><li>The broadcast channel does not deliver the message to itself. So, if you have a use case where you expect the same thing to listen to the event, it won’t work.</li><li>Broadcast channel does not natively support Internet Explorer. You can still use a polyfill that achieves a similar result using the Local Storage APIs <em>(Similar to what Bjørn used).</em></li><li>Broadcast channel APIs do not support promises, and you cannot return values to the sender.</li></ol><h3>Final Act: Advanced Broadcast Message and the demo</h3><p>I built an NPM package called <a href="https://www.npmjs.com/package/advanced-broadcast-message">Advanced Broadcast Message</a> that introduces promises and return statements, and addresses considerations such as ensuring that event names do not collide across channels, among other features. A variant of this package is used in one of the products currently in production and by many major brands. You can check out our <a href="https://github.com/Deepak-Kharah/advanced-broadcast-message">GitHub repository</a> for the source code. Feel free to contribute!</p><p>I built an example app, hosted at <a href="https://inter-tab-communication.deepakkharah.com/">https://inter-tab-communication.deepakkharah.com/</a>, that showcases the power of the broadcast channel. Click the “Open in new tab” button, then go back to the previous tab and edit the form content. You’ll see the change in the new tab instantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1X0VMCreBuswPvHe5xsvw.png" /><figcaption>Demo application showcasing the inter tab communication</figcaption></figure><blockquote>NOTE: The preview beside the form also updates when we change the content, but it does not use the broadcast message. It uses the Advanced Post Message, another package I built, which is linked to the Post Robot package. I explained how it works in a React India 2023 session titled <a href="https://www.youtube.com/watch?v=PPgJ7Q4kAa8"><strong>“Nuances of Iframe: Lessons from Contentstack Live Preview.”</strong></a><strong> </strong>A <a href="https://nuances-of-iframe.deepakkharah.com/"><strong>companion site</strong></a> is available with examples for you to explore on your own.</blockquote><h3>Final words</h3><p>The Broadcast Channel API is a powerful addition to the modern web developer’s toolkit. It simplifies complex inter-tab communication, makes your application feel more cohesive, and improves the user experience by keeping all tabs in sync.</p><p>By understanding its broadcasting behaviour, security model, and best practices, you can use this API to create more robust, responsive, and engaging web applications.</p><p>Happy broadcasting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a2469a8612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In a search for a good type-safe NestJS Configuration setup.]]></title>
            <link>https://deepak-kharah.medium.com/in-a-search-for-a-good-type-safe-nestjs-configuration-setup-dd5356ca3c68?source=rss-533e022804d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd5356ca3c68</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[developer-experience]]></category>
            <dc:creator><![CDATA[Deepak Kharah]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 20:00:19 GMT</pubDate>
            <atom:updated>2025-09-29T20:00:19.383Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UEDdp3t5Zz1vw95yfpWz-A.png" /></figure><p>I have loved TypeScript ever since I was introduced to it five years ago. As of writing this article, I have developed five SDKs from scratch. Strong type safety is essential when building SDKs, and I sometimes spend hours meticulously crafting types that are dynamic enough that users appreciate them.</p><p>A year and a half ago, I was invited one day to co-lead <a href="http://contentstack.com/">Contentstack’s</a> first Marketing-Engineering collaboration project — <a href="https://contentstack.com/academy">The Academy</a>. Our Digital team handles all the marketing development. They were responsible for crafting the UI of the Academy, and my team was responsible for developing the backend.</p><p>The Academy’s backend was pretty standard — no rocket science. We used NestJS and MongoDB as our stack. While working on this project, I had one instruction for my team: ensure strong type safety throughout the project.</p><p>We did many things to improve the project’s overall type safety, including improving the configuration. Here’s how the configuration evolved during the initial development.</p><h3>Tl;dr</h3><ul><li>Create a global .d.ts file to type your environment variables.</li><li>Set the NestJS’s config module to infer the type automatically and provide autocomplete.</li><li>Generate a <a href="https://json-schema.org/">JSON schema</a> for the config JSON to enable linting and autocomplete.</li></ul><figure><img alt="SpongeBob after the work is done." src="https://cdn-images-1.medium.com/max/480/1*1Tu6W5mCQM5nXFrRX0XUow.gif" /></figure><h3>Declaring global environment variables</h3><p>When we started the project, the environment variables were trivial. Hence, we stored them in the .env file.</p><pre>PORT=3000<br>LOG_LEVEL=&#39;error&#39;</pre><p>However, when we used these environment variables in the project, our editor <em>never</em> autocompleted the keys or hinted whether they were correct.</p><figure><img alt=".env file describing the default behaviour of the code editor." src="https://cdn-images-1.medium.com/max/1024/1*7uLHIfHBoZnxaZqJWuYKQA.png" /><figcaption>A .env file describing the default behaviour of the code editor</figcaption></figure><p>Therefore, we declared them in the env.d.ts file. A .d.ts file in TypeScript is a declaration file that contains only type information. Here’s the <a href="https://www.typescriptlang.org/docs/handbook/2/type-declarations.html#dts-files">official TypeScript handbook</a> on these files.</p><pre>// src/env.d.ts<br><br>export {};<br>declare global {<br>  namespace NodeJS {<br>    interface ProcessEnv {<br>      PORT: string;<br>      LOG_LEVEL: &#39;error&#39; | &#39;log&#39; | &#39;debug&#39; | &#39;verbose&#39;<br>    }<br>  }<br>}</pre><p>Now, we have the autocomplete and the hint whether it is correct.</p><figure><img alt="A .env file with autocomplete feature after the types were added" src="https://cdn-images-1.medium.com/max/1024/1*X4PEFTtJqgB6ZrvhD-kZzQ.png" /><figcaption>A .env file with autocomplete and syntax highlighting</figcaption></figure><p>As the project progressed, the configuration became more complex and required more than the .env files. Hence, we opted for JSON files. We have created a config.json file to <strong>store the JSON</strong> and introduced NestJS’s <a href="https://docs.nestjs.com/techniques/configuration">configuration module</a> to manage it better. This is where our second part comes in.</p><h3>Infering types of the Configuration</h3><p>From here, when we talk about the config, the following will be the type:</p><pre>interface MainConfig {<br>  port: number;<br>  logLevel: &#39;error&#39; | &#39;log&#39; | &#39;debug&#39; | &#39;verbose&#39;;<br>  authentication: {<br>    superDuperSecret: string;<br>  };<br>}</pre><p>I have seen developers specify the types of configuration in the configuration service’s get() method.</p><pre>@Controller(&#39;course&#39;)<br>export class CourseController {<br>  constructor(private readonly configService: ConfigService) {}<br><br>  async getAllCourses() {<br>    const superDuperSecret = this.configService.get&lt;string&gt;(<br>      //                                             ^ Here&#39;s the line<br>      &#39;authentication.superDuperSecret&#39;,<br>    );<br><br>    return getCourses(superDuperSecret);<br>  }<br>}</pre><p>I am <strong>not</strong> a fan of this method, as we can <strong>mistakenly give it a different type</strong>, and the compiler will not complain. Also, we can easily misspell the key &#39;authentication.superDuperSecret&#39;, and the compiler won’t be triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qPm2zYSakR5YiyQ7cki2Q.png" /><figcaption>Example of the .get() method with incorrect type</figcaption></figure><p>Therefore, I love to infer it from the MainConfig instead.</p><pre>@Controller(&#39;course&#39;)<br>export class CourseController {<br>- constructor(private readonly configService: ConfigService) {}<br>+ constructor(private readonly configService: ConfigService&lt;MainConfig&gt;) {}<br><br><br>  async getAllCourses() {<br>-   const superDuperSecret = this.configService.get&lt;string&gt;(<br>+   const superDuperSecret = this.configService.get(<br>      &#39;authentication.superDuperSecret&#39;,<br>+     { infer: true },<br><br>    );<br><br>    return getCourses(superDuperSecret);<br>  }<br>}</pre><p>In this case, we won’t incorrectly type the variable, autocomplete the keys, and prevent ourselves from misspelling it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmmBpfc4EdoH7HaA281z8w.png" /><figcaption>Autocomplete is available after inference</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gAWLNNUsTJq-jYjG-UG8w.png" /><figcaption>Misspellings are visible after inference</figcaption></figure><p>The NestJS docs cover the inference part in their configuration document, yet it is not extensively used, at least in the codebases I saw.</p><h3>Introducing Schema for config.json</h3><p>When we write the config in the config.json file, the editor doesn’t help, making it prone to misspellings similar to the .env files.</p><p>At this stage, our configuration system was robust enough to allow developers to work on the backend with minimal manual setup, while also triggering a fail-safe if deployed without the proper configuration. Any misspellings or missing configurations during development would result in an error, alerting the developer. However, this wasn’t sufficient; I also wanted features like autocompletion and linting to help craft the configuration more efficiently.</p><p>This is where I noticed the package.json file. When editing it, the editor provides autocomplete and linting. I got excited and looked further, and I found the <a href="https://json-schema.org/"><strong>JSON Schema</strong></a>. In a nutshell, you can <strong>define schemas for your JSON files</strong> and tell the editor to use them when it sees specific files.</p><p>The first step was to create the schema.</p><blockquote>File: .config.schema.json</blockquote><pre>{<br>  &quot;$schema&quot;: &quot;http://json-schema.org/draft-04/schema#&quot;,<br>  &quot;title&quot;: &quot;Academy Configuration&quot;,<br>  &quot;description&quot;: &quot;The configuration for the Academy backend API.&quot;,<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;port&quot;: {<br>      &quot;description&quot;: &quot;The port on which the Academy 2.0 backend API will run.&quot;,<br>      &quot;type&quot;: &quot;integer&quot;,<br>      &quot;default&quot;: 3000<br>    },<br>    &quot;logLevel&quot;: {<br>      &quot;description&quot;: &quot;The level of logging to use.&quot;,<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;enum&quot;: [&quot;error&quot;, &quot;log&quot;, &quot;debug&quot;, &quot;verbose&quot;],<br>      &quot;default&quot;: &quot;error&quot;<br>    },<br>    &quot;authentication&quot;: {<br>      &quot;description&quot;: &quot;The authentication configuration.&quot;,<br>      &quot;type&quot;: &quot;object&quot;,<br>      &quot;properties&quot;: {<br>        &quot;superDuperSecret&quot;: {<br>          &quot;description&quot;: &quot;The super duper secret.&quot;,<br>          &quot;type&quot;: &quot;string&quot;,<br>          &quot;default&quot;: &quot;dev-super-duper-secret&quot;<br>        }<br>      },<br>      &quot;required&quot;: [&quot;superDuperSecret&quot;]<br>    }<br>  }<br>}</pre><blockquote>After I discussed this with my team, my colleague wrote the first version of the schema, and he did a great job covering all the bases.</blockquote><p>The next step was to tell my editor (VSCode or Cursor) about the file.</p><blockquote>File: .vscode/settings.json</blockquote><pre>{<br>  &quot;json.schemas&quot;: [<br>    {<br>      &quot;fileMatch&quot;: [&quot;/config.json&quot;, &quot;/config.sample.json&quot;],<br>      &quot;url&quot;: &quot;./config.schema.json&quot;<br>    }<br>  ]<br>}</pre><p>And, viola. We have autocomplete and linting in our config.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2fvDOPevfwMGsDFih8R_2A.png" /><figcaption>Autocomplete of the config.json file</figcaption></figure><p>The only <strong>flaw of this process</strong> is that we must maintain the config.schema.json and the MainConfig interface separately. It is easy to introduce a new key and forget to update it in one of the places.</p><p>Back then, I noted this and decided to revisit it in the future. However, the future never came. In all fairness, we never added or modified a key after the initial development, so the opportunity never came.</p><p>That’s all we did to improve the configuration experience. As mentioned earlier, we also made this project a <strong>low-setup project</strong> to start development quicker by having a default configuration ready that replaced the empty portions of the configuration.</p><p>Additionally, our setup ensures that the default sensitive keys never accidentally end up in production by flagging the missing configuration before the default configuration can replace it.</p><p>Strong types are not only present in the configuration. To keep this article&#39;s length in check, I’ll cover other developer experience improvements later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*5FYaxO8E5xh7IlJ-eaNiPw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd5356ca3c68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cancel Culture Comes to postMessage (And It's a Good Thing)]]></title>
            <link>https://deepak-kharah.medium.com/cancel-culture-comes-to-postmessage-and-its-a-good-thing-0d2dc75bbad1?source=rss-533e022804d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d2dc75bbad1</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[abortcontroller]]></category>
            <dc:creator><![CDATA[Deepak Kharah]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 12:32:35 GMT</pubDate>
            <atom:updated>2025-03-08T12:35:15.558Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cancel Culture Comes to Post Message (And It&#39;s a Good Thing)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeTEQHIU25N9Q5qWHU3Ezg.jpeg" /></figure><p>Recently, I stumbled upon <a href="https://kettanaito.com/blog/dont-sleep-on-abort-controller">an article on the </a><a href="https://kettanaito.com/blog/dont-sleep-on-abort-controller">AbortController API</a>, and honestly, it felt like a revelation! The idea of a standardized way to cancel asynchronous operations in JavaScript resonated with me. I started reading the documentation to learn more about it and found some interesting use cases.</p><p>You can not only cancel fetch requests but also cancel streams and even event listeners. This powerful tool can help you manage your application&#39;s resources more effectively.</p><p>I immediately started thinking about how I could apply this to my own projects and remembered about advanced-post-message.</p><p>About a year ago, I built a project called, advanced-post-message. At the time, I wanted to understand how powerful cross-origin messaging libraries post-robot worked under the hood. So, as a learning exercise, I decided to build my wrapper around the native Post Message API. You can find it on <a href="https://github.com/Deepak-Kharah/advanced-post-message/">GitHub</a>. Essentially, it provides a more structured way to send and receive post messages.</p><h3>But Why?</h3><p>Post Message API is a cornerstone for communication between different origins in web apps — think iframes, pop-up windows, and service workers, all talking to each other. It&#39;s fundamental for building modern, interactive web experiences.</p><p>But, and this is a big &quot;but&quot;, Post message communication is inherently asynchronous. It&#39;s not like making a function call and getting an immediate return value. When you send a message, it&#39;s more like <em>sending a letter in the mail</em>. You dispatch it, and you may get a reply back later. There&#39;s a delay, and things can happen in between.</p><p>Now, coming back to AbortController, it struck me that this API could be a perfect fit for enhancing advanced-post-message. Imagine being able to gracefully cancel a message you&#39;ve sent if you no longer need the response or cleanly unregister a message listener when things change. That&#39;s precisely what I set out to achieve.</p><p>For many use cases, this asynchronicity is totally fine. However, as I started thinking about it more deeply, and especially in the context of wanting to make advanced-post-message more robust, I realized there are scenarios where being able to <em>interrupt</em> or <em>cancel</em> these message flows becomes essential:</p><ul><li><strong>Timeouts and Deadlines:</strong> What if you send a message and you <em>expect</em> a response within, say 2 seconds? If that response doesn&#39;t arrive in time, you might want to give up and consider it a failure. Waiting indefinitely can be wasteful and lead to a poor user experience.</li><li><strong>User Actions and Navigation:</strong> Imagine a user interacting with a page, triggering a Post Message exchange. But then, they suddenly click a link and navigate away! Waiting for a response from the <em>previous</em> page context often becomes pointless and might cause issues if you try to process that response in the new context.</li><li><strong>Resource Optimization in Complex Apps:</strong> In larger applications with lots of message passing happening, being able to stop long-running or unnecessary message operations can actually contribute to better performance and make your app feel snappier.</li></ul><p>This is precisely where the AbortController API comes to the rescue. It gives us a standard, elegant way to signal cancellation and handle it gracefully in our asynchronous JavaScript code. And that&#39;s what I want to explore next in the context of advanced-post-message.</p><h3>Enter AbortController: A Unified Cancellation Mechanism</h3><p>The AbortController instance provides you with two components:</p><ul><li><strong>abort() method</strong>: When the user calls this method, the operation should be cancelled.</li><li><strong>signal object</strong>: This AbortSignal is what you pass to the asynchronous operation you want to make cancellable. The operation then <em>&quot;listens&quot;</em> to this signal. When abort() is called on the AbortController, the AbortSignal becomes <em>aborted</em>, and the asynchronous operation can check this status and take appropriate action to cancel itself.</li></ul><p>Let&#39;s look at a simple example, often used to illustrate AbortController – the fetch API:</p><pre>const controller = new AbortController();<br>const signal = controller.signal;<br><br>fetch(&#39;/some-api-endpoint&#39;, { signal }) // Pass the signal to fetch<br>  .then(response =&gt; {<br>    if (!response.ok) {<br>      throw new Error(`HTTP error! status: ${response.status}`);<br>    }<br>    return response.json();<br>  })<br>  .then(data =&gt; {<br>    console.log(&#39;Data fetched:&#39;, data);<br>  })<br>  .catch(error =&gt; {<br>    if (error.name === &#39;AbortError&#39;) {<br>      console.log(&#39;Fetch operation was aborted&#39;);<br>    } else {<br>      console.error(&#39;Fetch error:&#39;, error);<br>    }<br>  });<br><br>// To abort the fetch request after 5 seconds (for example):<br>setTimeout(() =&gt; {<br>  controller.abort(); // Signal the abort<br>  console.log(&#39;Fetch aborted after 5 seconds&#39;);<br>}, 5000);</pre><p>In this example:</p><ol><li>We create an AbortController.</li><li>We get its signal and pass it as an option to the fetch request.</li><li>The fetch API is now associated with this signal. If the signal is aborted, fetch will reject its promise with an AbortError.</li><li>We use setTimeout to simulate a condition where we might want to abort the request (e.g., a timeout). After 5 seconds, we call controller.abort().</li><li>In the .catch() block, we check if the error is an AbortError. If it is, we know the fetch was aborted intentionally.</li></ol><p>This pattern — create an AbortController, get the signal, pass it to the asynchronous operation, and call abort() when needed – is the core of how AbortController works. Now, let&#39;s see how we can apply this to our advanced-post-message project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XRNBOecNViBq1rtl7EqBA.jpeg" /><figcaption>Let’s start implementing!</figcaption></figure><h3>Implementing Cancellable send in advanced-post-message</h3><p>Looking at the send method, the first thing you might notice is that it now accepts an optional options parameter, which can include an AbortSignal:</p><pre>async send&lt;ReturnType = undefined&gt;(<br>    type: string,<br>    payload?: any,<br>    options: Partial&lt;EventManagerSendOptions&gt; = {}<br>  ) {<br>    const { signal } = options;<br>    // ... rest of the send method</pre><p>The key to cancellation lies in how we handle this signal. Within the send method, we first check if the signal is already aborted right at the beginning:</p><pre>if (signal?.aborted) {<br>      cancelEvent(); // Immediately cancel if already aborted<br>    } else {<br>      signal.addEventListener(&quot;abort&quot;, cancelEvent, {<br>        signal: cancelledCallbackController.signal,<br>      }); // Add abort listener<br>    }</pre><p>If the signal is already in the aborted state when send is called, we immediately trigger the cancelEvent function. Otherwise, we attach an event listener to the signal that will also call cancelEvent when the signal <em>does</em> get aborted later.</p><blockquote>You might be wondering about cancelledCallbackController.signal. In this implementation, a separate AbortController (cancelledCallbackController) is used specifically to manage the lifecycle of the abort event listener itself.</blockquote><blockquote><strong>The reason for this is to ensure explicit and reliable cleanup of this event listener.</strong> While modern JavaScript environments often handle garbage collection efficiently, especially for event listeners attached with signals, using cancelledCallbackController provides an extra layer of certainty.</blockquote><blockquote><strong>By associating the </strong><strong>abort event listener with the signal, you gain explicit control over its lifecycle.</strong> When the send operation&#39;s promise is finalized (either resolved or rejected), cancelledCallbackController.abort() is called in the finally block. This abort() call signals to the abort event listener (attached to the original signal) that it too should be cleaned up.</blockquote><blockquote>This proactive cleanup approach ensures that even after the send operation completes, there are no lingering event listeners associated with it, contributing to better resource management and preventing potential memory leaks, especially in scenarios where send might be called frequently in long-running applications.</blockquote><p>The cancelEvent function itself is straightforward:</p><pre>function cancelEvent() {<br>    responseListener.hasCancelled = true;<br>}</pre><p>It sets a flag, responseListener.hasCancelled, to true. This flag is then checked within an interval timer that is set up in the send method:</p><pre>const interval = safeInterval(() =&gt; {<br>      // ... other checks ...<br>      if (responseListener.hasCancelled) {<br>        return promise.reject(<br>          new DOMException(<br>            getErrorMessage(ERROR_MESSAGES.sendEvent.eventCancelled),<br>            &quot;AbortError&quot; // Reject with DOMException and AbortError name<br>          )<br>        );<br>      }<br>      // ... rest of interval logic ...<br>    }, RESPONSE_CYCLE);</pre><p>Within this interval, if responseListener.hasCancelled is true, the promise associated with the send operation is now rejected with a DOMException.</p><p>Significantly, we&#39;ve updated the code to reject with a DOMException and set its name property to &quot;AbortError&quot;. This is the standard error type used by APIs like fetch when an operation is aborted via AbortController.</p><p>This makes your send method&#39;s cancellation behaviour consistent with built-in browser APIs, which is excellent for predictability and developer experience.</p><p>Finally, in the finally block of the promise, we ensure comprehensive cleanup:</p><pre>promise<br>  .finally(() =&gt; {<br>  this.responseMessageHandlers.delete(hash);<br>  cancelledCallbackController.abort();<br>  interval.cancel();<br>  // ... error logging in .catch() ...<br>})</pre><p>This finally block is crucial for resource management. It ensures that regardless of whether the promise resolves successfully or is rejected (due to cancellation, timeout, or other errors), several cleanup actions are taken: the response handler is removed, the interval timer is stopped, and the cancelledCallbackController is aborted.</p><p>This last step, aborting cancelledCallbackController, is the key to explicitly cleaning up the abort event listener, we added to the main signal earlier.</p><h3>Implementing Cancellable on in advanced-post-message</h3><p>The on method in advanced-post-message is all about setting up listeners to handle incoming messages. Now, when I was thinking about making the on method cancellable with AbortController, I realized I wanted it to behave <em>just like</em> native browser event listeners when they are used with signals.</p><p>If you use an AbortSignal with window.addEventListener for, say, a &#39;click&#39; event, and then you abort that signal, the browser automatically removes the click listener! This is clean and intuitive, and I wanted to replicate this exact behaviour for message listeners in advanced-post-message. It makes the API consistent and easier to understand for anyone familiar with standard DOM event handling.</p><p>To achieve this, we can leverage the addEventListener options. In fact, the addEventListener method itself <em>supports</em> the AbortSignal option!</p><p>Here&#39;s how the cancellable on method is implemented in advanced-post-message:</p><pre>on&lt;Payload = unknown, ReturnType = any&gt;(<br>    type: string,<br>    handler: RequestHandler&lt;Payload, ReturnType&gt;,<br>    options: Partial&lt;EventManagerOnOptions&gt; = {}<br>  ) {<br>    const { signal } = options;<br>    // ... (Error check for duplicate registration) ...<br>    const requestListener: RequestListener = {<br>      handler,<br>    };<br>    this.requestMessageHandlers.set(type, requestListener);<br><br>    if (signal) {<br>      signal.addEventListener(&quot;abort&quot;, () =&gt; {<br>        this.unregisterEvent(type); // Call custom unregister logic on abort<br>      });<br>    }<br>    return {<br>      unregister: () =&gt; {<br>        this.unregisterEvent(type); // Manual unregistration function<br>      },<br>    };<br>  }</pre><p>In this, theon method:</p><ol><li><strong>Accepts </strong><strong>AbortSignal in Options:</strong> Like the send method, on accepts an optional signal within the options parameter.</li><li><strong>Registers a Request Handler:</strong> The core purpose of on is to register a handler for a specific messageType. This handler is stored in this.requestMessageHandlers (a detail of the EventManager class).</li><li><strong>Signal-Driven Unregistration:</strong> If an AbortSignal is provided, we attach an abort event listener to it. When the signal is aborted, this listener is triggered, and it calls this.unregisterEvent(type).</li><li><strong>Manual Unregistration Function:</strong> The on method also returns an unregister function. Calling this function also executes this.unregisterEvent(type), allowing for manual, programmatic unregistration of the handler, independent of any AbortSignal.</li></ol><h3>Conclusion: Embracing AbortController for Controlled Asynchronous Communication</h3><p>Integrating AbortController into advanced-post-message was an insightful experience for me. It demonstrated how this relatively simple yet powerful API can bring a significant level of control to asynchronous operations. In this case, window.postMessage communication.</p><p>By making both the send and on methods cancellable, advanced-post-message becomes a more robust and flexible library for managing cross-origin messaging. The ability to cancel message sending and cleanly unregister message listeners is not just about code elegance; it translates to real benefits regarding resource management, error handling, and overall application responsiveness.</p><p>If you are working on web applications that involve significant cross-origin communication or if you&#39;re building libraries that abstract the postMessage API, I highly encourage you to explore the AbortController API. As you&#39;ve seen in this example with advanced-post-message, it can be a valuable tool for creating more manageable and efficient asynchronous workflows.</p><p>Feel free to dive into the code of advanced-post-message on <a href="https://github.com/Deepak-Kharah/advanced-post-message/">GitHub</a> to see the full implementation and experiment with cancellable post messaging yourself. Happy coding!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOrXozCyJ6TXR0vf4uHSiw.jpeg" /><figcaption>Till next time!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d2dc75bbad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shipping JS SDK in the development environment]]></title>
            <link>https://deepak-kharah.medium.com/shipping-js-sdk-in-the-development-environment-aa0642f03b02?source=rss-533e022804d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0642f03b02</guid>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Deepak Kharah]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 14:00:08 GMT</pubDate>
            <atom:updated>2024-02-11T14:09:45.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dzra6xQtIEyhZQ3sTtyW5A.png" /></figure><p>Developing and shipping an SDK is slightly different from a full-fledged web app. You can spin up a development server with a hot module replacement, and you will have an app that reflects your live changes. Once you are happy with your changes, you can upload them to a dev server, where your peers can review the changes, and finally, you can upload them to production.</p><p>However, the SDKs do not work independently. A web app or other library must consume it to work. Hence, you’ll need an additional project to consume your SDK during the development. This article will explore how we ship the SDK in different environments so your app can consume it quickly.</p><p>This article is for freelancers or developers starting their development journey and developing a JS SDK for the first time. So, let’s dive in.</p><blockquote>Tl;dr: Use npm intall to work locally, have a prepare script that runs your build script, and use GitHub branches or GitHub private packages to share the SDK with your peers without pushing it to NPM.</blockquote><p>If you want to follow along, go to <a href="https://github.com/Deepak-Kharah/blog-ship-sdk-in-different-env">https://github.com/Deepak-Kharah/blog-ship-sdk-in-different-env</a> and <a href="https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository">clone it</a>.</p><p>Once cloned, you will see two folders: <strong>simple-star-wars-sdk</strong> and <strong>simple-star-wars-ui</strong>. Open this folder in your favorite code editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*_pck4t_AEGrwrEgNOWGEJA.png" /><figcaption>Folder structure of the simple-star-wars</figcaption></figure><p>Now, open these two folders in two separate terminals and Switch the branch to <strong>01-start-from-here</strong>.</p><pre>git switch 01-start-from-here</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCDG7QrzatpZ-vphkfYZmA.png" /><figcaption>Two instances of a terminal with two folders</figcaption></figure><p>Install the dependencies using the npm install command and run the server using npm run dev command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6PCoGW9F2zUM5hOgfKmsA.png" /><figcaption>Build successful message</figcaption></figure><p>Open <a href="http://localhost:3000/">http://localhost:3000/</a>, and you will see your application running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v4-sjMSeqtQXGwFf-DH41A.png" /><figcaption>Simple Star Wars character directory</figcaption></figure><p>However, clicking on any card will not fetch the character’s details and will show <strong>Classified</strong> instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-Eh9EE1Jj2HnHBg44-wUA.png" /><figcaption>Simple Star Wars character detail page</figcaption></figure><p>We will fix this error by the end of this article by modifying the code only in the <strong>SDK folder</strong>.</p><h3>Local development</h3><p>We want to update the SDK to fetch the character details. Open the <em>simple-star-wars-sdk/src/index.js</em> in your text editor. The <strong>line 21</strong> shows you what you need to update to fix the code.</p><p>However, before that, let’s prepare your development environment to see the changes in real time.</p><p>Stop both terminals by pressing ctrl+c. In the SDK’s terminal, run the pwd command. It will show you the current working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*jbsSKzjPJ7-ljGk2l4LYuQ.png" /><figcaption>The output of the pwd command</figcaption></figure><p>Copy the output and run the npm i &lt;pwd-path&gt; command in the UI’s terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*9C3AGwGe9iIx78kCDy5qeQ.png" /></figure><p>This will create a <a href="https://en.wikipedia.org/wiki/Symbolic_link"><strong>symlink</strong></a><strong> of the SDK</strong> in the UI. When you turn your servers back, you will see the changes in the SDK reflected in the UI automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*75vrkyS8bboXOLKSK6nSBA.png" /><figcaption>simple-star-wars-ui/package.json</figcaption></figure><p>Let’s open the <em>simple-star-wars-sdk/src/index.js </em>file back and fix the code.</p><pre>...<br>  static async getCharacter(id) {<br>    return fetch(`https://swapi.dev/api/people/${id}`)<br>      .then((response) =&gt; response.json())<br>-     .then((data) =&gt; ({}));<br>+     .then((data) =&gt; data);<br>  }<br>...</pre><p>Once you fix it, you’ll see the UI update and fetch the correct data automatically without reloading the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUGQ59hCVZBfDqsEvpiagg.png" /><figcaption>Working Star Wars detail page</figcaption></figure><p>You will find the code here in the <a href="https://github.com/Deepak-Kharah/blog-ship-sdk-in-different-env/tree/02-local-development-complete">02-local-development-complete branch</a>.</p><h3>Shared development</h3><p>Once your development is completed, you will push your changes to a branch where your peer will pull them and use them to review. Alternatively, once your SDK is updated, the other team may use it in their UI. Since the product is still under development, you cannot publish your SDK in the NPM registry. Hence, you’ll need an alternative method to share the SDK with your peers.</p><p>There are two methods I use when I develop SDKs. The first is <strong>installing the GitHub branches</strong> directly, and the second is <strong>using private packages</strong>.</p><p>Before we explore the methods, let’s prepare our SDK to handle it. If you start directly from this section, you can use the <a href="https://github.com/Deepak-Kharah/blog-ship-sdk-in-different-env/tree/02-local-development-complete">02-local-development-complete branch</a> to follow along.</p><p>You had to build your SDK manually to use in the UI at this stage. We did it by running the npm run dev command. In this scenario, we must push the <em>dist/</em> files in GitHub.</p><p>Here’s where the problem lies. You are bloating your Git history by keeping the <em>dist/</em> files, and if you forgot to build before pushing, you will have an outdated SDK.</p><p>To solve this, we will use the prepare script in the <em>package.json.</em> The prepare script runs when a user installs our package and some other times. You can learn more about the <a href="https://docs.npmjs.com/cli/v9/using-npm/scripts#prepare-and-prepublish">prepare script</a> from the NPM documentation.</p><p>Open <em>simple-star-wars-sdk/package.json</em> and add the prepare script to run the build command.</p><pre>...<br>  &quot;scripts&quot;: {<br>+   &quot;prepare&quot;: &quot;npm run build&quot;,<br>    &quot;build&quot;: &quot;parcel build&quot;,<br>    &quot;test&quot;: &quot;npm run test&quot;,<br>    &quot;dev&quot;: &quot;parcel watch&quot;<br>  },<br>...</pre><p>You can test it by deleting the <em>simple-star-wars-sdk/dist</em> folder and installing the SDK back in the UI. It should generate the <em>dist/</em> folder again. Push your changes to GitHub for the next steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*KIFy23QIbcCpnjqVttIMAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*Hg-nemyaFwodZtR3YF-3zA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*gBgVDuqCIK_-rbJl3E88tA.png" /><figcaption>Re-installing the SDK generates the dist/ folder.</figcaption></figure><p>The code changes are available in the <a href="https://github.com/Deepak-Kharah/blog-ship-sdk-in-different-env/tree/03-1-shared-development">03–1-shared-development</a> branch.</p><h4>Using GitHub branches to share the SDK</h4><p>You can specify a GitHub branch directly to the <em>package.json, </em>which will be installed from it.</p><p>Here’s the format</p><pre>...<br>  &quot;dependencies&quot;: {<br>    ...<br>    &quot;simple-star-wars-sdk&quot;: &quot;github:&lt;owner&gt;/&lt;repository&gt;/#&lt;branch&gt;&quot;<br>  },<br>...</pre><p>Or you can use the npm command like this:</p><pre>npm install &quot;https://github.com/&lt;owner&gt;/&lt;repository&gt;.git#&lt;branch&gt;&quot;</pre><blockquote><strong>Please note:</strong> Until today, while I am drafting this article there is no native way to npm install a GitHub subfolder. You can use <a href="https://gitpkg.vercel.app/about/">https://gitpkg.vercel.app/about/</a> for installing the sub folders.</blockquote><p>This will build your project and install it for others to use.</p><h4>Using private packages</h4><p>You can share your private repository with the GitHub package manager if your repository is private.</p><p>You have to <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens">create an access token (classic)</a> with the scope of read:packages and use it to publish the package. The <a href="https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-npm-registry">GitHub’s documentation</a> covers using the NPM registry with GitHub packages. Hence, I won’t be going in-depth about using it here.</p><p>Alternatively, you can publish using the --tag to mark a release as <em>alpha</em> or <em>beta</em>. This will allow you to push your changes to the NPM without affecting the mass users. They can install it if they opt-in.</p><p>Let me know if you know other ways to build and share SDKs during development. I’ll see you soon. Till then, have a great day. ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0642f03b02" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>