<?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 Rajat on Medium]]></title>
        <description><![CDATA[Stories by Rajat on Medium]]></description>
        <link>https://medium.com/@codewithrajat?source=rss-f0de257e3ede------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rVwkHCMttWJXq09Jc1-iGg.jpeg</url>
            <title>Stories by Rajat on Medium</title>
            <link>https://medium.com/@codewithrajat?source=rss-f0de257e3ede------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:46:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codewithrajat/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[Front End Observability: Why Your window.onerror Reports Say “Script error.” (and How to Fix Them)]]></title>
            <link>https://javascript.plainenglish.io/front-end-observability-why-your-window-onerror-reports-say-script-error-and-how-to-fix-them-38f605056563?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/38f605056563</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 17:35:14 GMT</pubDate>
            <atom:updated>2026-11-10T17:35:14.902Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A practical guide to browser error monitoring with window.onerror, covering the cross-origin blind spot, resource failures that never bubble, and error reports that die when the tab closes. Includes tests and Angular wiring.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9xuhg0MV-TNdAjAnmTajw.jpeg" /></figure><p>It’s late on a Friday. Support forwards a screenshot: a customer’s checkout page is blank. You open your error dashboard, and there it is, forty times since lunch:</p><pre>Script error.<br>  at  (line 0, column 0)</pre><p>No file, no stack, no line. Just a message that tells you nothing.</p><p>You have window.onerror wired up. You followed a tutorial. So why is the one thing you needed missing?</p><p>If you want more write-ups on browser error monitoring and front end observability, follow me here on Medium. I publish practical, copy-pasteable pieces like this one every week.</p><p>By the end of this article you will know exactly what window.onerror hands you and what it hides. You will build a small, tested error monitor in TypeScript that catches runtime errors, failed resources, and rejected promises, and delivers them reliably. And you will find out why that dashboard shows line 0.</p><p>Keep that line 0 question in mind. We’ll answer it near the end.</p><h3>Why does window.onerror give you so little?</h3><p>Before touching code, let’s set up the problem. Browsers expose three separate failure channels, and most tutorials only cover one.</p><p>Per <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event">MDN’s documentation for the Window error event</a>, the error event fires on window when a resource fails to load or can&#39;t be used, for example when a script throws. MDN also notes that it only fires for script errors thrown synchronously, such as during initial load or inside event handlers. A rejected promise with no handler fires a different event, unhandledrejection.</p><p>Here’s the map:</p><pre>Failure                          What you listen for<br>-------------------------------  -------------------------------------<br>Sync exception (script/handler)  window &quot;error&quot;  (ErrorEvent)<br>Failed &lt;img&gt;/&lt;script&gt;/&lt;link&gt;     &quot;error&quot; in CAPTURE phase (plain Event)<br>Unhandled promise rejection      window &quot;unhandledrejection&quot;</pre><p>If you only set window.onerror, you cover the first row and nothing else. And as you&#39;ll see, even that row has traps.</p><blockquote><em>Before we get into the examples, a quick note: The code snippets provided here are meant purely for understanding the concept</em></blockquote><p>Next up: the version of this that almost every project starts with, and why it quietly fails.</p><h3>What does a basic window.onerror handler actually receive?</h3><p><strong>Quick version (beginner)</strong></p><p>window.onerror takes a function with five arguments. Here is the classic setup:</p><pre>// src/naive-monitor.ts<br>window.onerror = (message, source, lineno, colno, error) =&gt; {<br>  void fetch(&#39;/api/errors&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify({ message, source, lineno, colno }),<br>  });<br>};</pre><pre>export {};</pre><p>Trigger an error from your app:</p><pre>// src/main.ts<br>import &#39;./naive-monitor&#39;;</pre><pre>const user = JSON.parse(&#39;{}&#39;) as { profile?: { name: string } };<br>console.log(user.profile!.name);</pre><p>In Chrome, your endpoint receives something like this:</p><pre>{<br>  &quot;message&quot;: &quot;Uncaught TypeError: Cannot read properties of undefined (reading &#39;name&#39;)&quot;,<br>  &quot;source&quot;: &quot;&lt;http://localhost:5173/src/main.ts&gt;&quot;,<br>  &quot;lineno&quot;: 4,<br>  &quot;colno&quot;: 22<br>}</pre><p>Message text varies by browser, and so does the exact line and column in bundled code. That works. It runs. It also has four problems.</p><p><strong>Real-world version (pitfalls)</strong></p><ol><li><strong>It’s a single slot.</strong> Assigning window.onerror replaces whatever was there. If a third-party widget or another monitoring script installed a handler first, you just deleted it. If one installs after you, it deletes yours.</li><li><strong>No stack.</strong> You sent the first four arguments and dropped error, which usually holds the Error object and its stack.</li><li><strong>fetch during page teardown can be cancelled.</strong> Errors that happen as the user leaves are exactly the ones you lose.</li><li><strong>Resource failures and promise rejections are invisible.</strong> A 404 on a script or an unhandled await never reaches this handler.</li></ol><p>There’s a fifth trap that bites people who copy handlers from old snippets. MDN documents that for onerror on Window, returning true cancels the default behavior, so the error won&#39;t appear in the console, though the current script still stops executing. A handler that ends with return true makes development miserable because your own errors vanish from DevTools.</p><p><strong>Under the hood (internals, trade-offs)</strong></p><p>MDN notes that onerror on Window and WorkerGlobalScope is the only event handler property that receives more than one argument, for historical reasons. That asymmetry only applies to the property. If you use addEventListener(&#39;error&#39;, ...), you get a single ErrorEvent object whose properties (message, filename, lineno, colno, error) match those five arguments. The return-true rule does not apply there either.</p><p>That’s the first reason I’d pick addEventListener every time: it composes with other code, and it has one argument shape.</p><p>Have you ever shipped a global handler and discovered months later that another script had overwritten it? Tell me what happened in the comments, I’m collecting war stories.</p><p>So why was your dashboard stuck on “Script error.”? That’s the failed first attempt, and it’s next.</p><h3>Why does the message say “Script error.” with line 0?</h3><p><strong>Quick version (beginner)</strong></p><p>When a script from a different origin throws, the browser deliberately hides the details from your handler. It does this so a page can’t peek at error text from another site’s code. You get a generic message and zeroed location.</p><p>Here is a page that reproduces it. Save it as index.html:</p><pre>&lt;!-- index.html --&gt;<br>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;Cross-origin error demo&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script&gt;<br>      window.addEventListener(&#39;error&#39;, (event) =&gt; {<br>        console.log(JSON.stringify({<br>          message: event.message,<br>          filename: event.filename,<br>          lineno: event.lineno,<br>          colno: event.colno,<br>          hasError: event.error !== null,<br>        }));<br>      });<br>    &lt;/script&gt;<br>    &lt;script src=&quot;&lt;http://localhost:4000/widget.js&gt;&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Serve widget.js from a second origin (a different port counts) with a line like null.boom; in it. The console prints:</p><pre>{&quot;message&quot;:&quot;Script error.&quot;,&quot;filename&quot;:&quot;&quot;,&quot;lineno&quot;:0,&quot;colno&quot;:0,&quot;hasError&quot;:false}</pre><p>That’s your line 0.</p><p><strong>Real-world version (pitfalls)</strong></p><p>The fix needs both sides to cooperate. The script tag needs the crossorigin attribute, and the server hosting the script must answer with a matching CORS header.</p><pre>&lt;!-- index.html (changed line only matters: crossorigin) --&gt;<br>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;Cross-origin error demo&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;script&gt;<br>      window.addEventListener(&#39;error&#39;, (event) =&gt; {<br>        console.log(JSON.stringify({<br>          message: event.message,<br>          filename: event.filename,<br>          lineno: event.lineno,<br>          colno: event.colno,<br>          hasError: event.error !== null,<br>        }));<br>      });<br>    &lt;/script&gt;<br>    &lt;script src=&quot;&lt;http://localhost:4000/widget.js&gt;&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And the response header on the CDN or asset server:</p><pre>Access-Control-Allow-Origin: *</pre><p>Now the output becomes:</p><pre>{&quot;message&quot;:&quot;Uncaught TypeError: Cannot read properties of null (reading &#39;boom&#39;)&quot;,&quot;filename&quot;:&quot;&lt;http://localhost:4000/widget.js&quot;,&quot;lineno&quot;:1,&quot;colno&quot;:6,&quot;hasError&gt;&quot;:true}</pre><p>The classic pitfall: you add crossorigin but the CDN doesn&#39;t send the header. In that case the browser refuses to load the script at all, which is worse than a vague error. Roll it out with your CDN config first, then the attribute.</p><p>The <a href="https://blog.sentry.io/client-javascript-reporting-window-onerror/">Sentry write-up on reporting window.onerror</a> covers this same cross-origin behavior and is a good companion read.</p><p><strong>Under the hood (internals, trade-offs)</strong></p><p>The browser treats the error as “muted” when the script isn’t same-origin or CORS-approved. It’s a privacy rule, not a bug, so there’s nothing a handler can do after the fact. The only fix is at the delivery layer: serve your own bundles from the same origin, or serve them with CORS enabled and mark the tags with crossorigin.</p><p>Third-party scripts you don’t control (ad tags, chat widgets) will stay muted unless their vendor sends CORS headers. Decide whether you want to filter those out of your dashboards, because “Script error.” with no location is unactionable noise. I would drop them or tag them as low priority rather than alert on them.</p><p>That explains the screenshot. But fixing it leaves a lot of failures still unseen. Let’s rebuild the monitor.</p><h3>How do you catch resource errors and rejected promises too?</h3><p><strong>Quick version (beginner)</strong></p><p>Use addEventListener for runtime errors, pass true as the third argument to catch resource errors, and add a separate unhandledrejection listener. This version is small and complete:</p><pre>// src/monitor-v2.ts<br>const post = (data: Record&lt;string, unknown&gt;): void =&gt; {<br>  navigator.sendBeacon(<br>    &#39;/api/errors&#39;,<br>    JSON.stringify({ ...data, pageUrl: location.href }),<br>  );<br>};<br><br><br>window.addEventListener(<br>  &#39;error&#39;,<br>  (event) =&gt; {<br>    if (event instanceof ErrorEvent) {<br>      post({<br>        kind: &#39;runtime&#39;,<br>        message: event.message,<br>        source: event.filename,<br>        lineno: event.lineno,<br>        colno: event.colno,<br>        stack: event.error?.stack,<br>      });<br>    } else if (event.target instanceof HTMLElement) {<br>      post({<br>        kind: &#39;resource&#39;,<br>        tag: event.target.tagName,<br>        src: event.target.getAttribute(&#39;src&#39;),<br>      });<br>    }<br>  },<br>  true,<br>);<br>window.addEventListener(&#39;unhandledrejection&#39;, (event) =&gt; {<br>  post({ kind: &#39;promise&#39;, message: String(event.reason) });<br>});<br>export {};</pre><p>Add a broken image and a floating promise to a test page:</p><pre>&lt;img src=&quot;/missing.png&quot; alt=&quot;&quot; /&gt;<br>&lt;script type=&quot;module&quot;&gt;<br>  import &#39;./src/monitor-v2.ts&#39;;<br>  Promise.reject(new Error(&#39;payment API timed out&#39;));<br>&lt;/script&gt;</pre><p>Your endpoint receives, among others:</p><pre>{&quot;kind&quot;:&quot;resource&quot;,&quot;tag&quot;:&quot;IMG&quot;,&quot;src&quot;:&quot;/missing.png&quot;,&quot;pageUrl&quot;:&quot;&lt;http://localhost:5173/&gt;&quot;}<br>{&quot;kind&quot;:&quot;promise&quot;,&quot;message&quot;:&quot;Error: payment API timed out&quot;,&quot;pageUrl&quot;:&quot;&lt;http://localhost:5173/&gt;&quot;}</pre><p><strong>Real-world version (pitfalls)</strong></p><p>Why the true? Resource load failures fire an error event on the element itself, and that event doesn&#39;t bubble. Your window listener would never see it in the bubbling phase. The capture phase runs on the way down, before the target, so a capturing listener on window sees every element&#39;s error event. MDN also says the event is an ErrorEvent for script errors and a plain Event otherwise, which is why the code branches on instanceof ErrorEvent.</p><p>Here’s what most developers get wrong: they log event.reason as-is. A rejection reason can be anything, a string, an object, undefined. Always check instanceof Error before reading .stack.</p><p><strong>Under the hood (internals, trade-offs)</strong></p><p>Capture-phase listeners on window also see errors that other code already handled with try/catch? No. A caught exception never becomes an error event, so you only see what the page failed to handle. Resource errors are different: there&#39;s no try/catch around an &lt;img&gt;, so every failed image, script, and stylesheet reports. That can be loud. A single bad CDN path across a list of 200 thumbnails produces 200 events, which is why the next step matters.</p><p>Notice the trade-off: catching more means collecting more, and more means cost and noise. Next we add guard rails.</p><h3>How do you make window.onerror monitoring safe for production?</h3><p><strong>Quick version (beginner)</strong></p><p>Three things turn a toy into something you can ship: deduplicate repeats, cap reports per session, and never let the reporter itself throw. Here’s the full module:</p><pre>// src/error-monitor.ts<br>export type ReportKind = &#39;runtime&#39; | &#39;resource&#39; | &#39;promise&#39;;<br><br><br>export interface ErrorReport {<br>  kind: ReportKind;<br>  message: string;<br>  source?: string;<br>  lineno?: number;<br>  colno?: number;<br>  stack?: string;<br>  pageUrl: string;<br>  userAgent: string;<br>  release: string;<br>  timestamp: number;<br>}<br>type PartialReport = Pick&lt;ErrorReport, &#39;kind&#39; | &#39;message&#39;&gt; &amp;<br>  Partial&lt;Omit&lt;ErrorReport, &#39;kind&#39; | &#39;message&#39;&gt;&gt;;<br>export interface MonitorOptions {<br>  endpoint: string;<br>  release: string;<br>  maxReportsPerSession?: number;<br>  send?: (endpoint: string, body: string) =&gt; void;<br>  target?: EventTarget;<br>}<br>export interface ErrorMonitor {<br>  reportError: (error: unknown) =&gt; void;<br>  uninstall: () =&gt; void;<br>}<br>export function defaultSend(endpoint: string, body: string): void {<br>  const blob = new Blob([body], { type: &#39;application/json&#39; });<br>  if (typeof navigator.sendBeacon === &#39;function&#39; &amp;&amp; navigator.sendBeacon(endpoint, blob)) {<br>    return;<br>  }<br>  void fetch(endpoint, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body,<br>    keepalive: true,<br>  }).catch(() =&gt; undefined);<br>}<br>export function installErrorMonitor(options: MonitorOptions): ErrorMonitor {<br>  const send = options.send ?? defaultSend;<br>  const limit = options.maxReportsPerSession ?? 20;<br>  const target: EventTarget = options.target ?? window;<br>  const seen = new Set&lt;string&gt;();<br>  let count = 0;<br>  let reporting = false;<br>  const report = (partial: PartialReport): void =&gt; {<br>    if (reporting || count &gt;= limit) return;<br>    const key = [<br>      partial.kind,<br>      partial.message,<br>      partial.source ?? &#39;&#39;,<br>      partial.lineno ?? 0,<br>      partial.colno ?? 0,<br>    ].join(&#39;|&#39;);<br>    if (seen.has(key)) return;<br>    seen.add(key);<br>    reporting = true;<br>    try {<br>      count += 1;<br>      const payload: ErrorReport = {<br>        ...partial,<br>        pageUrl: location.href,<br>        userAgent: navigator.userAgent,<br>        release: options.release,<br>        timestamp: Date.now(),<br>      };<br>      send(options.endpoint, JSON.stringify(payload));<br>    } catch {<br>      // The reporter must never throw, or it would report itself forever.<br>    } finally {<br>      reporting = false;<br>    }<br>  };<br>  const reportError = (error: unknown): void =&gt; {<br>    report({<br>      kind: &#39;runtime&#39;,<br>      message: error instanceof Error ? error.message : String(error),<br>      stack: error instanceof Error ? error.stack : undefined,<br>    });<br>  };<br>  const onError = (event: Event): void =&gt; {<br>    if (event instanceof ErrorEvent) {<br>      const error: unknown = event.error;<br>      report({<br>        kind: &#39;runtime&#39;,<br>        message: event.message,<br>        source: event.filename,<br>        lineno: event.lineno,<br>        colno: event.colno,<br>        stack: error instanceof Error ? error.stack : undefined,<br>      });<br>      return;<br>    }<br>    const el = event.target;<br>    if (el instanceof HTMLElement) {<br>      report({<br>        kind: &#39;resource&#39;,<br>        message: `Failed to load &lt;${el.tagName.toLowerCase()}&gt;`,<br>        source: el.getAttribute(&#39;src&#39;) ?? el.getAttribute(&#39;href&#39;) ?? undefined,<br>      });<br>    }<br>  };<br>  const onRejection = (event: PromiseRejectionEvent): void =&gt; {<br>    const reason: unknown = event.reason;<br>    report({<br>      kind: &#39;promise&#39;,<br>      message: reason instanceof Error ? reason.message : String(reason),<br>      stack: reason instanceof Error ? reason.stack : undefined,<br>    });<br>  };<br>  target.addEventListener(&#39;error&#39;, onError as EventListener, true);<br>  target.addEventListener(&#39;unhandledrejection&#39;, onRejection as EventListener);<br>  return {<br>    reportError,<br>    uninstall: () =&gt; {<br>      target.removeEventListener(&#39;error&#39;, onError as EventListener, true);<br>      target.removeEventListener(&#39;unhandledrejection&#39;, onRejection as EventListener);<br>    },<br>  };<br>}</pre><p>Use it from your entry file:</p><pre>// src/main.ts<br>import { installErrorMonitor } from &#39;./error-monitor&#39;;</pre><pre>installErrorMonitor({ endpoint: &#39;/api/errors&#39;, release: &#39;1.0.0&#39; });</pre><p><strong>Real-world version (pitfalls)</strong></p><p>Each guard rail earns its place:</p><ul><li><strong>The </strong><strong>reporting flag</strong> stops recursion. If building or sending a report throws, that exception would fire another error event, which calls the reporter again. Without the flag you can melt a tab.</li><li><strong>The dedupe key</strong> collapses the 200 broken thumbnails into one report. The trade-off is that you lose counts. If you need “how many users hit this”, count on the server by key, or send the count with the first report.</li><li><strong>The session cap</strong> protects your endpoint from a render loop that throws 60 times a second.</li><li><strong>release</strong> is the field you&#39;ll thank yourself for. Without it you can&#39;t tell whether yesterday&#39;s fix worked.</li></ul><p><strong>Under the hood (internals, trade-offs)</strong></p><p>Why sendBeacon first? The browser queues a beacon so it survives page unload, which is when fetch often gets cancelled. When sendBeacon returns false (queue full) or doesn&#39;t exist, the fallback is fetch with keepalive: true, which has the same survive-unload intent. One caveat: a beacon with a JSON Blob type sent to another origin triggers a CORS preflight. Keep your error endpoint same-origin, or set up CORS on it.</p><p>The target option exists for one reason: testing. We&#39;ll use it in a moment.</p><p>Here’s a quick pause: have you ever been unable to reproduce a production error because the report arrived without a stack or release tag? What was the one missing field that would have saved you? Reply in the comments, I read them all.</p><p>Next teaser: how do you prove this thing works without breaking your own test runner?</p><h3>How do you unit test window error handlers?</h3><p><strong>Quick version (beginner)</strong></p><p>Install Vitest and jsdom:</p><pre>npm install --save-dev vitest jsdom</pre><pre>// vitest.config.ts<br>import { defineConfig } from &#39;vitest/config&#39;;<br><br>export default defineConfig({<br>  test: {<br>    environment: &#39;jsdom&#39;,<br>  },<br>});</pre><p>Now the tests. They dispatch real ErrorEvent and Event objects at document, so we exercise the same code path the browser uses:</p><pre>// src/error-monitor.test.ts<br>import { afterEach, describe, expect, it, vi } from &#39;vitest&#39;;<br>import { installErrorMonitor, type ErrorMonitor, type ErrorReport } from &#39;./error-monitor&#39;;<br><br>describe(&#39;installErrorMonitor&#39;, () =&gt; {<br>  let monitor: ErrorMonitor | undefined;<br>  const send = vi.fn&lt;(endpoint: string, body: string) =&gt; void&gt;();<br>  const install = (maxReportsPerSession?: number): void =&gt; {<br>    send.mockClear();<br>    monitor = installErrorMonitor({<br>      endpoint: &#39;/api/errors&#39;,<br>      release: &#39;1.4.2&#39;,<br>      send,<br>      target: document,<br>      maxReportsPerSession,<br>    });<br>  };<br>  const lastReport = (): ErrorReport =&gt; {<br>    const call = send.mock.calls[send.mock.calls.length - 1];<br>    return JSON.parse(call[1]) as ErrorReport;<br>  };<br>  afterEach(() =&gt; {<br>    monitor?.uninstall();<br>    document.body.innerHTML = &#39;&#39;;<br>  });<br>  it(&#39;reports runtime errors with location and release&#39;, () =&gt; {<br>    install();<br>    document.dispatchEvent(<br>      new ErrorEvent(&#39;error&#39;, {<br>        message: &#39;boom&#39;,<br>        filename: &#39;app.js&#39;,<br>        lineno: 10,<br>        colno: 5,<br>        error: new Error(&#39;boom&#39;),<br>      }),<br>    );<br>    expect(send).toHaveBeenCalledTimes(1);<br>    const report = lastReport();<br>    expect(report.kind).toBe(&#39;runtime&#39;);<br>    expect(report.lineno).toBe(10);<br>    expect(report.release).toBe(&#39;1.4.2&#39;);<br>    expect(report.stack).toContain(&#39;boom&#39;);<br>  });<br>  it(&#39;reports failed resources caught in the capture phase&#39;, () =&gt; {<br>    install();<br>    const img = document.createElement(&#39;img&#39;);<br>    img.setAttribute(&#39;src&#39;, &#39;/missing.png&#39;);<br>    document.body.appendChild(img);<br>    img.dispatchEvent(new Event(&#39;error&#39;));<br>    const report = lastReport();<br>    expect(report.kind).toBe(&#39;resource&#39;);<br>    expect(report.message).toBe(&#39;Failed to load &lt;img&gt;&#39;);<br>    expect(report.source).toBe(&#39;/missing.png&#39;);<br>  });<br>  it(&#39;reports unhandled promise rejections&#39;, () =&gt; {<br>    install();<br>    const event = Object.assign(new Event(&#39;unhandledrejection&#39;), {<br>      reason: new Error(&#39;nope&#39;),<br>    });<br>    document.dispatchEvent(event);<br>    expect(lastReport().kind).toBe(&#39;promise&#39;);<br>    expect(lastReport().message).toBe(&#39;nope&#39;);<br>  });<br>  it(&#39;deduplicates identical errors&#39;, () =&gt; {<br>    install();<br>    const make = (): ErrorEvent =&gt;<br>      new ErrorEvent(&#39;error&#39;, { message: &#39;same&#39;, filename: &#39;a.js&#39;, lineno: 1, colno: 1 });<br>    document.dispatchEvent(make());<br>    document.dispatchEvent(make());<br>    expect(send).toHaveBeenCalledTimes(1);<br>  });<br>  it(&#39;stops after the per-session limit&#39;, () =&gt; {<br>    install(2);<br>    for (let i = 0; i &lt; 5; i += 1) {<br>      document.dispatchEvent(new ErrorEvent(&#39;error&#39;, { message: `err ${i}` }));<br>    }<br>    expect(send).toHaveBeenCalledTimes(2);<br>  });<br>});</pre><p>Run them:</p><pre>npx vitest run</pre><p>Expected output (timings will differ):</p><pre>✓ src/error-monitor.test.ts (5 tests)</pre><pre> Test Files  1 passed (1)<br>      Tests  5 passed (5)</pre><p><strong>Real-world version (pitfalls)</strong></p><p>Why dispatch on document instead of window? Test runners commonly watch window for uncaught errors and fail the run when one appears. Dispatching a synthetic error at the real window can look like a genuine crash to the runner. A stand-in target keeps the test about your logic. The capture-phase test works because document sits above the img in the event path.</p><p><strong>Under the hood (internals, trade-offs)</strong></p><p>These tests don’t prove the browser delivers events the way jsdom does. They prove your branching, dedupe, and limits. For the delivery side, add one end-to-end check with a real browser tool against a page that really throws. Cheap tests for logic, one expensive test for wiring: that’s the split I’d keep.</p><p>Now the part most Angular readers are waiting for.</p><h3>How do you connect this to Angular’s ErrorHandler?</h3><p><strong>Quick version (beginner)</strong></p><p>Angular routes errors from templates, lifecycle hooks, and event handlers it manages to its own ErrorHandler, and by default that logs to the console. Because Angular catches those errors first, they often never reach window.onerror. So wire your monitor into ErrorHandler:</p><pre>// src/app/monitoring-error-handler.ts<br>import { ErrorHandler, Injectable, InjectionToken, inject } from &#39;@angular/core&#39;;<br><br>export const REPORT_ERROR = new InjectionToken&lt;(error: unknown) =&gt; void&gt;(&#39;REPORT_ERROR&#39;);<br>@Injectable()<br>export class MonitoringErrorHandler implements ErrorHandler {<br>  private readonly report = inject(REPORT_ERROR);<br>  handleError(error: unknown): void {<br>    this.report(error);<br>    console.error(error);<br>  }<br>}</pre><pre>// src/main.ts<br>import { ErrorHandler } from &#39;@angular/core&#39;;<br>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br>import { App } from &#39;./app/app&#39;;<br>import { REPORT_ERROR, MonitoringErrorHandler } from &#39;./app/monitoring-error-handler&#39;;<br>import { installErrorMonitor } from &#39;./error-monitor&#39;;</pre><pre>const monitor = installErrorMonitor({ endpoint: &#39;/api/errors&#39;, release: &#39;1.0.0&#39; });</pre><pre>bootstrapApplication(App, {<br>  providers: [<br>    { provide: REPORT_ERROR, useValue: (error: unknown) =&gt; monitor.reportError(error) },<br>    { provide: ErrorHandler, useClass: MonitoringErrorHandler },<br>  ],<br>}).catch((error: unknown) =&gt; monitor.reportError(error));</pre><pre>// src/app/app.ts<br>import { Component, signal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;button (click)=&quot;explode()&quot;&gt;Break something&lt;/button&gt;<br>    @if (clicks() &gt; 0) {<br>      &lt;p&gt;Clicked {{ clicks() }} times&lt;/p&gt;<br>    }<br>  `,<br>})<br>export class App {<br>  protected readonly clicks = signal(0);<br>  protected explode(): void {<br>    this.clicks.update((n) =&gt; n + 1);<br>    const user = JSON.parse(&#39;{}&#39;) as { profile?: { name: string } };<br>    console.log(user.profile!.name);<br>  }<br>}</pre><p>Click the button and your network tab shows a POST to /api/errors:</p><pre>{&quot;kind&quot;:&quot;runtime&quot;,&quot;message&quot;:&quot;Cannot read properties of undefined (reading &#39;name&#39;)&quot;,&quot;stack&quot;:&quot;TypeError: Cannot read properties of undefined (reading &#39;name&#39;)\n    at App.explode ...&quot;,&quot;pageUrl&quot;:&quot;&lt;http://localhost:4200/&quot;,&quot;userAgent&quot;:&quot;Mozilla/5.0&gt; ...&quot;,&quot;release&quot;:&quot;1.0.0&quot;,&quot;timestamp&quot;:1790000000000}</pre><p>(The stack is truncated here for readability, yours will be full.)</p><p><strong>Real-world version (pitfalls)</strong></p><p>Notice the module doesn’t import Angular, and the handler doesn’t import the monitor. The token is the seam. That keeps the monitor reusable in React or plain JavaScript, and it keeps the Angular piece trivially testable:</p><pre>// src/app/monitoring-error-handler.spec.ts<br>import { ErrorHandler } from &#39;@angular/core&#39;;<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { MonitoringErrorHandler, REPORT_ERROR } from &#39;./monitoring-error-handler&#39;;<br><br>describe(&#39;MonitoringErrorHandler&#39;, () =&gt; {<br>  it(&#39;forwards errors to the reporter&#39;, () =&gt; {<br>    const captured: unknown[] = [];<br>    TestBed.configureTestingModule({<br>      providers: [<br>        { provide: REPORT_ERROR, useValue: (error: unknown) =&gt; captured.push(error) },<br>        { provide: ErrorHandler, useClass: MonitoringErrorHandler },<br>      ],<br>    });<br>    const handler = TestBed.inject(ErrorHandler);<br>    const error = new Error(&#39;template blew up&#39;);<br>    handler.handleError(error);<br>    expect(captured).toEqual([error]);<br>  });<br>});</pre><pre>ng test</pre><pre>Executed 1 of 1 SUCCESS</pre><p>(The exact summary line depends on the runner your CLI version generates. The test itself uses only describe, it, and expect, so it works with either of the common runners. The console.error call will print the test error to the log, which is expected.)</p><p>For React, the same idea applies. Error boundaries catch render-phase errors, and those need a class component for the boundary itself, so check <a href="https://react.dev/">react.dev</a> for the current boundary and root error callback options, then call monitor.reportError from there.</p><p><strong>Under the hood (internals, trade-offs)</strong></p><p>Do you need both layers? Yes. The framework handler sees what the framework swallows. The window listeners see everything else: third-party scripts, failed assets, code outside the framework, and the bootstrap itself. Dedupe makes it safe if the same error reaches both.</p><p>One last gap. Reports now arrive, but the stacks point into minified bundles.</p><h3>How do you read minified stack traces from window.onerror?</h3><p>Your lineno and colno describe the file the browser ran, which is the bundle. Without source maps, &quot;line 1, column 48213&quot; is useless.</p><p>The usual setup: generate source maps at build time, upload them to your error backend (or keep them private on your own server), and don’t serve them publicly if your code is sensitive. In Vite, hidden generates maps without adding the reference comment to the bundle:</p><pre>// vite.config.ts<br>import { defineConfig } from &#39;vite&#39;;<br><br>export default defineConfig({<br>  build: {<br>    sourcemap: &#39;hidden&#39;,<br>  },<br>});</pre><p>For Angular, the builder has a matching hidden option under sourceMap in angular.json, so confirm the exact shape on <a href="https://angular.dev/">angular.dev</a> for your CLI version.</p><p>The release field from our payload is what ties a report to the right map. A map from build 1.0.0 will mislabel frames from 1.0.1.</p><p>When shouldn’t you build this yourself? If you need grouping across thousands of error variants, alerting, release health, and session replay, use a hosted tool. This module is the right size for small apps, internal tools, and for understanding what those tools are doing under the hood. It’s also a good way to learn the browser’s failure channels so you can configure any vendor SDK properly.</p><h3>What was behind line 0 all along?</h3><p>Back to your Friday screenshot. The counter said “Script error.” because a script from another origin threw, and the browser muted it. Your handler was fine. The delivery was the problem: the script tag lacked crossorigin, and the host lacked the CORS header.</p><p>Add both, and the next report carries a file, a line, a column, and a stack. Add the capture listener and the promise listener, and failed images and floating promises show up as well. Add the beacon and the limits, and you stop losing the last error before a tab closes.</p><p>The lesson I’d take from this: window.onerror isn&#39;t wrong, it&#39;s just one of three channels, and the rest of the work is delivery and noise control.</p><p>If this changed how you think about error reporting, share it with the teammate who owns your monitoring setup. They’ll thank you after the next Friday incident.</p><h3>Bonus tips</h3><p><strong>Beginner:</strong> Search your codebase for window.onerror = and return true. Both are worth a second look.</p><p><strong>Intermediate:</strong> Use window.reportError(error) inside a catch block when you want to log a handled error through the same global channel. Check the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/reportError">MDN compatibility table</a> before relying on it in older browsers.</p><p><strong>Advanced:</strong> Track a “same error, different release” counter server-side using the dedupe key plus release. A fix that doesn&#39;t move that number didn&#39;t fix anything.</p><h3>Recap</h3><ul><li>window.onerror passes five arguments and is a single slot. addEventListener(&#39;error&#39;, ...) composes and gives you one ErrorEvent.</li><li>Returning true from onerror hides the error in the console.</li><li>“Script error.” with line 0 means a muted cross-origin script. Fix it with the crossorigin attribute plus a CORS header.</li><li>Resource errors don’t bubble, so listen in the capture phase. Rejected promises need their own unhandledrejection listener.</li><li>Dedupe, cap, and guard against recursion in the reporter. Send with sendBeacon, fall back to fetch with keepalive.</li><li>Wire your framework’s error handler into the same reporter, and test the logic with synthetic events.</li></ul><p>Further reading: the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event">MDN page on the Window error event</a>, an <a href="https://udn.realityripple.com/docs/Web/API/GlobalEventHandlers/onerror">archived copy of the older onerror documentation</a>, the <a href="https://blog.sentry.io/client-javascript-reporting-window-onerror/">Sentry post on reporting window.onerror</a>, the <a href="https://medium.com/fiverr-engineering/front-end-observability-a-practical-guide-to-browsers-error-monitoring-with-window-onerror-307f7a93deef">Fiverr engineering guide to front end error monitoring</a>, and <a href="https://www.linkedin.com/pulse/capture-report-javascript-errors-windowonerror-andrey-okhotnikov/">this LinkedIn write-up on capturing and reporting JavaScript errors with window.onerror</a>.</p><p><strong>What did you think?</strong></p><p>Did this approach match how you are solving it, or do you have a different take? Drop a comment. I genuinely read every single one.</p><p><strong>Found this helpful?</strong></p><p>If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong></p><p>I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let us connect. Find me on LinkedIn or GitHub and let us keep the conversation going.</p><p>Follow Me for More Angular &amp; Frontend Goodness:</p><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">Reddit</a> — Developer blog posts &amp; tech discussions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38f605056563" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/front-end-observability-why-your-window-onerror-reports-say-script-error-and-how-to-fix-them-38f605056563">Front End Observability: Why Your window.onerror Reports Say “Script error.” (and How to Fix Them)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DoubleClick jacking: Why Your Clickjacking Headers Never See It Coming]]></title>
            <link>https://javascript.plainenglish.io/doubleclick-jacking-why-your-clickjacking-headers-never-see-it-coming-a86aa4e2144e?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/a86aa4e2144e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 13:06:56 GMT</pubDate>
            <atom:updated>2026-11-03T13:06:56.127Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The attack never puts your page in a frame, so the headers on NGINX, Cloudflare and CloudFront have nothing to block. Here is how it works, what actually stops it, and an Angular component with tests you can copy.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kjr6x9uU22beitVrMW0eOg.jpeg" /></figure><p>It’s Friday, 4:40 p.m., and your security review just came back clean. The report has one line you’re proud of: “Clickjacking: protected.” You set X-Frame-Options and frame-ancestors on NGINX months ago, the scanner agrees, and your session cookie is SameSite=Lax.</p><p>Then a teammate drops a link in chat. “Try this. Just double-click the box.”</p><p>A fake verification window pops up. You double-click. Nothing seems to happen. Ten seconds later you open your account settings, and a stranger’s app is sitting in the list of connected apps with permissions you never agreed to.</p><p>You never saw a consent screen. You never even saw your own site. So how does DoubleClickjacking get past a setup that every checklist calls correct?</p><p>Here’s what you’ll get from this article: how the attack really works, the families it comes in, what NGINX, Apache, Cloudflare and CloudFront can and can’t do about it, and a small client-side gate that closes the hole. You’ll build that gate as an Angular component and test it.</p><p>One question to carry with you: if this attack never puts your page in a frame, what exactly are those headers protecting? I’ll answer it near the end.</p><p>If you like security write-ups told as stories, with code you can paste into a project today, follow me here on Medium so the next one finds you.</p><blockquote><em>Before we get into the examples, a quick note: The code snippets provided here are meant purely for understanding the concept. Some syntax shown may reflect patterns from earlier Angular/React versions. Always refer to the official documentation for the most current API and syntax.</em></blockquote><h3>What happens when you double-click a fake CAPTCHA?</h3><p><strong>Quick version.</strong> Classic clickjacking hides your site inside an invisible frame and tricks you into clicking through it. Browsers fought back with headers that say “don’t let other sites frame me.” DoubleClickjacking skips the frame completely. The attacker’s page opens a second window on top and asks you to double-click. While you’re busy doing that, the window underneath quietly navigates to your real page, say an OAuth approval screen. Your first click closes the top window. Your second click lands on whatever is now underneath. That’s your Approve button.</p><p><strong>Real-world version.</strong> Security researcher Paulos Yibelo <a href="https://www.evil.blog/2024/12/doubleclickjacking-what.html">published the technique in December 2024</a>, and the coverage that followed reported that it sidesteps X-Frame-Options, CSP and SameSite cookies. The reason is boring and important: your page is opened as a normal top-level page, in a normal window, with the victim’s normal session. From the browser’s point of view nothing is being framed, and nothing about the request is cross-site.</p><p>The usual targets are screens where one click does something serious: approving an OAuth app, confirming a payment, flipping a security setting. If you want more angles on the same exploit, these are worth your time: the <a href="https://www.computer.org/csdl/proceedings-article/icoin/2026/11480509/2g3lDAhIKMU">ICOIN 2026 paper on clickjacking and double-clickjacking prevention</a>, <a href="https://medium.com/@whitedragon2348/new-doubleclickjacking-exploit-bypasses-clickjacking-protections-on-major-websites-4a6bc2476a95">my earlier piece on this exploit</a>, the <a href="https://www.indusface.com/learning/what-is-double-clickjacking/">Indusface explainer</a> and the <a href="https://www.yeswehack.com/news/double-clickjacking-request-tunnelling-encryption">YesWeHack write-up</a>.</p><p><strong>Under the hood.</strong> A double-click is two presses with a gap between them. The browser delivers each press to whichever window is under the cursor at that moment. So the attacker only has to change what’s under the cursor inside that gap. Here’s the timeline in plain text:</p><pre>time ------------------------------------------------------------&gt;<br><br>1. attacker page opens a small window on top: &quot;double-click to verify&quot;<br>2. that window navigates the window underneath to YOUR consent page<br>3. first press and release  -&gt; handled by the top window, which closes itself<br>4. second press and release -&gt; lands on the page that is now underneath<br>                               (your Approve button)</pre><p>Notice what’s missing. There’s no iframe anywhere in that story. The user sees one fake box and does the one thing it asked for.</p><p>That’s the original trick. The headline hides how many shapes it comes in, so let’s count them.</p><h3>How many ways can DoubleClickjacking happen?</h3><p>It depends on how you count, and I don’t trust anyone who gives you a single number. These are the four families I’d keep in your head.</p><p><strong>The window swap.</strong> The original. A top window asks for a double-click while the window underneath is sent to the target page. Everything above describes this one.</p><p><strong>The held-key variant.</strong> Researcher Jorian Woltjer pushed the idea further in a write-up on <a href="https://jorianwoltjer.com/blog/p/research/ultimate-doubleclickjacking-poc">making the attack smoother with popups and keyboard input</a>. In his research, a victim who is holding a key can hand the attacker a steady supply of user activations, which is what lets popups open and swap without a fresh click each time. Takeaway for you: a keypress isn’t automatic proof of intent.</p><p><strong>The extension and wallet variant.</strong> Reports on the original research name browser extensions as targets, including crypto wallets, Web3 transaction prompts and VPN toggles that can be switched off.</p><p><strong>The touch variant.</strong> The same reports say phones are affected too, through double-taps instead of double-clicks.</p><p>I can’t promise that list is complete, and new variants keep showing up. That’s why I’d defend the behavior (a button that fires on a click nobody meant) and not any single variant.</p><p>So here’s a question for you. Which screens in your app do something expensive on a single click? Write that list down, because you’ll need it in a minute.</p><p>First, though, let’s do what everyone does and reach for headers.</p><h3>Why don’t X-Frame-Options and frame-ancestors stop it?</h3><p><strong>Quick version.</strong> Those headers answer exactly one question: “may another page frame me?” In this attack nobody frames you, so there’s no question for the header to answer.</p><p>Here’s the screen from your Friday story. This is the wrong version, the one that still runs.</p><p>src/app/consent.component.ts</p><pre>import { Component, input, output } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-consent&#39;,<br>  template: `<br>    &lt;h2&gt;{{ appName() }} wants access to your account&lt;/h2&gt;<br>    &lt;p&gt;Scopes: {{ scopes().join(&#39;, &#39;) }}&lt;/p&gt;<br>    &lt;button type=&quot;button&quot; data-testid=&quot;approve&quot; (click)=&quot;approved.emit()&quot;&gt;Approve&lt;/button&gt;<br>  `,<br>})<br>export class ConsentComponent {<br>  readonly appName = input.required&lt;string&gt;();<br>  readonly scopes = input&lt;string[]&gt;([]);<br>  readonly approved = output&lt;void&gt;();<br>}</pre><p>It renders an Approve button that works on the very first click. That’s the weakness, and no server setting touches it.</p><p>Now the first attempt, the one every checklist suggests: set the framing headers. They’re still worth having, since classic clickjacking hasn’t gone anywhere, so do this and keep reading.</p><p><strong>NGINX.</strong> Put the headers in the server block and add always so error pages get them too.</p><p>/etc/nginx/conf.d/app.conf</p><pre>server {<br>    listen 443 ssl;<br>    server_name app.example.com;<br>    add_header X-Frame-Options &quot;DENY&quot; always;<br>    add_header Content-Security-Policy &quot;frame-ancestors &#39;none&#39;&quot; always;<br>    <br>    location / {<br>        proxy_pass &lt;http://127.0.0.1:4200&gt;;<br>    }<br>}<br></pre><p>Pitfall: NGINX only inherits add_header lines from the level above when the current level has none of its own. The moment a location block adds a header, your server-level ones vanish for that location. The <a href="https://nginx.org/en/docs/http/ngx_http_headers_module.html">NGINX headers module docs</a> spell this out.</p><p><strong>Apache.</strong> Same idea, with mod_headers.</p><p>/etc/apache2/conf-available/framing.conf</p><pre>Header always set X-Frame-Options &quot;DENY&quot;<br>Header always set Content-Security-Policy &quot;frame-ancestors &#39;none&#39;&quot;</pre><p>Run a2enmod headers and a2enconf framing, then reload Apache.</p><p><strong>Cloudflare.</strong> If you can’t touch the origin, add a <a href="https://developers.cloudflare.com/rules/transform/response-header-modification/">response header Transform Rule</a> in the dashboard. If you prefer code, a Worker does the same job.</p><p>src/worker.ts</p><pre>export default {<br>  async fetch(request: Request): Promise&lt;Response&gt; {<br>    const upstream = await fetch(request);<br>    const headers = new Headers(upstream.headers);<br>    headers.set(&#39;X-Frame-Options&#39;, &#39;DENY&#39;);<br>    headers.set(&#39;Content-Security-Policy&#39;, &quot;frame-ancestors &#39;none&#39;&quot;);<br>    return new Response(upstream.body, {<br>      status: upstream.status,<br>      statusText: upstream.statusText,<br>      headers,<br>    });<br>  },<br>};</pre><p>Pitfall: headers.set replaces any Content-Security-Policy your origin already sends. If you have one, merge frame-ancestors &#39;none&#39; into it instead of overwriting it.</p><p><strong>CloudFront.</strong> Create a <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/adding-response-headers.html">response headers policy</a> and attach it to your cache behavior.</p><p>policy.json</p><pre>{<br>  &quot;Name&quot;: &quot;framing-protection&quot;,<br>  &quot;Comment&quot;: &quot;Block framing of every response&quot;,<br>  &quot;SecurityHeadersConfig&quot;: {<br>    &quot;FrameOptions&quot;: {<br>      &quot;FrameOption&quot;: &quot;DENY&quot;,<br>      &quot;Override&quot;: true<br>    },<br>    &quot;ContentSecurityPolicy&quot;: {<br>      &quot;ContentSecurityPolicy&quot;: &quot;frame-ancestors &#39;none&#39;&quot;,<br>      &quot;Override&quot;: true<br>    }<br>  }<br>}</pre><pre>aws cloudfront create-response-headers-policy --response-headers-policy-config file://policy.json</pre><p>The command returns JSON that includes the new policy’s Id. Copy it into the ResponseHeadersPolicyId field of the cache behavior that serves your app, or the policy exists and does nothing.</p><p>Whichever server you use, verify it from the outside:</p><pre>curl -sI &lt;https://app.example.com/oauth/authorize&gt; | grep -i -E &quot;x-frame-options|content-security-policy&quot;</pre><p>Expected output:</p><pre>x-frame-options: DENY<br>content-security-policy: frame-ancestors &#39;none&#39;</pre><p><strong>Real-world version.</strong> Both headers work as designed. A browser consults them when a document is about to load inside a frame. In this attack your consent page loads into a top-level window, so there’s no frame and no ancestor to check. SameSite=Lax doesn’t help either: it exists to stop cross-site requests, and a top-level navigation is the exact case Lax allows.</p><p><strong>Under the hood.</strong> This is why the report I mentioned earlier says the old defenses are blind to it. The defenses answer questions about where your page is embedded. The attack changes which window your user’s next click goes to.</p><p>Every green tick above is real, and none of them touches this attack.</p><p>Have you ever added a security header, watched the scanner turn green, and later found out it was guarding a different door? Tell me which header and which door in the comments.</p><p>So if headers can’t see the attack, what can? Something small, and slightly rude to your own users.</p><h3>What if the button refuses to work until a human proves they’re there?</h3><p>Back to your Friday. Your first instinct is to open the config files again and add one more header. There’s nothing left to add. Those headers describe where your page may live, and this attack doesn’t care where it lives. The flaw is smaller and closer to home: your Approve button trusts every click it receives.</p><p><strong>Quick version.</strong> Load sensitive buttons disabled. Enable them only after the page sees something a person looking at this window would do, like moving the mouse a little or pressing Tab. In the attack, the cursor is parked over the fake box when your page slides in underneath. The pointer never moves inside your page, so the button stays dead and the second click goes nowhere. This is the client-side fix <a href="https://www.evil.blog/2024/12/doubleclickjacking-what.html">Yibelo recommends in his write-up</a>: keep critical buttons disabled until a gesture shows up.</p><p><strong>Real-world version.</strong> The naive version, “enable on any mousemove”, has holes, and I found a few by thinking about real devices. Touch screens never fire mousemove, so a pure pointer gate would lock out every phone user. A held key repeats keydown events, and we saw earlier that an attacker can get a victim to hold a key, so repeats must not count. If the window loses focus, whatever trust you earned should be thrown away. The gate below handles all of that. On touch screens it falls back to a short delay after the window gains focus, set longer than the gap between two quick taps. That delay is my pick, so tune it against your own users.</p><p>src/app/gesture-gate.ts</p><pre>export interface GestureGateOptions {<br>  /** Pixels the pointer must travel before we trust it. */<br>  minTravel?: number;<br>  /** Delay before arming on touch screens, after the window gains focus. */<br>  touchDelayMs?: number;<br>  /** Where to listen. Defaults to the global document. */<br>  root?: Document;<br>  /** Override for tests. Defaults to a (pointer: coarse) media query. */<br>  isCoarsePointer?: () =&gt; boolean;<br>}<br><br>export interface GestureGate {<br>  destroy(): void;<br>}<br>export function createGestureGate(<br>  onChange: (armed: boolean) =&gt; void,<br>  options: GestureGateOptions = {},<br>): GestureGate {<br>  const root = options.root ?? document;<br>  const win = root.defaultView ?? window;<br>  const minTravel = options.minTravel ?? 8;<br>  const touchDelayMs = options.touchDelayMs ?? 800;<br>  const isCoarsePointer =<br>    options.isCoarsePointer ??<br>    (() =&gt; win.matchMedia?.(&#39;(pointer: coarse)&#39;).matches ?? false);<br>  let armed = false;<br>  let last: { x: number; y: number } | null = null;<br>  let travelled = 0;<br>  let timer: ReturnType&lt;typeof setTimeout&gt; | undefined;<br>  const set = (value: boolean): void =&gt; {<br>    if (armed !== value) {<br>      armed = value;<br>      onChange(value);<br>    }<br>  };<br>  const clearTimer = (): void =&gt; {<br>    if (timer !== undefined) {<br>      clearTimeout(timer);<br>      timer = undefined;<br>    }<br>  };<br>  const startTimer = (): void =&gt; {<br>    clearTimer();<br>    timer = setTimeout(() =&gt; set(true), touchDelayMs);<br>  };<br>  const reset = (): void =&gt; {<br>    last = null;<br>    travelled = 0;<br>    clearTimer();<br>    set(false);<br>  };<br>  const onMove = (e: MouseEvent): void =&gt; {<br>    if (last) {<br>      travelled += Math.hypot(e.clientX - last.x, e.clientY - last.y);<br>    }<br>    last = { x: e.clientX, y: e.clientY };<br>    if (travelled &gt;= minTravel) {<br>      set(true);<br>    }<br>  };<br>  const onKey = (e: KeyboardEvent): void =&gt; {<br>    // A held key repeats. An attacker can make the victim hold a key.<br>    if (e.repeat) return;<br>    if (e.key === &#39;Tab&#39;) set(true);<br>  };<br>  const onBlur = (): void =&gt; reset();<br>  const onFocus = (): void =&gt; {<br>    if (isCoarsePointer()) startTimer();<br>  };<br>  const onVisibility = (): void =&gt; {<br>    if (root.visibilityState === &#39;hidden&#39;) reset();<br>  };<br>  root.addEventListener(&#39;mousemove&#39;, onMove);<br>  root.addEventListener(&#39;keydown&#39;, onKey);<br>  root.addEventListener(&#39;visibilitychange&#39;, onVisibility);<br>  win.addEventListener(&#39;blur&#39;, onBlur);<br>  win.addEventListener(&#39;focus&#39;, onFocus);<br>  if (isCoarsePointer() &amp;&amp; root.hasFocus()) startTimer();<br>  return {<br>    destroy(): void {<br>      clearTimer();<br>      root.removeEventListener(&#39;mousemove&#39;, onMove);<br>      root.removeEventListener(&#39;keydown&#39;, onKey);<br>      root.removeEventListener(&#39;visibilitychange&#39;, onVisibility);<br>      win.removeEventListener(&#39;blur&#39;, onBlur);<br>      win.removeEventListener(&#39;focus&#39;, onFocus);<br>    },<br>  };<br>}</pre><p>The gate takes a callback and returns a handle you can destroy, so it isn’t tied to Angular. The component is where the signal lives. This is the fixed version of the screen from earlier.</p><p>src/app/consent.component.ts</p><pre>import { Component, DestroyRef, inject, input, output, signal } from &#39;@angular/core&#39;;<br>import { createGestureGate } from &#39;./gesture-gate&#39;;<br><br>@Component({<br>  selector: &#39;app-consent&#39;,<br>  template: `<br>    &lt;h2&gt;{{ appName() }} wants access to your account&lt;/h2&gt;<br>    &lt;p&gt;Scopes: {{ scopes().join(&#39;, &#39;) }}&lt;/p&gt;<br>    &lt;button<br>      type=&quot;button&quot;<br>      data-testid=&quot;approve&quot;<br>      [disabled]=&quot;!armed()&quot;<br>      (click)=&quot;approved.emit()&quot;<br>    &gt;<br>      Approve<br>    &lt;/button&gt;<br>    @if (!armed()) {<br>      &lt;small data-testid=&quot;hint&quot;&gt;Move your mouse or press Tab to enable this button.&lt;/small&gt;<br>    }<br>  `,<br>})<br>export class ConsentComponent {<br>  readonly appName = input.required&lt;string&gt;();<br>  readonly scopes = input&lt;string[]&gt;([]);<br>  readonly approved = output&lt;void&gt;();<br>  protected readonly armed = signal(false);<br>  constructor() {<br>    const gate = createGestureGate((value) =&gt; this.armed.set(value));<br>    inject(DestroyRef).onDestroy(() =&gt; gate.destroy());<br>  }<br>}</pre><p>What you should see in the browser:</p><pre>page loads            -&gt; Approve is disabled, the hint is visible<br>mouse moves 8px+      -&gt; Approve is enabled, the hint disappears<br>window loses focus    -&gt; Approve is disabled again</pre><p><strong>Under the hood.</strong> The gate asks for evidence that only a person at your window can produce. Another origin can’t dispatch pointer events into your page, and a parked cursor produces none. That evidence has limits. Yibelo floated a browser-level header called Double-Click-Protection as an idea, and I found no sign of any browser honoring a header like that, so don’t add one and expect protection. I also couldn’t verify a browser-level fix when I researched this, so read current browser release notes and test the browsers you support.</p><p>Assistive technology deserves its own check. If a screen reader doesn’t produce the key events the gate listens for, add the ones it does produce, or your keyboard-only users will meet a button that never wakes up. And if an attacker already has script running on your page, no gate helps, because that’s a different problem.</p><p>A gate like this is only worth something if it keeps working after the next refactor, so let’s pin it down with tests.</p><h3>How do you test a gate you can’t click through?</h3><p><strong>Quick version.</strong> You don’t click. You dispatch the same events a browser would and check the button after each one. In a new Angular project, ng test runs Vitest by default since Angular 21 (see the <a href="https://angular.dev/guide/testing">Angular testing guide</a>). Older projects use Karma and Jasmine, so swap vi.fn() for jasmine.createSpy() and vi.useFakeTimers() for jasmine.clock().install().</p><p>src/app/consent.component.spec.ts</p><pre>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { ConsentComponent } from &#39;./consent.component&#39;;<br><br>describe(&#39;ConsentComponent&#39;, () =&gt; {<br>  let fixture: ComponentFixture&lt;ConsentComponent&gt;;<br>  const approve = (): HTMLButtonElement =&gt;<br>    fixture.nativeElement.querySelector(&#39;[data-testid=&quot;approve&quot;]&#39;);<br>  const move = (x: number, y: number): void =&gt; {<br>    document.dispatchEvent(new MouseEvent(&#39;mousemove&#39;, { clientX: x, clientY: y }));<br>    fixture.detectChanges();<br>  };<br>  const press = (init: KeyboardEventInit): void =&gt; {<br>    document.dispatchEvent(new KeyboardEvent(&#39;keydown&#39;, init));<br>    fixture.detectChanges();<br>  };<br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({ imports: [ConsentComponent] }).compileComponents();<br>    fixture = TestBed.createComponent(ConsentComponent);<br>    fixture.componentRef.setInput(&#39;appName&#39;, &#39;Photo Printer&#39;);<br>    fixture.componentRef.setInput(&#39;scopes&#39;, [&#39;read:photos&#39;]);<br>    fixture.detectChanges();<br>  });<br>  it(&#39;starts disabled&#39;, () =&gt; {<br>    expect(approve().disabled).toBe(true);<br>  });<br>  it(&#39;ignores a click when no gesture happened&#39;, () =&gt; {<br>    const spy = vi.fn();<br>    fixture.componentInstance.approved.subscribe(spy);<br>    approve().click();<br>    expect(spy).not.toHaveBeenCalled();<br>  });<br>  it(&#39;enables after real pointer travel and then emits&#39;, () =&gt; {<br>    const spy = vi.fn();<br>    fixture.componentInstance.approved.subscribe(spy);<br>    move(0, 0);<br>    move(20, 20);<br>    expect(approve().disabled).toBe(false);<br>    approve().click();<br>    expect(spy).toHaveBeenCalledTimes(1);<br>  });<br>  it(&#39;arms on Tab but not on a repeating key&#39;, () =&gt; {<br>    press({ key: &#39;Tab&#39;, repeat: true });<br>    expect(approve().disabled).toBe(true);<br>    press({ key: &#39;Tab&#39; });<br>    expect(approve().disabled).toBe(false);<br>  });<br>  it(&#39;disarms when the window loses focus&#39;, () =&gt; {<br>    move(0, 0);<br>    move(30, 30);<br>    expect(approve().disabled).toBe(false);<br>    window.dispatchEvent(new Event(&#39;blur&#39;));<br>    fixture.detectChanges();<br>    expect(approve().disabled).toBe(true);<br>  });<br>});</pre><p>src/app/gesture-gate.spec.ts</p><pre>import { createGestureGate } from &#39;./gesture-gate&#39;;<br><br>describe(&#39;createGestureGate on touch screens&#39;, () =&gt; {<br>  afterEach(() =&gt; vi.useRealTimers());<br>  it(&#39;arms only after the delay that follows a focus event&#39;, () =&gt; {<br>    vi.useFakeTimers();<br>    const states: boolean[] = [];<br>    const gate = createGestureGate((armed) =&gt; states.push(armed), {<br>      isCoarsePointer: () =&gt; true,<br>      touchDelayMs: 800,<br>    });<br>    window.dispatchEvent(new Event(&#39;focus&#39;));<br>    vi.advanceTimersByTime(799);<br>    expect(states).toEqual([]);<br>    vi.advanceTimersByTime(1);<br>    expect(states).toEqual([true]);<br>    gate.destroy();<br>  });<br>});</pre><p>Run them once without watch mode:</p><pre>ng test --no-watch</pre><p>Expected output (the CLI prints a check mark in front of each file, and a project made with ng new also lists its default app spec, which we replace near the end):</p><pre>src/app/consent.component.spec.ts (5 tests)<br> src/app/gesture-gate.spec.ts (1 test)<br><br>Test Files  2 passed (2)<br>      Tests  6 passed (6)</pre><p><strong>Real-world version.</strong> Unit tests prove your logic, not the browser’s event order. Add one manual check for every browser you support: park the cursor where the Approve button will appear, load the page with a keyboard shortcut, then click without moving the mouse. Nothing should happen. If some browser enables the button on its own after layout, you’ve learned something valuable before an attacker did.</p><p><strong>Under the hood.</strong> jsdom has no matchMedia, so the gate treats the test environment as a mouse-and-keyboard device, and the touch path is covered by injecting isCoarsePointer. Fake timers let the 800 ms delay run in zero real milliseconds, and the afterEach puts real timers back so the next test isn&#39;t affected.</p><p>So far the fix lives inside an Angular app. What about the pages you don’t own the code for?</p><h3>Can NGINX, Cloudflare or CloudFront deliver the gate for you?</h3><p><strong>Quick version.</strong> They can’t block the attack with headers, but they can deliver the script that does. For server-rendered or legacy pages, bundle the same gate as a tiny standalone script, mark the dangerous buttons with data-sensitive, and let the edge add one script tag.</p><p>src/guard.ts</p><pre>import { createGestureGate } from &#39;./app/gesture-gate&#39;;<br><br>const targets = Array.from(<br>  document.querySelectorAll&lt;HTMLButtonElement | HTMLInputElement&gt;(&#39;[data-sensitive]&#39;),<br>);<br>const setDisabled = (disabled: boolean): void =&gt; {<br>  for (const el of targets) {<br>    el.disabled = disabled;<br>  }<br>};<br>setDisabled(true);<br>createGestureGate((armed) =&gt; setDisabled(!armed));</pre><p>Bundle it into one file. A typical Angular project already has esbuild installed through its build tooling; if yours doesn’t, install it first.</p><pre>npx esbuild src/guard.ts --bundle --minify --format=iife --outfile=public/dcj-guard.js</pre><p>Expected output, with timings that will differ on your machine:</p><pre>public/dcj-guard.js  1.0kb<br><br>Done in 7ms</pre><p>Mark the buttons in the server-rendered page:</p><p>consent.html</p><pre>&lt;button type=&quot;submit&quot; data-sensitive&gt;Approve&lt;/button&gt;</pre><p><strong>NGINX.</strong> Add these two locations inside the same server block as before. Neither one declares its own add_header, so the framing headers keep being inherited.</p><p>/etc/nginx/conf.d/app.conf</p><pre>location = /static/dcj-guard.js {<br>    root /var/www/app;<br>}<br><br>location /oauth/authorize {<br>    proxy_pass &lt;http://127.0.0.1:4200&gt;;<br>    proxy_set_header Accept-Encoding &quot;&quot;;<br>    sub_filter &#39;&lt;/head&gt;&#39; &#39;&lt;script src=&quot;/static/dcj-guard.js&quot; defer&gt;&lt;/script&gt;&lt;/head&gt;&#39;;<br>}</pre><p>Copy the bundle to /var/www/app/static/dcj-guard.js. Two details trip people up here. sub_filter needs the ngx_http_sub_module, which not every NGINX build includes. And the empty Accept-Encoding header makes the upstream send plain HTML, because NGINX can&#39;t rewrite a compressed body.</p><p>Check that the tag arrives:</p><pre>curl -s &lt;https://app.example.com/oauth/authorize&gt; | grep -o &#39;&lt;script src=&quot;/static/dcj-guard.js&quot; defer&gt;&lt;/script&gt;&#39;</pre><p>Expected output:</p><pre>&lt;script src=&quot;/static/dcj-guard.js&quot; defer&gt;&lt;/script&gt;</pre><p><strong>Cloudflare.</strong> A Worker can add the same tag with HTMLRewriter, only on the pages that need it. Types for the Workers runtime come from the @cloudflare/workers-types package.</p><p>src/inject-guard.ts</p><pre>export default {<br>  async fetch(request: Request): Promise&lt;Response&gt; {<br>    const upstream = await fetch(request);<br>    const { pathname } = new URL(request.url);<br><br>    if (!pathname.startsWith(&#39;/oauth/authorize&#39;)) {<br>      return upstream;<br>    }<br>    return new HTMLRewriter()<br>      .on(&#39;head&#39;, {<br>        element(head) {<br>          head.append(&#39;&lt;script src=&quot;/static/dcj-guard.js&quot; defer&gt;&lt;/script&gt;&#39;, { html: true });<br>        },<br>      })<br>      .transform(upstream);<br>  },<br>};</pre><p><strong>CloudFront.</strong> A response headers policy only changes headers, so it can’t add a script tag. I’d put the tag in the page template or the build output at your origin and let CloudFront cache it. If you want to rewrite bodies at the edge, check the current CloudFront documentation for what it supports today.</p><p><strong>Real-world version.</strong> If you run a strict Content-Security-Policy, make sure script-src allows the guard script&#39;s origin. Also remember the script is deferred, so there&#39;s a short moment before it runs when the button is still live. If that bothers you, ship the button with the disabled attribute already in the markup and let the script enable it. The trade-off is that people with JavaScript turned off can never approve anything, which may be exactly what you want on a consent screen.</p><p><strong>Under the hood.</strong> Injecting at the edge keeps your app code untouched, but it ties your security to a string replace. The day someone removes the closing head tag from that template, the guard quietly disappears. A test that fetches the page and looks for the script tag is cheap insurance.</p><p>Disabling a button handles the timing trick. But what if you want a second lock that doesn’t depend on timing at all?</p><h3>What should the server ask for when a click can’t be trusted?</h3><p><strong>Quick version.</strong> Ask for something an attacker can’t produce by hijacking a click. A click can be stolen. Typing into your own field can’t. Here’s a small component that makes the user type the app’s name before the final button wakes up.</p><p>src/app/typed-confirm.component.ts</p><pre>import { Component, input, output, signal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-typed-confirm&#39;,<br>  template: `<br>    &lt;label&gt;<br>      Type {{ expected() }} to continue<br>      &lt;input #box data-testid=&quot;typed&quot; [value]=&quot;typed()&quot; (input)=&quot;typed.set(box.value)&quot; /&gt;<br>    &lt;/label&gt;<br>    &lt;button<br>      type=&quot;button&quot;<br>      data-testid=&quot;confirm&quot;<br>      [disabled]=&quot;typed() !== expected()&quot;<br>      (click)=&quot;confirmed.emit()&quot;<br>    &gt;<br>      Confirm<br>    &lt;/button&gt;<br>  `,<br>})<br>export class TypedConfirmComponent {<br>  readonly expected = input.required&lt;string&gt;();<br>  readonly confirmed = output&lt;void&gt;();<br>  protected readonly typed = signal(&#39;&#39;);<br>}</pre><p>src/app/typed-confirm.component.spec.ts</p><pre>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { TypedConfirmComponent } from &#39;./typed-confirm.component&#39;;<br><br>describe(&#39;TypedConfirmComponent&#39;, () =&gt; {<br>  let fixture: ComponentFixture&lt;TypedConfirmComponent&gt;;<br>  const confirm = (): HTMLButtonElement =&gt;<br>    fixture.nativeElement.querySelector(&#39;[data-testid=&quot;confirm&quot;]&#39;);<br>  const type = (value: string): void =&gt; {<br>    const input: HTMLInputElement = fixture.nativeElement.querySelector(&#39;[data-testid=&quot;typed&quot;]&#39;);<br>    input.value = value;<br>    input.dispatchEvent(new Event(&#39;input&#39;));<br>    fixture.detectChanges();<br>  };<br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({ imports: [TypedConfirmComponent] }).compileComponents();<br>    fixture = TestBed.createComponent(TypedConfirmComponent);<br>    fixture.componentRef.setInput(&#39;expected&#39;, &#39;Photo Printer&#39;);<br>    fixture.detectChanges();<br>  });<br>  it(&#39;stays disabled until the exact name is typed&#39;, () =&gt; {<br>    expect(confirm().disabled).toBe(true);<br>    type(&#39;Photo&#39;);<br>    expect(confirm().disabled).toBe(true);<br>    type(&#39;Photo Printer&#39;);<br>    expect(confirm().disabled).toBe(false);<br>  });<br>  it(&#39;emits once when confirmed&#39;, () =&gt; {<br>    const spy = vi.fn();<br>    fixture.componentInstance.confirmed.subscribe(spy);<br>    type(&#39;Photo Printer&#39;);<br>    confirm().click();<br>    expect(spy).toHaveBeenCalledTimes(1);<br>  });<br>});</pre><p><strong>Real-world version.</strong> My rule: an app asking to read private data, or a change to a security setting, gets step-up verification. Make the user re-enter their password or a one-time code first. Email them when a new app is connected, and make revoking it one tap away. If a future variant slips past your gate, the attacker still can’t type your user’s password.</p><p><strong>Under the hood.</strong> The attacker controls the timing of clicks and which window receives them. They don’t control keystrokes going into a field on your page. Typing the app’s name has a side benefit, too: it forces a glance at the name, which a reflexive click never does. Use it on rare, high-impact steps only. If every screen asks for typing, people learn to type without reading.</p><p>Time to see all of it running together.</p><h3>Does the whole thing work together?</h3><p>Here’s the full running example. The root component walks the user through the gated consent screen, then the typed confirmation, then a final message.</p><p>src/app/app.ts</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { ConsentComponent } from &#39;./consent.component&#39;;<br>import { TypedConfirmComponent } from &#39;./typed-confirm.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  imports: [ConsentComponent, TypedConfirmComponent],<br>  template: `<br>    @switch (step()) {<br>      @case (&#39;consent&#39;) {<br>        &lt;app-consent<br>          appName=&quot;Photo Printer&quot;<br>          [scopes]=&quot;[&#39;read:photos&#39;]&quot;<br>          (approved)=&quot;step.set(&#39;confirm&#39;)&quot;<br>        /&gt;<br>      }<br>      @case (&#39;confirm&#39;) {<br>        &lt;app-typed-confirm expected=&quot;Photo Printer&quot; (confirmed)=&quot;step.set(&#39;done&#39;)&quot; /&gt;<br>      }<br>      @case (&#39;done&#39;) {<br>        &lt;p data-testid=&quot;done&quot;&gt;Access granted to Photo Printer.&lt;/p&gt;<br>      }<br>    }<br>  `,<br>})<br>export class App {<br>  protected readonly step = signal&lt;&#39;consent&#39; | &#39;confirm&#39; | &#39;done&#39;&gt;(&#39;consent&#39;);<br>}</pre><p>The CLI generates an app.html and app.css next to this file. Delete both, since the template now lives inline. Then replace the default app.spec.ts with a test that plays the whole flow, including a click that should do nothing.</p><p>src/app/app.spec.ts</p><pre>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { App } from &#39;./app&#39;;<br><br>describe(&#39;App&#39;, () =&gt; {<br>  it(&#39;walks consent, typed confirmation and done in order&#39;, async () =&gt; {<br>    await TestBed.configureTestingModule({ imports: [App] }).compileComponents();<br>    const fixture = TestBed.createComponent(App);<br>    fixture.detectChanges();<br>    const el: HTMLElement = fixture.nativeElement;<br>    const q = &lt;T extends HTMLElement = HTMLElement&gt;(id: string): T | null =&gt;<br>      el.querySelector&lt;T&gt;(`[data-testid=&quot;${id}&quot;]`);<br>    // a click without a gesture does nothing<br>    q(&#39;approve&#39;)!.click();<br>    fixture.detectChanges();<br>    expect(q(&#39;typed&#39;)).toBeNull();<br>    // real pointer movement arms the gate<br>    document.dispatchEvent(new MouseEvent(&#39;mousemove&#39;, { clientX: 0, clientY: 0 }));<br>    document.dispatchEvent(new MouseEvent(&#39;mousemove&#39;, { clientX: 40, clientY: 40 }));<br>    fixture.detectChanges();<br>    q(&#39;approve&#39;)!.click();<br>    fixture.detectChanges();<br>    expect(q(&#39;typed&#39;)).not.toBeNull();<br>    const typed = q&lt;HTMLInputElement&gt;(&#39;typed&#39;)!;<br>    typed.value = &#39;Photo Printer&#39;;<br>    typed.dispatchEvent(new Event(&#39;input&#39;));<br>    fixture.detectChanges();<br>    q(&#39;confirm&#39;)!.click();<br>    fixture.detectChanges();<br>    expect(q(&#39;done&#39;)?.textContent).toContain(&#39;Access granted&#39;);<br>  });<br>});</pre><p>Run everything:</p><pre>ng test --no-watch</pre><p>Expected output (again, the CLI puts a check mark before each file):</p><pre>src/app/app.spec.ts (1 test)<br> src/app/consent.component.spec.ts (5 tests)<br> src/app/typed-confirm.component.spec.ts (2 tests)<br> src/app/gesture-gate.spec.ts (1 test)<br><br>Test Files  4 passed (4)<br>      Tests  9 passed (9)</pre><p>If you’d rather watch it by hand, run ng serve and open the page. You&#39;ll see a disabled Approve button and the hint. Move the mouse and the button wakes up. Click it, type the app&#39;s name, press Confirm, and the final message appears.</p><h3>So what were those headers protecting all along?</h3><p>Remember the question I planted at the start? Here’s the answer. X-Frame-Options and frame-ancestors protect your page from being framed by someone else’s page, which is the classic clickjacking attack. They do that job well, and you should keep them. They’re the right answer to a different question.</p><p>What changed is that your defenses now come in layers, each answering a different question. The framing headers cover your page living inside someone else’s frame. The gesture gate covers a click arriving that the user never aimed at your page. The typed confirmation covers whatever slips past both. You can paste all three from this article.</p><p>It’s Friday, 4:40 p.m. again, and the scanner is green again. This time you know what it can’t see. You pull up the list of one-click screens you wrote down earlier, and the report line changes from “Clickjacking: protected” to something more honest. Then you close the laptop.</p><p>If you know someone who ships consent screens or payment confirmations, send them this article. It might save them a very strange Monday.</p><h3>Bonus tips</h3><p><strong>Beginner.</strong> Take the list of screens that act on a single click and add data-sensitive to every dangerous button. Even if you do nothing else this week, that list is worth more than another header.</p><p><strong>Intermediate.</strong> Record how long passes between the window gaining focus and the Approve click, and send it with the request. I’d use it as a risk signal, not as a lock, and alert on a burst of instant approvals.</p><p><strong>Advanced.</strong> Browsers change. Script the parked-cursor check from the testing section in an end-to-end run for each engine you support, so a browser update that changes the behavior fails a test instead of surprising you in production.</p><h3>Recap</h3><p>DoubleClickjacking swaps the page under a user’s cursor between the two halves of a double-click, so the second click lands on your most sensitive button. Because your page is never framed, X-Frame-Options, frame-ancestors and SameSite cookies have nothing to catch, whether they’re set in NGINX, Apache, Cloudflare or CloudFront. The fix that holds up is on the client: keep sensitive buttons disabled until you see real interaction, guard against held keys and focus changes, and handle touch with a delay. Back it with a typed confirmation or step-up verification for the actions that matter most, and keep your framing headers for the classic attack.</p><p><strong>What did you think?</strong> Did this approach match how you are solving it, or do you have a different take? Drop a comment. I genuinely read every single one.</p><p><strong>Found this helpful?</strong> If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong> I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let us connect. Find me on LinkedIn or GitHub and let us keep the conversation going.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/"><strong>Reddit</strong></a> — Developer blog posts &amp; tech discussions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a86aa4e2144e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/doubleclick-jacking-why-your-clickjacking-headers-never-see-it-coming-a86aa4e2144e">DoubleClick jacking: Why Your Clickjacking Headers Never See It Coming</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pomodoro Timer That Survives You Closing the Tab]]></title>
            <link>https://javascript.plainenglish.io/the-pomodoro-timer-that-survives-you-closing-the-tab-0f817083c8fd?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f817083c8fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[pomodoro-technique]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[pomodoro-timer]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 15:32:59 GMT</pubDate>
            <atom:updated>2026-10-27T15:32:59.065Z</atom:updated>
            <content:encoded><![CDATA[<p><em>DeepWork is a free focus timer, task manager and calendar for Windows, macOS, Linux and the browser, and it keeps every record on your own disk</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1AAS59QZc_LHdi2qJ4kzw.png" /></figure><p>It is 2:47 in the afternoon and you have fourteen tabs open. One of them is a focus timer. You started a session in it an hour ago, then closed it along with the rest, because that is what you do with tabs.</p><p>Ninety seconds later you cannot remember whether you were twenty minutes in or forty. The session is gone. So is the intention behind it.</p><p>That is not a productivity problem. That is a software problem, and it is the one this article is about.</p><h3>Why every focus timer I have tried ends up closed</h3><p>The pattern is always the same shape, and I have been through it enough times to recognise it early.</p><p>You find a timer. It is beautiful. It asks you to create an account, or it asks you to pick a plan, or it explains that your sessions are syncing to the cloud so you can pick up on your phone. You enter your first task. You start a block. Somewhere in the second block a notification arrives telling you to hydrate, or that a teammate has commented on something.</p><p>By Thursday you have muted it. By Friday you have stopped opening it.</p><p>The timers that survive past a week tend to share one property: they behave like software on your computer rather than like a website you are visiting. They keep running when the window is small. They remember what you were doing. They stay quiet until the timer actually ends.</p><p>That is what I wanted, so I built it. It is called <a href="https://deepwork.rajatmalik.dev/">DeepWork</a>, it is free and open source under the MIT licence, and the rest of this article is what it does and why you might want it.</p><p>If you already know you want to look at it, <a href="https://app.deepwork.rajatmalik.dev/">open the web app</a> in the next thirty seconds and come back. Nothing to install, no account, no email field. The rest will still be here. And if you want to know when the next release lands, a follow is the cheapest way to find out.</p><h3>The one decision that shaped everything</h3><p>DeepWork has no account system. There is no sign in, no profile, no server of its own. Everything it knows lives in a SQLite database on the machine you are sitting at, in the folder your operating system keeps for applications.</p><p>I want to be precise about what that buys you, because “local first” gets used loosely.</p><p>It means your focus history for the last six months cannot disappear because a company changed its pricing. It means the app opens on a plane, with the Wi-Fi off, on the version you installed. It means nobody is A/B testing a redesign of your timer. And it means the only person who can read your journal entries is you, because there is nowhere for them to go.</p><p>Three things leave the machine, and I would rather list them than let you wonder. There is a once-per-startup check against GitHub to see whether a newer version exists. There is an installer download, but only if you press Update. And there are the links you click, which open in your real browser. That is the whole list. The browser build adds a visitor counter so the page can answer “is anyone actually using this”, and there is a switch in Settings that turns it off completely.</p><p>The trade for all of this is in a later section, and it is a real one. First, though, let me show you what a day with it looks like.</p><h3>A day with DeepWork, from the first block to the last</h3><p>I will not walk you through every screen. Ten pages is too many to describe in a row, and reading a feature list is not how anyone decides to use something. Instead, here is the day the app is shaped around.</p><h3>Morning: work out what actually matters</h3><p>You open DeepWork and land on the Dashboard. Twenty five minutes on the clock, a ring waiting to fill, a daily goal of eight sessions, and the tasks you have booked for today underneath it.</p><p>Behind that is the page I end up on most mornings. The Matrix is the Eisenhower grid, four quadrants and drag and drop between them. Do First, Schedule, Delegate, Eliminate. Dragging a card from Schedule to Do First is a fifteen second decision that saves you an hour of pretending everything is equally urgent.</p><p>The other thing that happens in the morning is the Today page. A task lands on today for one of three reasons: it is due today, it is overdue and still open, or you starred it. Starring is the override, and it is how you say “this one, today, whatever the date says”.</p><h3>The block itself: a timer that rings until you answer it</h3><p>You press Start, or you press Space if you are not typing in a field. The ring fills. Short break after the first three blocks, a longer one after the fourth, and you can change all of those lengths in Settings if twenty five and five are not your numbers.</p><p>When the block ends, the app does not send one polite chime and hope you noticed. It rings, shows a card, and posts a system notification, and then it repeats every interval you chose until you answer. Start, skip and stop all count as answers.</p><p>Two details here are the kind of thing you only notice after a week. Every repeat moves to the next colour of a twelve entry palette, so the alert you have been ignoring for six minutes is visibly a different colour than the one that started. And every alert carries its own line of text, drawn one per session from a list of twenty four for a finished focus block and twenty four more for the end of a break. Step away. Come back. It never shows you the same sentence twice in a row.</p><p>Ticking a task off is deliberately quieter. A card appears with a line from a third list, and no sound at all. You tick off tasks dozens of times a day; an app that rang for each one would train you to mute it, and then the session alert would be muted too.</p><h3>The middle of the day: shrink it and forget it</h3><p>This is the feature I would keep above all the others. DeepWork does not disappear into your other windows. Press minimise on any page and it does not vanish into the taskbar. It shrinks into a small always on top widget, 136 by 76 pixels, with the countdown ring, the time, and play, skip, stop and expand.</p><p>It sits in the corner over your editor while you actually do the work. You can start and pause without bringing the full window back. Press Escape and it grows back to exactly where it was.</p><p>And when you press the close button, the app does not quit. It goes to the system tray and keeps running, so a session can finish and ring while the window does not exist. Tray then Exit is what actually quits, and if you prefer the close button to quit, that is a setting.</p><p>The first launch asks you about three of these things before changing anything: start with the system, stay always on top, keep running in the tray. Nothing is enabled unless you say so. No installer writes a startup entry behind your back.</p><h3>Afternoon: the calendar that schedules in pomodoros</h3><p>The Calendar page is the one people underestimate. It shows you the day as events, and then does the scheduling arithmetic on top of it. It takes your quadrant order and lays your day out as focus blocks, at the block length and long break cadence your timer uses, so the day is planned in the same unit it is counted in.</p><p>A task that needs three blocks gets three. The breaks are reserved and never filled with work, which is the whole point of a break. If you drop something into a specific slot by hand, that slot is fixed and everything else flows around it.</p><p>Somewhere in the afternoon the water reminder asks you a question. It is on by default, it only fires inside the working hours you set, and it waits for an answer instead of announcing a fact. One glass counts as 30 millilitres by default, because the smallest thing anyone would call a drink is the honest unit for a day of sipping. If you minimise the window it logs the glass and leaves you alone rather than pulling the full app over your work.</p><p>The Habits page sits next to all this with current streaks, personal bests and a check-in strip per habit. Nothing clever. Just the thing that makes you not want to break the chain.</p><h3>Evening: the part that tells you what to change</h3><p>Most productivity apps hand you charts and let you draw the conclusion. Analytics in DeepWork pairs every number with a plain language reading of it.</p><p>Focus over the last seven days, with a hint telling you what the seven days before that looked like. Tasks closed, with a total underneath. Focus streak, with the number of active days behind it. Completion rate over thirty days, next to how many tasks are still open and how many are overdue. Habit consistency. Journal words over twelve weeks.</p><p>Those readings are arithmetic over your own records, computed on your machine, so the same week always produces the same reading. You can check any of them by opening the records they came from.</p><p>Then the Journal. Dated entries with word counts, a weekly words chart, and one figure I did not expect to find useful: the correlation between your writing and your focus. More words on the days you worked more blocks is either a good sign or a warning, and it is more useful to know which.</p><h3>The details you find by poking around</h3><p>Feature lists are boring. These are the things that made me keep a copy installed.</p><p><strong>Excel import that shows you what it will do before it does it.</strong> Tasks, then Import, accepts .xlsx, .xlsm and .csv, recognises the headers people actually write (Task, Due Date, Prio, Labels), validates every row, and writes nothing until you confirm the preview. Duplicate titles are labelled, and you choose whether to skip them. There is a download template with real dropdowns and an instructions sheet, if you want your spreadsheet to be valid before you start.</p><p><strong>Export that tells you where the file went.</strong> Twenty four columns per task, quick ranges like Today and Last 7 days, an optional totals block, and UTF-8 with a BOM so accents and non Latin scripts survive Excel. It writes into your Downloads folder, shows you the full path, and never overwrites: the second export of the day becomes export-2026-09-13 (2).csv.</p><p><strong>More than twenty keyboard shortcuts.</strong> Ctrl+1 through Ctrl+0 jump between pages. Ctrl+Shift+F is focus mode, which is the clock and nothing else. Space starts and pauses. With a task card focused, 1, 2 and 3 move it between To Do, In Progress and Done, the arrow keys walk it along the board, and Enter opens it for editing.</p><p><strong>Editing from wherever you are reading.</strong> Every card that shows a task carries the way into the same task form: a pencil on a board card, a pencil on a Matrix quadrant, one on a Calendar rail card, and Edit at the top of the Matrix right click menu. You never have to go and find the page that owns the task.</p><p><strong>A backup you can actually restore.</strong> Settings writes a single dated JSON file with your sessions, tasks, habits, journal and water records. Importing it overwrites what you have, after a confirmation, because it is a restore and not a merge.</p><p><strong>Diagnostics for when something breaks.</strong> Settings then Logs and Diagnostics shows you the app’s own logs, opens the folder, and has a Copy diagnostics button that puts the last three hundred lines plus your environment on the clipboard. If you ever report a bug, that is the thing to paste.</p><p><strong>Themes, fonts and no network.</strong> System, light and dark themes, two bundled typefaces, and no font CDN, so it looks like itself offline or behind a company proxy.</p><h3>What it is not, and the trade you are making</h3><p>I would rather you decide with the whole picture.</p><p><strong>It does not sync.</strong> Each machine has its own database. Moving your work between two computers means exporting the JSON on one and importing it on the other. There is no backend, and nothing arrives on your other device by itself.</p><p><strong>It is one person’s app.</strong> One developer, a public changelog, and issues on GitHub. There is no support team and no roadmap meeting.</p><p><strong>The installers are not code signed.</strong> This is the one that makes people nervous, so here is exactly what happens. On Windows you will see “Windows protected your PC” from SmartScreen, and the UAC dialog will say Unknown publisher. On macOS, Gatekeeper will refuse the first launch with a message about not being able to verify the app. Both are the absence of a signature worth several hundred dollars a year, not a sign of a broken download. If a release publishes a SHA-256 checksum, compare it before installing.</p><p><strong>The web build is the least private option of the three.</strong> Anything you do in a browser tab lives in that origin’s localStorage, and clearing site data erases it. If you want the real database, install the desktop app.</p><p><strong>It is not a team tool.</strong> No sharing, no assignment, no comments, no collaboration. One person, one database, by design.</p><p>If any of those are deal breakers, that is a fair answer, and the web app is still there for you to try before deciding.</p><h3>How to get it in the next five minutes</h3><p><strong>The fastest route is the browser.</strong> Open <a href="https://deepwork.rajatmalik.dev/">https://app.deepwork.rajatmalik.dev/</a>, and if you like it, install it as an app from your browser’s menu. In Chrome or Edge that is the install icon in the address bar. In Safari 17 or newer it is File, then Add to Dock. Firefox cannot install web apps, so use the desktop build there.</p><p><strong>The real thing is the desktop build</strong>, and it is on the <a href="https://github.com/malikrajat/deepwork/releases">releases page</a>. The source, the changelog and every issue live in the same repository at <a href="https://github.com/malikrajat/deepwork">github.com/malikrajat/deepwork</a>.</p><ul><li>Windows 10 and newer, 64 bit or 32 bit: an NSIS .exe setup or an .msi.</li><li>macOS: a .dmg, with separate builds for Intel and Apple Silicon.</li><li>Linux: an .AppImage, a .deb or an .rpm.</li></ul><p>There is also a page for it at<a href="https://app.deepwork.rajatmalik.dev/"> app.deepwork.rajatmalik.dev</a>.</p><p>Because nothing is signed, here is what gets you past it.</p><pre># Linux: make the AppImage runnable<br>chmod +x DeepWork_*.AppImage</pre><pre># macOS 15 and later: clear the quarantine flag after the first refusal<br>xattr -dr com.apple.quarantine /Applications/DeepWork.app</pre><p>On Windows, choose More info, then Run anyway, only if you trust the source. On macOS, the old Control click trick no longer works on recent versions; open System Settings, Privacy and Security, Security, and use Open Anyway after the first attempt.</p><p>Then let the first launch ask you its three questions, answer them honestly, and start a block.</p><h3>A ten minute tour, if you want the short version</h3><p>If you install it and then wonder where to begin, do these in order. It is the fastest way to find out whether it fits how you work.</p><ol><li>Press Ctrl+2 and add three tasks, starring the one you would do first if the day went well.</li><li>Press Ctrl+3 and drag those three into quadrants honestly, not optimistically.</li><li>Press Ctrl+4 and look at what your day becomes when it is laid out as blocks.</li><li>Go back to the Dashboard, press Space, and then press minimise. Watch what happens.</li><li>Let the block finish and ignore the alert for two minutes. Notice the colour has changed.</li><li>Press Ctrl+6 and read the hint under each number.</li><li>Open Settings and change one thing you dislike.</li></ol><p>Seven steps, ten minutes, and by the end you will know whether the shape of this app matches the shape of your day. If it does not, uninstall it; there is no account to delete and nothing to cancel.</p><h3>If something is missing, say so</h3><p>This is the part where a one person app genuinely needs you.</p><p>It is on its sixth tagged release, and the changelog in the repository is longer than this article. A good number of those fixes came from using it daily and writing down what annoyed me. The ones that did not came from people telling me.</p><p>So if you try it and something is wrong, the most useful things to send are concrete. What you did, what you expected, what happened instead, and which page you were on. If it is a crash or something looks broken, use Settings, Logs and Diagnostics, Copy diagnostics, and paste that in. It saves an hour of guessing.</p><p>Feature requests are welcome too, and the honest answer is sometimes no. If it is a no, you will get a why.</p><p>The two places to put it:</p><ul><li>An issue at <a href="https://github.com/malikrajat/deepwork/issues">github.com/malikrajat/deepwork/issues</a></li><li>An email to <a href="/service/mailto:mr.rajatmalik@gmail.com">support@rajatmalik.d</a>ev</li></ul><p>If you would rather just say it worked, that is also useful. Knowing which features people actually use is how the next version gets decided.</p><p>Have you ever abandoned a productivity app because it asked for an account on day one? I would like to know what pushed you off, because that list is the one I am trying to avoid.</p><h3>Back to that tab</h3><p>It is 2:47 in the afternoon and you have fourteen tabs open. One of them is DeepWork, because you installed it, and closing the tab does not matter any more.</p><p>The window is small, in the corner, over your editor. The ring is two thirds full. Your three tasks for today are on the board, one of them is in progress, and the fourth block is scheduled for after the break. The app is not asking you for anything.</p><p>When the block ends, it will ring, and it will keep ringing, and it will not stop until you decide you are done with it. That is the whole promise. The timer is the only thing that has to stop.</p><h3>If you try it</h3><p><strong>Tell me how it went.</strong> Did the ten minute tour match how you actually work, or did the app get in your way? Leave a comment, and if you found a bug, the issue link above is the fastest route. I read everything.</p><p><strong>Found this useful?</strong> If it saved you from another timer that forgets you the moment you close the tab, hit the clap button so more people find it. It genuinely helps a one person project more than it does a big one.</p><p><strong>Want the next one?</strong> I write about the tools I build and the decisions behind them, roughly once a week. Follow me here on Medium, where I am <a href="https://medium.com/@codewithrajat">@codewithrajat</a>, or subscribe to the newsletter so you do not miss the next release.</p><p>Let us connect. Find me on <a href="https://www.linkedin.com/in/errajatmalik/">LinkedIn</a> or <a href="https://github.com/malikrajat">GitHub</a> or <a href="https://deepwork.rajatmalik.dev/">https://rajatmalik.dev</a> and tell me what your day actually looks like. And if you know someone whose focus timer lives in a tab they keep closing, send them this article.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">Reddit</a>— Developer blog posts &amp; tech discussions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f817083c8fd" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-pomodoro-timer-that-survives-you-closing-the-tab-0f817083c8fd">The Pomodoro Timer That Survives You Closing the Tab</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 22.2 Explained: Router Resources, Error Boundaries, and Private Template Access]]></title>
            <link>https://javascript.plainenglish.io/angular-22-2-explained-router-resources-error-boundaries-and-private-template-access-40d077610a9d?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/40d077610a9d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 14:12:12 GMT</pubDate>
            <atom:updated>2026-10-20T14:12:12.247Z</atom:updated>
            <content:encoded><![CDATA[<h4>Three developer-preview features that quietly change how you load data, isolate failures, and structure components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBoiy4oT3xlvrp8_gVfPuQ.png" /></figure><p>Have you ever opened a page and watched it flicker through an empty state, a spinner, and finally real data, all because the component had to manage its own loading? Angular 22.2 gives us a cleaner way to handle this with router resources, and it ships two other changes worth knowing.</p><p>Since Angular now ships only one major release per year, the minors carry real weight. This one brings router resources, error boundaries (both in developer preview), and access to private members from templates.</p><p>If you like practical Angular breakdowns written like a chat between devs, follow me here on Medium so you do not miss the next one.</p><h3>What You Will Learn</h3><p>By the end of this article, you will know how to:</p><ul><li>Load data in the router with router resources, so your component receives the final value</li><li>Isolate failing child components with @boundary and @error</li><li>Use private members directly in templates, and why #private fields no longer fit</li><li>Write unit tests for each of these features</li></ul><blockquote><strong><em>Note:</em></strong><em> Before we dive into the examples, a quick note: the code snippets provided here are meant purely for understanding the concept. Some syntax shown may reflect patterns from earlier Angular versions, and the features covered here are in developer preview. Always refer to the official documentation for the most current API and syntax.</em></blockquote><h3>Feature 1: Angular Router Resources</h3><h3>The problem with loading inside the component</h3><p>Imagine a holidays page. A service creates a resource, and the component consumes it. The resource only starts when the component is created, and the component must handle the loading state, where the value may not exist yet.</p><p>Here is the typical setup. First, a small service that exposes a resource:</p><pre>// holiday.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { httpResource } from &#39;@angular/common/http&#39;;<br><br>export interface Holiday {<br>  id: number;<br>  title: string;<br>}<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class HolidayService {<br>  load() {<br>    return httpResource&lt;Holiday[]&gt;(() =&gt; &#39;/api/holidays&#39;);<br>  }<br>}</pre><p>This service is a plain injectable that returns an HTTP resource. Nothing is router-specific yet.</p><h3>Moving the resource into the router</h3><p>With router resources, the router starts loading during navigation and blocks until the data is ready. Your component then gets the final value.</p><p>Define the resource on the route:</p><pre>// app.routes.ts<br>import { inject } from &#39;@angular/core&#39;;<br>import { Routes } from &#39;@angular/router&#39;;<br>import { HolidayService } from &#39;./holiday.service&#39;;<br>import { HolidaysComponent } from &#39;./holidays.component&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;holidays&#39;,<br>    component: HolidaysComponent,<br>    resources: () =&gt; {<br>      const holidayService = inject(HolidayService);<br>      return {<br>        holidays: holidayService.load(),<br>      };<br>    },<br>  },<br>];</pre><p>The object literal’s key (holidays) is the name under which the loaded value reaches your component. The router also passes a context with params and query params as signals. That matters when a route ID changes, because you can feed that signal into the resource and it refreshes automatically.</p><h3>Receiving the value as a plain input</h3><pre>// holidays.component.ts<br>import { Component, input } from &#39;@angular/core&#39;;<br>import { Holiday } from &#39;./holiday.service&#39;;<br><br>@Component({<br>  selector: &#39;app-holidays&#39;,<br>  template: `<br>    @for (holiday of holidays(); track holiday.id) {<br>      &lt;article&gt;{{ holiday.title }}&lt;/article&gt;<br>    } @empty {<br>      &lt;p&gt;No holidays found.&lt;/p&gt;<br>    }<br>  `,<br>})<br>export class HolidaysComponent {<br>  readonly holidays = input.required&lt;Holiday[]&gt;();<br>}</pre><p>The component asks for a Holiday[], not a resource. It has no idea the data came from a resource, and the input is public because it is bound from outside.</p><h3>Enabling the feature</h3><p>You have to opt in explicitly in your app config:</p><pre>// app.config.ts<br>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideRouter, withRouterResources } from &#39;@angular/router&#39;;<br>import { provideHttpClient } from &#39;@angular/common/http&#39;;<br>import { routes } from &#39;./app.routes&#39;;<br><br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter(routes, withRouterResources()),<br>    provideHttpClient(),<br>  ],<br>};</pre><p>Now navigate Home, then Holidays. Loading starts early, inside the router navigation itself.</p><p>Where do you load data today: in the component, in a resolver, or in a store? Tell me in the comments and I will cover the migration path in a follow-up.</p><h3>Unit testing a component that receives router data</h3><p>Because the component just takes an input, testing is simple. No router needed:</p><pre>// holidays.component.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { HolidaysComponent } from &#39;./holidays.component&#39;;<br><br>describe(&#39;HolidaysComponent&#39;, () =&gt; {<br>  it(&#39;renders holidays passed in as input&#39;, async () =&gt; {<br>    const fixture = TestBed.createComponent(HolidaysComponent);<br>    fixture.componentRef.setInput(&#39;holidays&#39;, [<br>      { id: 1, title: &#39;Vienna&#39; },<br>      { id: 2, title: &#39;Lisbon&#39; },<br>    ]);<br>    await fixture.whenStable();<br>    const cards = fixture.nativeElement.querySelectorAll(&#39;article&#39;);<br>    expect(cards.length).toBe(2);<br>    expect(cards[0].textContent).toContain(&#39;Vienna&#39;);<br>  });<br>  it(&#39;shows the empty message when there are no holidays&#39;, async () =&gt; {<br>    const fixture = TestBed.createComponent(HolidaysComponent);<br>    fixture.componentRef.setInput(&#39;holidays&#39;, []);<br>    await fixture.whenStable();<br>    expect(fixture.nativeElement.textContent).toContain(&#39;No holidays found.&#39;);<br>  });<br>});</pre><p>The test uses setInput to simulate what the router will provide. That is a nice side effect of this design: the component stays easy to test.</p><h3>Feature 2: Angular Error Boundaries</h3><h3>Why one broken child hurts everyone</h3><p>Say the holidays page has two children, a title component and a holiday card. If one throws, the parent has a problem too. Here is a title component that fails on purpose:</p><pre>// title.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-title&#39;,<br>  template: `&lt;h1&gt;Holidays&lt;/h1&gt;`,<br>})<br>export class TitleComponent {<br>  constructor() {<br>    throw new Error(&#39;Title failed to initialize&#39;);<br>  }<br>}</pre><p>With this in place, the holidays page shows nothing at all.</p><h3>Isolating the failure with @boundary and @error</h3><p>Wrap the risky child in a boundary in the template:</p><pre>// holidays-page.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { TitleComponent } from &#39;./title.component&#39;;<br><br>@Component({<br>  selector: &#39;app-holidays-page&#39;,<br>  imports: [TitleComponent],<br>  template: `<br>    @boundary {<br>      &lt;app-title /&gt;<br>    } @error {<br>      &lt;h1&gt;Holidays&lt;/h1&gt;<br>    }<br>    &lt;section&gt;<br>      &lt;p&gt;The rest of the page still renders.&lt;/p&gt;<br>    &lt;/section&gt;<br>  `,<br>})<br>export class HolidaysPageComponent {}</pre><p>If app-title throws, the boundary catches it, the @error block acts as the fallback, and the rest of the page stays visible. There are more options, such as conditional catches, but this is the basic shape.</p><h3>Testing the fallback</h3><pre>// holidays-page.component.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { HolidaysPageComponent } from &#39;./holidays-page.component&#39;;<br><br>describe(&#39;HolidaysPageComponent&#39;, () =&gt; {<br>  it(&#39;shows the fallback and keeps the page alive when the title throws&#39;, async () =&gt; {<br>    const fixture = TestBed.createComponent(HolidaysPageComponent);<br>    await fixture.whenStable();<br>    const element: HTMLElement = fixture.nativeElement;<br>    expect(element.querySelector(&#39;h1&#39;)?.textContent).toContain(&#39;Holidays&#39;);<br>    expect(element.textContent).toContain(&#39;The rest of the page still renders.&#39;);<br>  });<br>});</pre><p>Because the child throws on purpose, this one test proves both the fallback and the isolation. Depending on how the test environment reports handled errors, you may need to adjust error handling in your test setup.</p><h3>Feature 3: Private Members in Templates</h3><p>Before 22.2, a template could only read members that were public or protected. That is why so much modern Angular code is full of protected.</p><pre>// summary.component.ts<br>import { Component, signal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-summary&#39;,<br>  template: `&lt;h2&gt;{{ title() }}&lt;/h2&gt;`,<br>})<br>export class SummaryComponent {<br>  private readonly title = signal(&#39;Summer Holidays&#39;);<br>}</pre><p>In 22.2, this just works. The reasoning from the Angular team is that the template and the TypeScript class form one unit, not two separate parts. Expect to see more private and fewer protected in modern Angular code.</p><p>There is one catch. ECMAScript private fields, the ones with hash notation, are private at runtime too, so the template cannot reach them:</p><pre>export class SummaryComponent {<br>  // This will NOT work in the template<br>  #title = signal(&#39;Summer Holidays&#39;);<br>}</pre><p>Switch to the TypeScript private keyword if the template needs the value.</p><h3>Testing it</h3><pre>// summary.component.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { SummaryComponent } from &#39;./summary.component&#39;;<br><br>describe(&#39;SummaryComponent&#39;, () =&gt; {<br>  it(&#39;renders a private signal in the template&#39;, async () =&gt; {<br>    const fixture = TestBed.createComponent(SummaryComponent);<br>    await fixture.whenStable();<br>    expect(fixture.nativeElement.querySelector(&#39;h2&#39;).textContent)<br>      .toContain(&#39;Summer Holidays&#39;);<br>  });<br>});</pre><p>Notice we test the rendered output, not the private member. That keeps tests focused on behavior.</p><p>Which of the three features will you adopt first? Vote in the comments: A) router resources, B) error boundaries, C) private in templates.</p><h3>Bonus Tips</h3><ul><li><strong>Feed route params into resources as signals.</strong> When the ID in the URL changes, the resource refreshes on its own, with no manual subscriptions.</li><li><strong>Keep fallbacks cheap.</strong> An @error block should be simple. A fallback that can also fail defeats the purpose.</li><li><strong>Place boundaries around risky areas only.</strong> Third-party widgets and optional panels are good candidates. Wrapping everything hides real bugs.</li><li><strong>Migrate </strong><strong>protected gradually.</strong> There is no need for a big-bang refactor. Switch to private when you touch a file anyway.</li><li><strong>Skim the changelog.</strong> This release has more changes than the three covered here.</li></ul><h3>Recap</h3><p>Angular 22.2 brings three notable changes. Router resources move data loading into the router, so your component receives the final value as a plain input. Error boundaries with @boundary and @error stop a single failing child from taking down the page. And private members can now be used in templates, reflecting that the template and class are one unit, though ECMAScript #private fields will not work there.</p><p>Both router resources and error boundaries have many more options than shown here. For the full picture, read the official documentation and the changelog, and look at the community’s videos and articles. Related reading: [link to your related Angular article here].</p><p>If this helped you, share it with a teammate or on social media. It is the easiest way to help another dev find it.</p><p><strong>What did you think?</strong></p><p>Did this approach match how you are solving it, or do you have a different take? Drop a comment. I genuinely read every single one.</p><p><strong>Found this helpful?</strong></p><p>If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong></p><p>I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let us connect. Find me on LinkedIn or GitHub and let us keep the conversation going.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">Reddit</a> — Developer blog posts &amp; tech discussions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40d077610a9d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-22-2-explained-router-resources-error-boundaries-and-private-template-access-40d077610a9d">Angular 22.2 Explained: Router Resources, Error Boundaries, and Private Template Access</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Browser Error Tracking: The Errors Your SDK Never Sends]]></title>
            <link>https://javascript.plainenglish.io/browser-error-tracking-the-errors-your-sdk-never-sends-05e2e87712fe?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/05e2e87712fe</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 12:00:49 GMT</pubDate>
            <atom:updated>2026-10-14T12:00:49.198Z</atom:updated>
            <content:encoded><![CDATA[<h4>An offline-first browser error tracking pipeline that runs inside the failure path, redacts before it stores anything, and slows one repeating failure instead of a whole page.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZXwrVC4Tzw3MUtU-E3EpA.png" /></figure><p>You are on a call with support. A customer says checkout failed twice this morning. Then it worked. You ask them for the browser console, they send a screenshot, and the console is empty, because the page has been reloaded twice since then. The network tab is gone with it. What you have is one sentence and a timestamp.</p><p>Somewhere in your dashboard, that customer has no error. Not a wrong error, not a truncated stack, just nothing. Which means the dashboard is telling you a story about happy users, and the users who are quietly giving up look exactly the same as them.</p><p>So here is the question that decides whether your browser error tracking is useful or decorative: what happens to the errors that never reach your tracker at all?</p><p>Between here and there you will build a capture pipeline that stores locally before it ever touches the network, redacts before it writes anything, slows one repeating failure without silencing the new ones, and ends in a single HTML file that a support engineer can open and read.</p><p>Keep one question in mind while you read, because I answer it near the end. Where does an error go when it is thrown before your tracker starts, and the tab closes a second later?</p><p>If debugging is the part of the job you actually like, follow me here on Medium. I publish one practical frontend piece a week and I reply to comments. If someone on your team owns the error dashboard, send them this.</p><h3>Why browser error tracking fails at the worst possible moment</h3><p><strong>Quick version.</strong> Your reporter is a handful of lines that run after something already went wrong. One call at startup, one call per failure you handle yourself, and a way to get the results out. In the version I use below, that startup call captures uncaught errors, unhandled promise rejections and everything logged at warn or above into IndexedDB, and the results come out when someone presses Ctrl+Shift+Alt+D. It is the smallest piece of your error handling, which is exactly why it gets the least attention.</p><p><strong>Real-world version.</strong> The failure modes are not exotic. They are the ordinary consequences of running code in a hostile moment.</p><p>A convenience reporter that touches error.message on a thrown value that is not an Error throws a second exception inside your catch block. A fetch call that is not keepalive gets cancelled when the tab closes, so the error you captured during pagehide never leaves the browser. A URL pasted into a payload carries whatever token a user’s password reset link had in the query string. One broken polling endpoint produces the same error every five seconds until it owns your entire rate limit, and the genuinely new failure that happened at minute three is the one that gets dropped. Any script loaded from a third-party origin can be blocked by an extension or a strict Content Security Policy, and when that happens capture stops silently.</p><p><strong>Under the hood.</strong> These are not separate bugs to fix one at a time. They come from one design decision: whether the reporting path is allowed to fail. The library I use in the examples below makes five promises to itself, and each one kills a class of the failures above.</p><p>It cannot throw, so a hostile value cannot turn reporting into a second crash. It cannot recurse, because a flag drops anything raised while the pipeline is already running. It cannot double count, because a WeakMap remembers the error objects it has already seen. It cannot flood, because a fixed-window limiter drops the excess. It cannot lose pre-init errors, because failures thrown before initTelemetry runs are normalised immediately and replayed once the application metadata exists.</p><p><strong>Teaser.</strong> Which brings us to the smallest and most important function in the whole system, the one that people write in thirty seconds and regret for a year.</p><blockquote><em>Before we get into the examples, a quick note: The code snippets provided here are meant purely for understanding the concept. Some syntax shown may reflect patterns from earlier Angular/React versions. Always refer to the official documentation for the most current API and syntax.</em></blockquote><h3>The reporter that throws while it reports</h3><p><strong>Quick version.</strong> Here is a helper that a lot of codebases have somewhere, and it looks fine.</p><pre>// shared/report-error.ts<br>export function reportError(error: unknown): void {<br>  const payload = JSON.stringify({<br>    message: (error as Error).message,<br>    stack: (error as Error).stack,<br>    url: window.location.href,<br>  });<br><br><br><br>void fetch(&#39;/telemetry/errors&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: payload,<br>  });<br>}</pre><p>It compiles, it runs, and in development it even works. Then production hands it a value that is not an Error, and the same helper fails in four different ways.</p><p>(error as Error).message on a thrown string returns undefined and you log an empty record. On null it throws a TypeError, and because this ran inside your own catch block, the original failure is replaced by a new one. window.location.href includes the query string, so a reset link with a token in it is now in your telemetry. And fetch without keepalive is dropped by the browser when the page is closing, which is when the errors you most want are captured.</p><p><strong>Real-world version.</strong> The fix is not to write a longer version of the same function. It is to route every capture through one ingestion point that owns normalisation, redaction and persistence.</p><pre>// shared/telemetry.ts<br>import { captureError, initTelemetry, logger } from &#39;@codewithrajat/rm-logvault&#39;;<br><br><br><br>initTelemetry({<br>  appName: &#39;checkout&#39;,<br>  appVersion: &#39;2.4.1&#39;,<br>  environment: &#39;production&#39;,<br>});<br>export function reportCheckoutFailure(error: unknown, orderId: string): void {<br>  captureError(error, {<br>    tags: { flow: &#39;checkout&#39;, route: &#39;/checkout/:orderId&#39; },<br>    extra: { orderId },<br>    severity: &#39;error&#39;,<br>  });<br>  logger.warn(&#39;[Checkout] payment attempt failed&#39;, { orderId });<br>}</pre><p>Note what is missing. No window.location.href, because the record picks up page context itself. No .message access, because captureError accepts unknown and normalises whatever it gets. No await, because capturing is fire-and-forget and the write is queued locally before any network is involved.</p><p>The library is @codewithrajat/rm-logvault, published on <a href="https://www.npmjs.com/package/@codewithrajat/rm-logvault">npm</a> with the source on <a href="https://github.com/malikrajat/rm-logvault">GitHub</a>.</p><p>The thrown value is the first argument, which makes the helper safe to call from any catch block you already have, including the one that rethrows.</p><pre>// checkout-api.ts<br>import { reportCheckoutFailure } from &#39;./telemetry&#39;;<br><br><br>export async function payForOrder(orderId: string): Promise&lt;void&gt; {<br>  try {<br>    await postPayment(orderId);<br>  } catch (error) {<br>    reportCheckoutFailure(error, orderId);<br>    throw error;<br>  }<br>}</pre><p>The record that lands in IndexedDB after payForOrder(&#39;A-1024&#39;) fails looks like this, trimmed to the fields that matter.</p><pre>{<br>  &quot;schemaVersion&quot;: 1,<br>  &quot;source&quot;: &quot;manual&quot;,<br>  &quot;severity&quot;: &quot;error&quot;,<br>  &quot;handled&quot;: true,<br>  &quot;thrownType&quot;: &quot;error&quot;,<br>  &quot;name&quot;: &quot;Error&quot;,<br>  &quot;message&quot;: &quot;Payment provider returned 502&quot;,<br>  &quot;fingerprint&quot;: &quot;3f2c81a9c4b7d0e5&quot;,<br>  &quot;occurrenceCount&quot;: 1,<br>  &quot;tags&quot;: { &quot;flow&quot;: &quot;checkout&quot;, &quot;route&quot;: &quot;/checkout/:orderId&quot; },<br>  &quot;extra&quot;: { &quot;orderId&quot;: &quot;A-1024&quot; },<br>  &quot;page&quot;: { &quot;url&quot;: &quot;&lt;https://shop.example.com/checkout&gt;&quot;, &quot;route&quot;: &quot;/checkout&quot;, &quot;pageLoadId&quot;: &quot;pl_8f13&quot; },<br>  &quot;uploadStatus&quot;: &quot;pending&quot;<br>}</pre><p><strong>Under the hood.</strong> Normalisation is where most of the work hides. A thrown string, a thrown number, a rejected Promise with a plain object, a Proxy whose getter raises, an AggregateError, a cause chain four levels deep: all of them have to become the same shape without ever throwing. The pipeline records thrownType so you can tell a real Error from an object someone rejected with, keeps up to three links of the cause chain, and reads at most five sub-errors from an AggregateError.</p><p>When the pipeline itself fails, it does not surface a new error to the user. It reports through an internal channel that fires once per stage, which is why a broken storage layer produces one warning instead of one warning per captured error.</p><p>If you have a value that must become a real Error before it reaches code that expects one, toError does that without stringifying anything hostile that came in with it.</p><p><strong>Teaser.</strong> Capturing locally is cheap. Deciding when those records travel, and what happens when they cannot, is the part people get wrong next.</p><h3>Where do browser errors go when the network is down?</h3><p><strong>Quick version.</strong> Nowhere, and that is the point. The default configuration stores everything in IndexedDB and makes no network request at all.</p><pre>// main.ts<br>import { initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br><br><br>initTelemetry({ appName: &#39;checkout&#39;, appVersion: &#39;2.4.1&#39; });</pre><p>Two databases are created, rm-logvault-errors and rm-logvault-logs. Errors are capped at 500 rows kept for 7 days, logs at 2000 rows kept for 3 days. Nothing is sent anywhere, which is why this works with no backend, in an air-gapped build, and in a page with a locked-down CSP.</p><p><strong>Real-world version.</strong> The turning point here is a design decision rather than a feature: nothing travels straight from the failure to the network. A queue that only lives in memory is not a queue, and the interesting moments are the ones where the page is going away.</p><p>The library flushes the write buffer on pagehide and on visibilitychange when the page becomes hidden, and it asks the uploader for a keepalive drain at the same time. That combination is what stops the last thirty seconds of a session from disappearing with the tab. It is also why a burst of logs can still be lost, since the buffer holds entries for up to a second before writing unless the batch size is reached first.</p><p>Storage is not guaranteed either. Private browsing modes, a full origin quota, and a corrupted database all happen, and the quota rules are set by the browser rather than by you, as covered in <a href="https://web.dev/articles/storage-for-the-web">Storage for the web</a>. When opening the database fails, storage moves to unavailable and the library keeps working with the console only, because losing diagnostics is much less bad than breaking the application.</p><pre>// support-tools.ts<br>import { getTelemetryStatus } from &#39;@codewithrajat/rm-logvault&#39;;<br><br><br>export function describeTelemetry(): string {<br>  const status = getTelemetryStatus();<br>  return `mode=${status.mode} storage=${status.storage} pending=${status.pending.errors}/${status.pending.logs} dropped=${status.droppedByRateLimit}`;<br>}</pre><p><strong>Under the hood.</strong> What sits on top of IndexedDB is an outbox. A write is a pending row. A sync run claims rows atomically, sends them, and marks them uploaded. Claiming matters for correctness, not performance: with two tabs open, two sync loops would otherwise upload the same record twice.</p><pre>captureError(error, ctx)<br>        |<br>        v<br>  normalize -&gt; fingerprint -&gt; already seen this Error object?<br>        |                          |<br>        |                    merge tags/extra onto the pending row<br>        v<br>  sanitize (redact + bound) -&gt; IndexedDB row (pending, occurrenceCount)<br>        |<br>        v<br>  outbox: claim -&gt; send -&gt; mark uploaded | retry with backoff | mark failed<br>        |<br>        v<br>  HTML report (Ctrl+Shift+Alt+D) / json / jsonl / csv</pre><p>Aggregation only ever touches pending rows. A row that is being uploaded is immutable, because rewriting a record after it has left the browser would make the server copy and the local copy disagree with each other and with their own fingerprint.</p><p><strong>Teaser.</strong> None of that queue matters if the thing you are queueing is a customer’s session token.</p><h3>Redaction should happen before storage, not before upload</h3><p><strong>Quick version.</strong> Records are scrubbed on the way in. A key named token, email, password or authorization becomes [REDACTED] regardless of nesting, and the same happens inside free text.</p><pre>// shared/telemetry.ts<br>import { captureError, initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br><br><br>initTelemetry({<br>  appName: &#39;checkout&#39;,<br>  redaction: {<br>    extraSensitiveKeys: [&#39;orderReference&#39;],<br>    allowedQueryParams: [&#39;page&#39;, &#39;locale&#39;],<br>  },<br>});<br>captureError(new Error(&#39;card declined for user@example.com&#39;), {<br>  extra: { accessToken: &#39;sk_live_51H8x&#39;, locale: &#39;en-GB&#39; },<br>});</pre><p>The stored record keeps the shape of your object and none of the secrets.</p><pre>{<br>  &quot;message&quot;: &quot;card declined for [REDACTED]&quot;,<br>  &quot;extra&quot;: { &quot;accessToken&quot;: &quot;[REDACTED]&quot;, &quot;locale&quot;: &quot;en-GB&quot; }<br>}</pre><p><strong>Real-world version.</strong> Redacting on the server is the common mistake, and it is a mistake even when the server is yours. The data has already crossed the network, sat in a request log, and been handled by whatever sits in front of your API. Redacting in the browser before the write means the plaintext value never exists in any store you have to audit later.</p><p>The second common mistake is assuming the redactor only looks at keys. It also scans text, because phone=+14150000000 in a log message leaks the same value as { phone: &#39;+14150000000&#39; } would. The sensitive-key match is done against a lowercased key with separators stripped, so access_token, accessToken and ACCESS TOKEN all resolve to the same decision. Free text gets JWT-shaped strings, Bearer and Basic schemes, e-mail addresses, and token=... style pairs scrubbed, along with long opaque runs of 32 to 200 word characters, which is the shape of a leaked API key or a dashless UUID.</p><p>Query strings follow a different rule, because dropping every value would make a URL useless. Values survive only for parameter names on an allow-list, which by default is limit, offset, page, pageSize, size, sort, order, scope, lng, lang and type. A URL that is really an identifier gets replaced with a placeholder, and the fingerprint normalises those placeholders so /orders/8842 and /orders/9917 group as one bug.</p><p><strong>Under the hood.</strong> The sanitizer is one instance reached through getDefaultSanitizer(), and it is wired before anything can capture, not after.</p><p>The stronger half of the privacy claim is what is never read at all, since there is no rule to get wrong when there is no read. Request and response bodies are never touched, including axios data and params. Cookies and document.cookie are never read. localStorage and sessionStorage are never read, because the vault is separate storage rather than a view over yours. Auth header values are never read, and only four named correlation headers are probed by name for a request id. Form values are never read. The only DOM element the library inspects is the shortcut’s own event target, and only to decide whether to stop.</p><p>Bounding is as important as removing. Text is truncated before any pattern runs, so the regular expressions cannot be driven into a pathological backtrack. Values are walked to a depth of four, thirty keys, twenty array items, two thousand characters per string. Records are then reduced against a byte budget, 16 KB for errors and 4 KB for logs, so one enormous stack trace cannot block the write queue.</p><p>Which of your own query parameters would survive that allow-list? Open one real production URL from your application and look at what the key names are. If an identifier you did not expect is in the list, you just found a leak before an auditor did.</p><p><strong>Teaser.</strong> A redacted record is still capable of drowning out the record that matters.</p><h3>One failing poll should not bury every other error</h3><p><strong>Quick version.</strong> Identical failures aggregate into one row with an occurrenceCount, so a thousand repeats cost one row instead of a thousand.</p><pre>// shared/telemetry.ts<br>import { captureError, flushTelemetry, initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br>import { createMemoryRepository } from &#39;@codewithrajat/rm-logvault/testing&#39;;<br><br><br>const repository = createMemoryRepository();<br>initTelemetry({ appName: &#39;checkout&#39;, repository, shortcut: false });<br>for (let attempt = 0; attempt &lt; 5; attempt += 1) {<br>  captureError(new Error(&#39;orders refresh failed&#39;), { tags: { poll: &#39;true&#39; } });<br>}<br>await flushTelemetry();<br>const rows = repository.errors.all();<br>// rows.length === 1, rows[0].occurrenceCount === 5</pre><p><strong>Real-world version.</strong> Aggregation alone does not save you, and this is the bug I see most often in hand-rolled trackers. A global limit answers “how many errors may this page produce per minute”. It does not answer “may this one error be produced again”. A poll that refetches every five seconds and fails every time spends a tenth of a 120-per-minute budget on a failure that is already sitting in the report. Ten endpoints failing on that cadence exhaust the budget completely, and the new failure at minute three is the one that gets dropped, which is the exact opposite of what you want.</p><p>The fix is a second limiter, per fingerprint, consulted before the global one. Twelve repeats per minute by default. A repeat that is refused does not consume the global budget, so the budget goes to failures nobody has seen yet.</p><pre>// shared/telemetry.ts<br>import { initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>initTelemetry({<br>  appName: &#39;checkout&#39;,<br>  errors: {<br>    maxEventsPerMinute: 120,<br>    maxRepeatsPerMinute: 12,<br>  },<br>});</pre><p>A wrong version that still runs, and still looks reasonable, is deduplicating on the full stack including line numbers.</p><pre>// shared/dedupe-error.ts<br>const seen = new Set&lt;string&gt;();<br><br><br>export function isDuplicate(error: Error): boolean {<br>  const key = `${error.message}:${error.stack ?? &#39;&#39;}`;<br>  if (seen.has(key)) return true;<br>  seen.add(key);<br>  return false;<br>}</pre><p>Every deploy shifts line numbers, so every deploy creates a brand new group for a bug you already knew about. The set also grows without bound for the lifetime of the page. Dropping the stack and deduping on the message alone fails in the other direction, collapsing two unrelated failures that happen to share a message.</p><p>Have you ever lost an evening to a bug like one of these, where the tooling lied to you about what happened? Tell me what it was in the comments, because these are usually more interesting than the fix.</p><p><strong>Under the hood.</strong> A fingerprint is built from the source, the normalised message, the top stack frames, and a path with identifiers replaced. It is hashed with cyrb53 rather than a cryptographic hash, because this value is a grouping key, not a security boundary, and the whole thing has to stay small and fast on the error path.</p><p>Two layers of dedupe run before any of that. Capturing the same Error object twice, once from a React boundary and once from window.onerror, does not create two records, because the object identity is remembered in a WeakMap. The second capture is not wasted either. It can merge severity, tags and extra onto the row that already exists, which is how a global handler’s generic capture gets upgraded by the caller that actually knew where the failure came from.</p><p>message, stack, category, page and environment are deliberately not patchable. They describe the occurrence, and the first capture recorded them. Changing them afterwards would leave a stored record disagreeing with its own fingerprint.</p><p>The aggregate itself is mutable by design: a repeat widens lastSeen and increments occurrenceCount on the pending row. Repeat throttling is the same mechanism that keeps that update path from becoming a write storm.</p><p><strong>Teaser.</strong> Everything so far assumes your code threw the error. A lot of real browser failures never reach a try block at all.</p><h3>The errors a window.onerror handler cannot see</h3><p><strong>Quick version.</strong> Two of these are off by default, because capturing them changes behaviour for the host page. The third is on by default, and the snippet below sets all three so you can see where they live.</p><pre>// shared/telemetry.ts<br>import { initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br><br><br>initTelemetry({<br>  appName: &#39;checkout&#39;,<br>  errors: {<br>    captureResources: true,<br>    captureCsp: true,<br>    captureChunkErrors: true,<br>  },<br>});</pre><p>Resource failures cover a &lt;script&gt; or &lt;link&gt; that failed to load. CSP violations arrive as securitypolicyviolation events. Chunk errors are dynamic import failures, and they are on by default because a stale chunk after a deploy is one of the most common production-only failures there is.</p><p><strong>Real-world version.</strong> Each of these has a reason to be invisible by default.</p><p>A resource error does not bubble, so a listener on the document in the bubble phase never sees it, which is why the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event">error event</a> has to be caught during capture. A CSP violation is not an error at all, it is an event with a blockedURI and a directive. And a cross-origin script that throws produces the message Script error. with no stack and no details, which is a browser security decision rather than a bug in your tracker. The same rule applies to rejected promises from cross-origin scripts, which do not fire unhandledrejection at all, as documented on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event">MDN</a>.</p><p>Dynamic imports need one more thing, because the failure happens before any component or route handler is running. withChunkCapture wraps the loader and attaches the route pattern.</p><pre>// orders.routes.ts<br>import { withChunkCapture } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>export const loadOrderDetail = withChunkCapture(<br>  &#39;/orders/:id&#39;,<br>  () =&gt; import(&#39;./pages/order-detail&#39;),<br>  { tags: { flow: &#39;order-detail&#39; } },<br>);<br>export async function openOrder(orderId: string): Promise&lt;void&gt; {<br>  try {<br>    await loadOrderDetail();<br>  } catch {<br>    offerReload();<br>  }<br>}</pre><p>The record from that failure carries source: &#39;chunk&#39; and fatal severity, which is what makes “the deploy broke lazy loading” a query rather than a hunch.</p><p><strong>Under the hood.</strong> Angular and React both funnel framework failures into the same ingestion point, which is the only reason the grouping works across boundaries. Angular’s <a href="https://angular.dev/api/core/ErrorHandler">ErrorHandler</a> is an injectable class, so the adapter subclasses it, reports, and then delegates to console.error so the framework’s own diagnostics are unchanged. React 19 added root level error callbacks to <a href="https://react.dev/reference/react-dom/client/createRoot">createRoot</a>, and the adapter exposes them as a spreadable bundle.</p><p>Workers are their own case, because a worker has its own global scope. The worker adapter listens for error and messageerror inside the worker and forwards the failure, which is the only way an uncaught exception in a worker stops being silent.</p><p>If your application knows something the library cannot, a context builder is the hook for it. Registration is by name, a second registration under the same name replaces the first, and a throwing builder falls through to the next one instead of swallowing the capture.</p><pre>// shared/telemetry.ts<br>import { registerErrorContextBuilder } from &#39;@codewithrajat/rm-logvault&#39;;<br><br><br>const unregister = registerErrorContextBuilder({<br>  name: &#39;feature-flag-failures&#39;,<br>  canHandle: (error) =&gt; error instanceof Error &amp;&amp; error.message.includes(&#39;flag&#39;),<br>  build: (error) =&gt; ({<br>    tags: { subsystem: &#39;feature-flags&#39; },<br>    extra: { flagMessage: error instanceof Error ? error.message : &#39;unknown&#39; },<br>  }),<br>});<br>// Later, on teardown. Safe to call twice.<br>unregister();</pre><p><strong>Teaser.</strong> Two of those boundaries are in frameworks you are already using, and wiring them the wrong way is how people end up with a capture from a component that React never actually failed on.</p><h3>Wiring React and Angular error boundaries without replacing them</h3><p><strong>Quick version.</strong> In React, an error boundary that reports is a class component, because that is still how boundaries work.</p><pre>// app-root.tsx<br>import { TelemetryErrorBoundary } from &#39;@codewithrajat/rm-logvault/react&#39;;<br>import { App } from &#39;./app&#39;;<br><br><br>export function AppRoot() {<br>  return (<br>    &lt;TelemetryErrorBoundary<br>      fallback={(error, reset) =&gt; (<br>        &lt;div&gt;<br>          &lt;p role=&quot;alert&quot;&gt;Something went wrong: {error.message}&lt;/p&gt;<br>          &lt;button type=&quot;button&quot; onClick={reset}&gt;<br>            Try again<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &gt;<br>      &lt;App /&gt;<br>    &lt;/TelemetryErrorBoundary&gt;<br>  );<br>}</pre><p><strong>Real-world version.</strong> A boundary catches render failures in the tree below it. It does not catch a failure in an event handler, and React 19 added root level callbacks for the ones that never reach a boundary at all. Use both, and do not fight the framework: spread the root handlers into createRoot rather than rewriting the boundary.</p><pre>// main.tsx<br>import { StrictMode } from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br>import { reactRootErrorHandlers } from &#39;@codewithrajat/rm-logvault/react&#39;;<br>import { AppRoot } from &#39;./app-root&#39;;<br><br><br>const container = document.getElementById(&#39;root&#39;);<br>if (container === null) throw new Error(&#39;missing #root element&#39;);<br>createRoot(container, reactRootErrorHandlers({ tags: { shell: &#39;checkout&#39; } })).render(<br>  &lt;StrictMode&gt;<br>    &lt;AppRoot /&gt;<br>  &lt;/StrictMode&gt;,<br>);</pre><p>For a failure you handle yourself, a hook keeps the context consistent and gives you a function that is safe to call from a handler or an effect.</p><pre>// checkout-panel.tsx<br>import { useState } from &#39;react&#39;;<br>import { useErrorCapture } from &#39;@codewithrajat/rm-logvault/react&#39;;<br>import { payForOrder } from &#39;./pay-for-order&#39;;<br><br><br>export function CheckoutPanel({ orderId }: { readonly orderId: string }) {<br>  const capture = useErrorCapture({ tags: { flow: &#39;checkout&#39; } });<br>  const [status, setStatus] = useState&lt;&#39;idle&#39; | &#39;paying&#39; | &#39;failed&#39;&gt;(&#39;idle&#39;);<br>  async function pay(): Promise&lt;void&gt; {<br>    setStatus(&#39;paying&#39;);<br>    try {<br>      await payForOrder(orderId);<br>      setStatus(&#39;idle&#39;);<br>    } catch (error) {<br>      setStatus(&#39;failed&#39;);<br>      capture(error, { extra: { orderId } });<br>    }<br>  }<br>  return (<br>    &lt;section&gt;<br>      {status === &#39;failed&#39; ? &lt;p role=&quot;alert&quot;&gt;Payment failed. Try again.&lt;/p&gt; : null}<br>      &lt;button type=&quot;button&quot; onClick={() =&gt; void pay()}&gt;<br>        Pay<br>      &lt;/button&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>In Angular the integration is a provider, and the default handler stays in place underneath it.</p><pre>// main.ts<br>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br>import { provideTelemetryErrorHandler } from &#39;@codewithrajat/rm-logvault/angular&#39;;<br>import { captureError, initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>initTelemetry({ appName: &#39;checkout&#39;, appVersion: &#39;2.4.1&#39; });<br>bootstrapApplication(AppComponent, {<br>  providers: [provideTelemetryErrorHandler({ tags: { shell: &#39;checkout&#39; } })],<br>}).catch((error: unknown) =&gt; {<br>  // Bootstrap failures happen before any handler exists, so they are captured explicitly.<br>  captureError(error, { source: &#39;manual&#39;, severity: &#39;fatal&#39; });<br>});</pre><p>The provider uses a factory rather than a class provider on purpose, so it does not require emitDecoratorMetadata in your tsconfig. A component that handles a failure itself looks like this.</p><pre>// order-detail.component.ts<br>import { Component, inject, input, signal } from &#39;@angular/core&#39;;<br>import { captureError } from &#39;@codewithrajat/rm-logvault&#39;;<br>import { OrdersApi } from &#39;./orders-api&#39;;<br>import type { OrderLine } from &#39;./order-line&#39;;<br><br><br>@Component({<br>  selector: &#39;app-order-detail&#39;,<br>  template: `<br>    &lt;h2&gt;Order {{ orderId() }}&lt;/h2&gt;<br>    @if (status() === &#39;error&#39;) {<br>      &lt;p role=&quot;alert&quot;&gt;We could not load this order.&lt;/p&gt;<br>    }<br>    @for (line of lines(); track line.sku) {<br>      &lt;p&gt;{{ line.sku }} x {{ line.quantity }}&lt;/p&gt;<br>    }<br>    &lt;button type=&quot;button&quot; (click)=&quot;load()&quot;&gt;Retry&lt;/button&gt;<br>  `,<br>})<br>export class OrderDetailComponent {<br>  readonly orderId = input.required&lt;string&gt;();<br>  readonly lines = signal&lt;readonly OrderLine[]&gt;([]);<br>  readonly status = signal&lt;&#39;idle&#39; | &#39;loading&#39; | &#39;error&#39;&gt;(&#39;idle&#39;);<br>  private readonly api = inject(OrdersApi);<br>  async load(): Promise&lt;void&gt; {<br>    this.status.set(&#39;loading&#39;);<br>    try {<br>      this.lines.set(await this.api.load(this.orderId()));<br>      this.status.set(&#39;idle&#39;);<br>    } catch (error) {<br>      this.status.set(&#39;error&#39;);<br>      captureError(error, {<br>        tags: { route: &#39;/orders/:id&#39;, flow: &#39;order-detail&#39; },<br>        extra: { orderId: this.orderId() },<br>      });<br>    }<br>  }<br>}</pre><p><strong>Under the hood.</strong> The reason both frameworks funnel into one place is deduplication. A failure that reaches a boundary and also reaches the root is one failure, and object identity is what makes the second capture merge into the first rather than double up. That is also why both adapters swallow their own exceptions: a reporting call that throws inside componentDidCatch turns a handled render failure into an unhandled one.</p><p>The Angular adapter only reports and delegates. It never replaces the default console output, so an Angular developer’s usual error messages stay exactly where they were, and the adapter works whether the application uses bootstrapApplication or an older bootstrap path.</p><p><strong>Teaser.</strong> At this point the vault has everything. Somebody still has to get it out and read it.</p><h3>From a support ticket to one self-contained HTML report</h3><p><strong>Quick version.</strong> Press Ctrl+Shift+Alt+D in the page, and a single HTML file downloads. The default shortcut is registered at startup, so there is nothing to wire.</p><pre>// support-tools.ts<br>import { exportDiagnosticsReport, logger } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>export async function downloadReport(): Promise&lt;void&gt; {<br>  const result = await exportDiagnosticsReport({ format: &#39;html&#39; });<br>  logger.info(`report ok=${String(result.ok)} bytes=${String(result.bytes)}`);<br>}</pre><p><strong>Real-world version.</strong> The shortcut gets you a file. It does not get you the right file, and it does not get you the record the support agent needs to read.</p><p>Four formats exist for four different readers. html is the one a support engineer opens, and it embeds the raw payload so the file is complete on its own. json is one document for a script. jsonl is one object per line, which is the format that survives grep and jq. csv is a flat table you can open in a spreadsheet when someone asks for a summary by route.</p><p>Two details are worth knowing before you hand the shortcut to everyone. The default gate allows it for anyone in the page, so gate it yourself with allow, and use redactAgain when the records were written before your redaction configuration changed.</p><pre>// shared/telemetry.ts<br>import { initTelemetry, logger } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>initTelemetry({<br>  appName: &#39;checkout&#39;,<br>  shortcut: {<br>    key: &#39;d&#39;,<br>    filenamePrefix: &#39;checkout-diagnostics&#39;,<br>    allow: () =&gt; isInternalUser(),<br>    onExported: (ok) =&gt; {<br>      logger.info(`[Diagnostics] export finished ok=${String(ok)}`);<br>    },<br>  },<br>});</pre><p>The library exposes the same shortcut as obscurity, not access control. Anyone who knows the key combination can press it, which is why the report is scrubbed twice rather than trusting the records to be safe.</p><p><strong>Under the hood.</strong> A report is an HTML file that a user e-mails to somebody else, so it has to be unable to execute anything. Three rules make that true: record data is escaped rather than interpolated into markup, the viewer never touches innerHTML, and the file fetches nothing. The payload is embedded as escaped JSON so the page can render a table without a network request.</p><p>Export is also bounded. Records are marshalled in slices of 500 with a yield to the event loop between slices, and an export already in flight rejects a second one, because a double key press is a double click and not a request for two files.</p><p><strong>Teaser.</strong> Local-only is a complete product on its own. The moment you want a dashboard, you add an endpoint, and that is a decision with its own failure modes.</p><h3>Sending records to your backend, on purpose</h3><p><strong>Quick version.</strong> One URL is enough if your collector accepts both kinds.</p><pre>// shared/telemetry.ts<br>import { initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>initTelemetry({<br>  appName: &#39;checkout&#39;,<br>  env: &#39;VITE_&#39;,<br>  url: &#39;/telemetry&#39;,<br>  headers: () =&gt; ({ Authorization: `Bearer${getAccessToken()}` }),<br>  level: &#39;info&#39;,<br>});</pre><p>Supplying a URL turns uploads on and moves the mode to remote. Records are still written to IndexedDB first, so an endpoint that is down costs latency in your dashboard and nothing at all in your data.</p><p><strong>Real-world version.</strong> Uploads introduce three questions that local-only never asked.</p><p>What happens when the request never lands. Network failures, timeouts, 408, 429 and every 5xx are retried with backoff, and a Retry-After header is honoured when the server sends one. What happens when the request lands and is refused. 400, 401, 403, 404, 405, 410, 413, 415 and 422 are terminal, and the records are marked failed so they stop consuming retry budget forever. What happens after the user re-authenticates and you want those records anyway. retryFailedTelemetry() moves failed records back to pending, which is the difference between losing everything captured during a token expiry and getting it back.</p><pre>// session-recovery.ts<br>import { retryFailedTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>export async function recoverSession(): Promise&lt;number&gt; {<br>  await refreshSession();<br>  return retryFailedTelemetry();<br>}</pre><p>Credentials default to same-origin, never include, so a configured endpoint cannot quietly start carrying cookies to a third party. For a same-origin collector that is exactly right. For a cross-origin one, pass a header provider and let your own auth code decide what goes out.</p><p><strong>Under the hood.</strong> The wire format is one envelope per batch, batched at 50 records and flushed every 30 seconds.</p><pre>{<br>  &quot;schemaVersion&quot;: 1,<br>  &quot;kind&quot;: &quot;errors&quot;,<br>  &quot;sentAt&quot;: 1767225600000,<br>  &quot;app&quot;: { &quot;appName&quot;: &quot;checkout&quot;, &quot;appVersion&quot;: &quot;2.4.1&quot;, &quot;buildId&quot;: &quot;9c1a2f4&quot;, &quot;environment&quot;: &quot;production&quot; },<br>  &quot;records&quot;: [{ &quot;id&quot;: &quot;err_01j8&quot;, &quot;fingerprint&quot;: &quot;3f2c81a9c4b7d0e5&quot;, &quot;occurrenceCount&quot;: 3, &quot;message&quot;: &quot;Payment provider returned 502&quot; }]<br>}</pre><p>Your server has one obligation: answer 2xx for accepted records, and use a status your client can interpret correctly when you do not accept them. A 429 with Retry-After is respected rather than fought. A 401 is terminal on purpose, because retrying an unauthenticated request is a way to hammer your own gateway while the token is broken. The full envelope, the status table and the server obligations are in the <a href="https://github.com/malikrajat/rm-logvault/blob/main/docs/REST-CONTRACT.md">REST contract</a>.</p><p>If the shipped fetch transport does not fit, rest.transport accepts your own implementation with a send method, and the testing subpath ships a scriptable one so tests can exercise every branch of the outbox without a server.</p><p><strong>Teaser.</strong> Everything above is code you can reason about, which means all of it is code you can break with a bad test setup.</p><h3>Testing a browser error tracker without a browser</h3><p><strong>Quick version.</strong> The library ships test doubles on a separate subpath, and that subpath installs nothing, starts nothing and opens no database.</p><pre>// telemetry-upload.test.ts<br>import { afterEach, expect, it } from &#39;vitest&#39;;<br>import {<br>  destroyTelemetry,<br>  initTelemetry,<br>  logger,<br>  syncTelemetry,<br>} from &#39;@codewithrajat/rm-logvault&#39;;<br>import { createFakeTransport, createMemoryRepository } from &#39;@codewithrajat/rm-logvault/testing&#39;;<br><br><br>afterEach(() =&gt; {<br>  destroyTelemetry();<br>});<br>it(&#39;retries a 503 instead of dropping the batch&#39;, async () =&gt; {<br>  const repository = createMemoryRepository();<br>  const transport = createFakeTransport({ status: 503, retryAfterMs: 30_000 });<br>  initTelemetry({<br>    appName: &#39;orders-test&#39;,<br>    repository,<br>    shortcut: false,<br>    rest: {<br>      errorsUrl: &#39;/telemetry/errors&#39;,<br>      logsUrl: &#39;/telemetry/logs&#39;,<br>      transport,<br>    },<br>  });<br>  logger.error(&#39;[Orders] load failed&#39;);<br>  const result = await syncTelemetry();<br>  expect(transport.sendCount).toBe(1);<br>  expect(transport.lastBody()?.records).toHaveLength(1);<br>  expect(result.logs.uploaded).toBe(0);<br>  expect(result.logs.retried).toBe(1);<br>});</pre><p>Run it with npx vitest run. The in-memory repository also fails on demand through failWith and quotaAt, which is how you test the degradation path instead of hoping it works.</p><p><strong>Real-world version.</strong> The test people actually need is the one that asserts a component failure produced a record with the right context. In React, Testing Library plus Vitest does it with a real boundary.</p><pre>// telemetry-error-boundary.test.tsx<br>import { render, screen } from &#39;@testing-library/react&#39;;<br>import { afterEach, beforeEach, describe, expect, it, vi } from &#39;vitest&#39;;<br>import { destroyTelemetry, flushTelemetry, initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br>import { TelemetryErrorBoundary } from &#39;@codewithrajat/rm-logvault/react&#39;;<br>import { createMemoryRepository } from &#39;@codewithrajat/rm-logvault/testing&#39;;<br><br>function BrokenWidget(): never {<br>  throw new Error(&#39;orders widget exploded&#39;);<br>}<br>describe(&#39;TelemetryErrorBoundary&#39;, () =&gt; {<br>  beforeEach(() =&gt; {<br>    vi.spyOn(console, &#39;error&#39;).mockImplementation(() =&gt; undefined);<br>  });<br>  afterEach(() =&gt; {<br>    destroyTelemetry();<br>    vi.restoreAllMocks();<br>  });<br>  it(&#39;renders the fallback and stores exactly one record&#39;, async () =&gt; {<br>    const repository = createMemoryRepository();<br>    initTelemetry({ appName: &#39;orders-test&#39;, repository, shortcut: false });<br>    render(<br>      &lt;TelemetryErrorBoundary fallback={&lt;p&gt;Widget unavailable&lt;/p&gt;}&gt;<br>        &lt;BrokenWidget /&gt;<br>      &lt;/TelemetryErrorBoundary&gt;,<br>    );<br>    expect(screen.getByText(&#39;Widget unavailable&#39;)).toBeTruthy();<br>    await flushTelemetry();<br>    const [record] = repository.errors.all();<br>    expect(record?.source).toBe(&#39;react&#39;);<br>    expect(record?.message).toContain(&#39;orders widget exploded&#39;);<br>    expect(record?.componentStack).toBeTruthy();<br>  });<br>});</pre><p>In Angular, the handler is an injectable, so the test is a TestBed provider test and it runs with ng test.</p><pre>// checkout-error-handler.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { ErrorHandler } from &#39;@angular/core&#39;;<br>import { provideTelemetryErrorHandler } from &#39;@codewithrajat/rm-logvault/angular&#39;;<br>import { destroyTelemetry, flushTelemetry, initTelemetry } from &#39;@codewithrajat/rm-logvault&#39;;<br>import { createMemoryRepository } from &#39;@codewithrajat/rm-logvault/testing&#39;;<br><br>describe(&#39;TelemetryErrorHandler&#39;, () =&gt; {<br>  it(&#39;stores an error Angular reported, with its context&#39;, async () =&gt; {<br>    const repository = createMemoryRepository();<br>    initTelemetry({ appName: &#39;checkout-test&#39;, repository, shortcut: false });<br>    TestBed.configureTestingModule({<br>      providers: [provideTelemetryErrorHandler({ tags: { shell: &#39;checkout&#39; } })],<br>    });<br>    TestBed.inject(ErrorHandler).handleError(new Error(&#39;payment failed&#39;));<br>    await flushTelemetry();<br>    const [record] = repository.errors.all();<br>    expect(record?.source).toBe(&#39;angular&#39;);<br>    expect(record?.message).toBe(&#39;payment failed&#39;);<br>    expect(record?.tags?.shell).toBe(&#39;checkout&#39;);<br>    destroyTelemetry();<br>  });<br>});</pre><p><strong>Under the hood.</strong> Both tests assert the same three things, and they are the three that break in production: the record exists, the message survived normalisation, and the context that identifies where it came from is attached.</p><p>The last double is for code that only calls capture, not for the pipeline. A recording captureError double replaces the real one in a unit test of a service, so a service test does not need the library initialised at all.</p><pre>// checkout-service.test.ts<br>import { expect, it, vi } from &#39;vitest&#39;;<br>import { createCaptureErrorMock } from &#39;@codewithrajat/rm-logvault/testing&#39;;<br><br>const telemetry = createCaptureErrorMock();<br>vi.mock(&#39;./telemetry&#39;, () =&gt; ({ captureError: telemetry.captureError }));<br>it(&#39;reports a failed load with the route&#39;, async () =&gt; {<br>  const { loadOrders } = await import(&#39;./orders-service&#39;);<br>  await loadOrders(&#39;42&#39;);<br>  expect(telemetry.messages()).toEqual([&#39;orders 42 not found&#39;]);<br>  expect(telemetry.last()?.ctx?.source).toBe(&#39;router&#39;);<br>  telemetry.reset();<br>});</pre><p>The reason to reach for a recording double instead of a bare vi.fn() is the assertion itself. telemetry.last()?.ctx?.source reads like the thing you are checking, while mock.calls[0][1].source reads like an implementation detail of the mock.</p><p><strong>Teaser.</strong> Here is the whole thing in one file, plus the answer to the question I asked at the start.</p><h3>The full integration, and the answer to the question from the top</h3><p>This is the complete version of the running example, in one place. Every option here is optional, and the ordering comments matter more than the values.</p><pre>// shared/telemetry.ts<br>import {<br>  captureError,<br>  destroyTelemetry,<br>  getTelemetryStatus,<br>  initTelemetry,<br>  logger,<br>} from &#39;@codewithrajat/rm-logvault&#39;;<br>import type { TelemetryHandle } from &#39;@codewithrajat/rm-logvault&#39;;<br><br>let handle: TelemetryHandle | undefined;<br>export function startTelemetry(): TelemetryHandle {<br>  if (handle !== undefined) return handle;<br>  handle = initTelemetry({<br>    // Identity. Everything on a record that says which build produced it.<br>    appName: &#39;checkout&#39;,<br>    appVersion: &#39;2.4.1&#39;,<br>    buildId: &#39;9c1a2f4&#39;,<br>    environment: &#39;production&#39;,<br>    // Local by default. Adding a URL is the only thing that turns uploads on.<br>    url: &#39;/telemetry&#39;,<br>    headers: () =&gt; ({ Authorization: `Bearer${getAccessToken()}` }),<br>    errors: {<br>      maxRecords: 1000,<br>      retentionDays: 14,<br>      maxEventsPerMinute: 120,<br>      maxRepeatsPerMinute: 12,<br>      captureResources: true,<br>      captureCsp: true,<br>      captureChunkErrors: true,<br>      beforeCapture: (record) =&gt; (record.message.includes(&#39;ResizeObserver loop&#39;) ? null : record),<br>    },<br>    logs: {<br>      level: &#39;info&#39;,<br>      consoleLevel: &#39;warn&#39;,<br>      maxRecords: 5000,<br>      retentionDays: 7,<br>    },<br>    redaction: {<br>      allowedQueryParams: [&#39;page&#39;, &#39;locale&#39;],<br>    },<br>    rest: {<br>      intervalMs: 30_000,<br>      batchSize: 50,<br>      onTerminalFailure: (status) =&gt; {<br>        logger.warn(`[Telemetry] batch rejected with status${String(status)}`);<br>      },<br>    },<br>    shortcut: {<br>      filenamePrefix: &#39;checkout-diagnostics&#39;,<br>      allow: () =&gt; isInternalUser(),<br>    },<br>    // Consent is evaluated before every capture, persist and upload.<br>    consent: () =&gt; hasAnalyticsConsent(),<br>    onInternalError: (stage, error) =&gt; {<br>      logger.warn(`[Telemetry] internal failure in${stage}`, error);<br>    },<br>  });<br>  return handle;<br>}<br>export function reportFailure(error: unknown, context: Record&lt;string, string&gt;): void {<br>  captureError(error, {<br>    tags: context,<br>    severity: &#39;error&#39;,<br>  });<br>}<br>export function stopTelemetry(): void {<br>  destroyTelemetry();<br>  handle = undefined;<br>}<br>export function telemetrySummary(): string {<br>  const status = getTelemetryStatus();<br>  return `${status.mode}${status.storage} pending=${status.pending.errors}/${status.pending.logs}`;<br>}</pre><p>Now the question from the top: where does an error go when it is thrown before your tracker starts, and the tab closes a second later?</p><p>Two mechanisms cover it, and they are independent. Before initTelemetry runs, a failure is normalised immediately and held in a bounded buffer of 50 entries. It is stored in its safe form rather than as a live reference to a caller’s object graph, so nothing about the application is retained by accident. When initialisation completes, that buffer is replayed into the real tracker, which is why an exception thrown during module evaluation still appears in the report with the application metadata attached.</p><p>The tab closing is the other half, and it is the outbox doing the work. Records are written to IndexedDB as pending rows, pagehide and the hidden visibilitychange state both trigger a flush, and the uploader gets a keepalive drain at that moment. If the network is gone, the rows are still there when the user comes back, and the next sync pass picks them up.</p><p>The result of all of this is a support conversation that goes differently. Someone opens the report, sees a single row with a large occurrence count and a route tag, and the ninety seconds of guessing are gone.</p><p><strong>The one thing most teams get wrong.</strong> They audit the reporter for correctness and never audit it for failure. Every code path in this article exists because the pipeline runs while the application is already broken: storage is allowed to be missing, the network is allowed to be gone, and the value being reported is allowed to be hostile. A reporter that only works when everything else works is not monitoring, it is a happy-path logger with a dashboard attached.</p><p><strong>When this is the wrong tool.</strong> If you need session replay, stack traces symbolicated from uploaded source maps, alerting with on-call routing, or a hosted dashboard that somebody else maintains, a hosted SDK will get you there faster and this library will not pretend otherwise. It captures and stores browser-side failures and hands you a report. Turning those records into a page at 3am is a pipeline you own. That list of non-goals is written down in the <a href="https://github.com/malikrajat/rm-logvault#what-it-does-not-do">README</a> rather than left for you to discover.</p><p><strong>Bonus tips.</strong> One per level.</p><p>Beginner: pass extra and tags explicitly instead of dumping an object into a payload. The sanitizer will scrub the values, but it cannot invent the route or the order id you never told it about.</p><p>Intermediate: set logs.consoleLevel at build time, &#39;off&#39; in production and &#39;debug&#39; in development. The console level and the persist level are separate, so silencing the console does not silence the vault, and initialising telemetry does not change your console output on its own.</p><p>Advanced: use errors.beforeCapture for noise you have genuinely decided to ignore, and use a registered context builder for classification your application already knows. Neither should be used to hide an error category you have not investigated yet.</p><p><strong>Recap.</strong></p><ul><li>The reporter runs inside the failure path, so the first requirement is that it cannot throw, and hostile values are the normal case rather than the edge case.</li><li>Local-first storage with an outbox on top is what makes a flush at pagehide and a retry after a network outage the same mechanism.</li><li>Redaction belongs before the write, not before the upload, and the strongest version of that claim is reading less in the first place.</li><li>Aggregation stops the row count exploding, but a per-fingerprint limiter is what stops one repeating failure from eating the budget that new failures need.</li><li>A report that a support engineer can open, read and forward is the actual deliverable. Everything else is plumbing that makes it possible.</li></ul><p><strong>What did you think?</strong><br> Did this approach match how you are solving it, or do you have a different take? Drop a comment. I genuinely read every single one.</p><p><strong>Found this helpful?</strong><br> If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong><br> I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let us connect. Find me on LinkedIn or GitHub and let us keep the conversation going.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">Reddit</a> — Developer blog posts &amp; tech discussions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05e2e87712fe" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/browser-error-tracking-the-errors-your-sdk-never-sends-05e2e87712fe">Browser Error Tracking: The Errors Your SDK Never Sends</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular’s provideBrowserGlobalErrorListeners: The Missing Piece in Your Zoneless Error Strategy]]></title>
            <link>https://javascript.plainenglish.io/angulars-providebrowserglobalerrorlisteners-the-missing-piece-in-your-zoneless-error-strategy-67efabc3367a?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/67efabc3367a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 12:55:32 GMT</pubDate>
            <atom:updated>2026-10-06T12:55:32.675Z</atom:updated>
            <content:encoded><![CDATA[<h4>How one small provider can save your production app from silent, untracked errors — and why most Angular teams miss it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUg-77y1PJtNC8ogNrjZCQ.png" /></figure><p>Have you ever deployed what felt like a rock-solid Angular app, only to get a support ticket about an error that <em>never</em> showed up in your monitoring dashboard? You open Sentry, Datadog, or your custom logger — and nothing. No trace. No breadcrumb. The error happened, your users saw it, but your error handler was completely silent.</p><p>If you recently migrated to zoneless Angular (or you’re planning to), there’s a very good chance this is already happening to you.</p><p>This article dives deep into provideBrowserGlobalErrorListeners — a relatively new Angular API that plugs a critical gap in global error handling for zoneless applications. By the time you finish reading, you will understand:</p><ul><li>Why zone.js was quietly doing more than just change detection</li><li>What breaks in your error pipeline when you remove it</li><li>How provideBrowserGlobalErrorListeners restores that pipeline the right way</li><li>How to build a production-grade custom error handler from scratch</li><li>How to integrate it with Sentry, Datadog, or any monitoring tool</li><li>How to write unit tests that validate your error handling strategy</li></ul><p>Let’s get into it.</p><blockquote><em>Got a story about a silent error in production that cost you a weekend? Drop it in the comments — I read every one of them.</em></blockquote><blockquote>Before you scroll: If you’re moving your Angular app to zoneless change detection and you haven’t audited your error handling strategy yet, this article is for you. Stick around — your monitoring tools might be lying to you right now.</blockquote><h3>What Is provideBrowserGlobalErrorListeners?</h3><p>provideBrowserGlobalErrorListeners is a provider function introduced in Angular&#39;s core package. Its job is straightforward: it registers listeners on the browser&#39;s global window.onerror and window.unhandledrejection events, and routes those errors into Angular&#39;s ErrorHandler.</p><pre>// Simplified mental model of what this provider does internally<br>window.addEventListener(&#39;error&#39;, (event) =&gt; {<br>  errorHandler.handleError(event.error);<br>});<br><br>window.addEventListener(&#39;unhandledrejection&#39;, (event) =&gt; {<br>  errorHandler.handleError(event.reason);<br>});</pre><p>Simple enough. But <em>why</em> did Angular need to ship this as an explicit API? To answer that, we need to talk about the deal you were unknowingly making with zone.js.</p><h3>The Hidden Contract with zone.js</h3><p>When Angular apps run with zone.js (which was the default for years), your ErrorHandler worked like magic. Any async error — whether inside a Promise, a setTimeout, an RxJS observable chain, or a plain event handler — would reliably land in your ErrorHandler.handleError() method. No extra configuration needed.</p><p>That was not Angular being clever. That was zone.js doing the heavy lifting.</p><p>Here’s what zone.js was actually doing under the hood:</p><ol><li><strong>Monkey-patching async APIs</strong> — It overwrote browser-native functions like Promise, setTimeout, setInterval, addEventListener, and others to wrap them in an execution &quot;zone.&quot;</li><li><strong>Tracking async execution</strong> — Every async callback ran inside a zone context that could observe its lifecycle.</li><li><strong>Intercepting unhandled errors</strong> — When an error escaped a zone without being caught, zone.js intercepted it before it reached the browser&#39;s global scope.</li><li><strong>Forwarding to NgZone</strong> — Angular’s NgZone listened for these zone-level errors and forwarded them to ErrorHandler.</li></ol><p>So your ErrorHandler was receiving a curated, intercepted stream of errors — not raw browser events. It never had to care about window.onerror or unhandledrejection because zone.js was translating everything into a format Angular understood.</p><p>When you remove zone.js, that translation layer disappears entirely.</p><h3>What Breaks Without zone.js</h3><p>When you switch to provideZonelessChangeDetection() and remove zone.js, here is exactly what changes in the error pipeline:</p><pre>WITH zone.js:<br>Async Error<br>  --&gt; zone.js intercepts<br>    --&gt; NgZone catches<br>      --&gt; ErrorHandler.handleError() [YOUR CODE RUNS]<br><br>WITHOUT zone.js:<br>Async Error<br>  --&gt; Browser fires &#39;unhandledrejection&#39; or &#39;error&#39; event<br>    --&gt; ... silence ...<br>      --&gt; Console warning (if dev mode)<br>        --&gt; Your ErrorHandler never sees it</pre><p>This means your custom ErrorHandler — the one that logs to Sentry, sends alerts to Slack, or shows a friendly toast message — will only receive synchronous errors happening within Angular&#39;s own rendering pipeline. Everything else disappears.</p><p>Template binding errors: still caught.<br> Failed HTTP calls not wrapped in a catchError: gone.<br> Unhandled promise rejections in services: gone.<br> Third-party library async errors: gone.</p><p>This is not a bug in Angular. It is the explicit trade-off of going zoneless. And provideBrowserGlobalErrorListeners is the explicit way to opt back into catching those global errors.</p><h3>Setting Up provideBrowserGlobalErrorListeners</h3><p>Let’s walk through a complete, production-ready setup.</p><h3>Step 1: Bootstrap with the provider</h3><pre>// main.ts<br>import {<br>  bootstrapApplication,<br>  provideBrowserGlobalErrorListeners,<br>} from &#39;@angular/core&#39;;<br>import { AppComponent } from &#39;./app/app.component&#39;;<br>import { appConfig } from &#39;./app/app.config&#39;;<br><br>bootstrapApplication(AppComponent, appConfig).catch((err) =&gt;<br>  console.error(err)<br>);</pre><pre>// app.config.ts<br>import {<br>  ApplicationConfig,<br>  provideZonelessChangeDetection,<br>  provideBrowserGlobalErrorListeners,<br>  ErrorHandler,<br>} from &#39;@angular/core&#39;;<br>import { provideRouter } from &#39;@angular/router&#39;;<br>import { routes } from &#39;./app.routes&#39;;<br>import { GlobalErrorHandler } from &#39;./core/error-handler/global-error-handler.service&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideZonelessChangeDetection(),<br>    provideBrowserGlobalErrorListeners(), // &lt;-- The key addition<br>    provideRouter(routes),<br>    {<br>      provide: ErrorHandler,<br>      useClass: GlobalErrorHandler,<br>    },<br>  ],<br>};</pre><p>Notice: provideBrowserGlobalErrorListeners() does not replace your ErrorHandler. It is a bridge that feeds global browser errors <em>into</em> whatever ErrorHandler is registered. These two work together.</p><h3>Step 2: Build a production-grade custom ErrorHandler</h3><pre>// core/error-handler/global-error-handler.service.ts<br>import { ErrorHandler, inject, Injectable, NgZone } from &#39;@angular/core&#39;;<br>import { HttpErrorResponse } from &#39;@angular/common/http&#39;;<br>import { ErrorLoggingService } from &#39;./error-logging.service&#39;;<br>import { NotificationService } from &#39;../notifications/notification.service&#39;;<br><br>@Injectable()<br>export class GlobalErrorHandler implements ErrorHandler {<br>  private readonly loggingService = inject(ErrorLoggingService);<br>  private readonly notificationService = inject(NotificationService);<br>  handleError(error: unknown): void {<br>    // Separate client-side errors from HTTP errors<br>    if (error instanceof HttpErrorResponse) {<br>      this.handleHttpError(error);<br>    } else if (error instanceof Error) {<br>      this.handleClientError(error);<br>    } else {<br>      this.handleUnknownError(error);<br>    }<br>  }<br>  private handleHttpError(error: HttpErrorResponse): void {<br>    const message = this.extractHttpMessage(error);<br>    console.error(&#39;[HTTP Error]&#39;, error.status, message);<br>    this.loggingService.logError({<br>      type: &#39;http&#39;,<br>      status: error.status,<br>      message,<br>      url: error.url ?? &#39;unknown&#39;,<br>    });<br>    if (error.status === 0) {<br>      this.notificationService.showError(&#39;Network error. Please check your connection.&#39;);<br>    } else if (error.status &gt;= 500) {<br>      this.notificationService.showError(&#39;Something went wrong on our end. We are working on it.&#39;);<br>    }<br>  }<br>  private handleClientError(error: Error): void {<br>    console.error(&#39;[Client Error]&#39;, error.message, error.stack);<br>    this.loggingService.logError({<br>      type: &#39;client&#39;,<br>      message: error.message,<br>      stack: error.stack,<br>    });<br>    // Show a generic user-facing message - never expose raw stack traces<br>    this.notificationService.showError(&#39;An unexpected error occurred. Please try again.&#39;);<br>  }<br>  private handleUnknownError(error: unknown): void {<br>    console.error(&#39;[Unknown Error]&#39;, error);<br>    this.loggingService.logError({<br>      type: &#39;unknown&#39;,<br>      message: String(error),<br>    });<br>  }<br>  private extractHttpMessage(error: HttpErrorResponse): string {<br>    if (error.error instanceof ErrorEvent) {<br>      return error.error.message;<br>    }<br>    return error.message;<br>  }<br>}</pre><h3>Step 3: Wire in your logging service</h3><pre>// core/error-handler/error-logging.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { environment } from &#39;../../environments/environment&#39;;<br><br>interface ErrorPayload {<br>  type: &#39;http&#39; | &#39;client&#39; | &#39;unknown&#39;;<br>  message: string;<br>  status?: number;<br>  url?: string;<br>  stack?: string;<br>}<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class ErrorLoggingService {<br>  logError(payload: ErrorPayload): void {<br>    if (!environment.production) {<br>      // In development, just log to console with structured data<br>      console.table(payload);<br>      return;<br>    }<br>    // In production, send to your monitoring tool<br>    this.sendToSentry(payload);<br>    this.sendToDatadog(payload);<br>  }<br>  private sendToSentry(payload: ErrorPayload): void {<br>    // Sentry integration example<br>    // Sentry.captureException(new Error(payload.message), {<br>    //   tags: { errorType: payload.type },<br>    //   extra: { status: payload.status, url: payload.url },<br>    // });<br>  }<br>  private sendToDatadog(payload: ErrorPayload): void {<br>    // Datadog RUM integration example<br>    // datadogRum.addError(new Error(payload.message), {<br>    //   errorType: payload.type,<br>    //   httpStatus: payload.status,<br>    // });<br>  }<br>}</pre><h3>Integrating with Sentry in a Real Application</h3><p>Here’s a practical, self-contained Sentry integration:</p><pre>// core/error-handler/sentry-error-handler.service.ts<br>import * as Sentry from &#39;@sentry/angular&#39;;<br>import { ErrorHandler, Injectable, inject } from &#39;@angular/core&#39;;<br>import { HttpErrorResponse } from &#39;@angular/common/http&#39;;<br><br>@Injectable()<br>export class SentryErrorHandler implements ErrorHandler {<br>  handleError(error: unknown): void {<br>    // Do not report 4xx HTTP errors to Sentry - those are user-facing issues<br>    if (error instanceof HttpErrorResponse &amp;&amp; error.status &lt; 500 &amp;&amp; error.status &gt;= 400) {<br>      console.warn(&#39;[Expected HTTP Error]&#39;, error.status, error.url);<br>      return;<br>    }<br>    const extractedError = this.extractError(error);<br>    Sentry.captureException(extractedError, {<br>      tags: {<br>        angular_error: &#39;true&#39;,<br>        error_type: error instanceof HttpErrorResponse ? &#39;http&#39; : &#39;client&#39;,<br>      },<br>    });<br>    // Always re-throw or log locally in development<br>    if (!environment.production) {<br>      throw extractedError;<br>    }<br>  }<br>  private extractError(error: unknown): Error {<br>    if (error instanceof Error) return error;<br>    if (error instanceof HttpErrorResponse) {<br>      return new Error(`HTTP ${error.status}: ${error.message}`);<br>    }<br>    return new Error(String(error));<br>  }<br>}</pre><p>And in your config:</p><pre>// app.config.ts<br>import * as Sentry from &#39;@sentry/angular&#39;;<br>import {<br>  ApplicationConfig,<br>  ErrorHandler,<br>  provideZonelessChangeDetection,<br>  provideBrowserGlobalErrorListeners,<br>} from &#39;@angular/core&#39;;<br><br>Sentry.init({<br>  dsn: &#39;YOUR_SENTRY_DSN&#39;,<br>  environment: environment.name,<br>  tracesSampleRate: 0.2,<br>});<br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideZonelessChangeDetection(),<br>    provideBrowserGlobalErrorListeners(),<br>    {<br>      provide: ErrorHandler,<br>      useClass: SentryErrorHandler,<br>    },<br>  ],<br>};</pre><h3>Behavior Comparison: zone.js vs. Zoneless + Provider</h3><p>Error Source zone.js Zoneless (no provider) Zoneless + provider Template binding error Caught Caught Caught Synchronous service error Caught Caught Caught Unhandled Promise rejection Caught NOT caught Caught setTimeout error Caught NOT caught Caught HTTP error (no catchError) Caught Caught via HttpClient Caught via HttpClient Third-party async error Caught NOT caught Caught</p><p>The provider restores everything in the third column that says “NOT caught.”</p><h3>Conceptual Flow Diagram</h3><pre>Browser Runtime<br>│<br>├── Synchronous Error (template / DI)<br>│     └── Angular catches directly<br>│           └── ErrorHandler.handleError()<br>│<br>├── Unhandled Promise rejection<br>│     └── Browser fires: window.unhandledrejection<br>│           └── [provideBrowserGlobalErrorListeners intercepts]<br>│                 └── ErrorHandler.handleError()<br>│<br>└── Script / runtime error<br>      └── Browser fires: window.onerror<br>            └── [provideBrowserGlobalErrorListeners intercepts]<br>                  └── ErrorHandler.handleError()</pre><h3>Pitfalls and Edge Cases</h3><h3>1. Duplicate error reporting</h3><p>If you manually add window.addEventListener(&#39;unhandledrejection&#39;, ...) anywhere in your codebase AND use provideBrowserGlobalErrorListeners, you will handle the same error twice. Audit your codebase before adding the provider.</p><pre>// DANGER: This will double-report errors<br>window.addEventListener(&#39;unhandledrejection&#39;, (event) =&gt; {<br>  myLogger.log(event.reason); // fires once<br>});<br><br>// And then provideBrowserGlobalErrorListeners also fires<br>// --&gt; ErrorHandler.handleError() also fires</pre><p>Pick one approach. Let provideBrowserGlobalErrorListeners be the single point of entry.</p><h3>2. SSR considerations</h3><p>provideBrowserGlobalErrorListeners hooks into browser-specific globals (window.onerror, window.addEventListener). These do not exist in a Node.js environment. If you are using Angular Universal or @angular/ssr, make sure this provider is only included in your browser config, not your server config.</p><pre>// app.config.browser.ts (browser-specific config)<br>import { mergeApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideBrowserGlobalErrorListeners } from &#39;@angular/core&#39;;<br>import { appConfig } from &#39;./app.config&#39;;<br><br>export const appBrowserConfig = mergeApplicationConfig(appConfig, {<br>  providers: [<br>    provideBrowserGlobalErrorListeners(), // safe here - browser only<br>  ],<br>});</pre><pre>// app.config.server.ts (server config — do NOT include the provider here)<br>import { mergeApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideServerRendering } from &#39;@angular/platform-server&#39;;<br>import { appConfig } from &#39;./app.config&#39;;<br><br>export const appServerConfig = mergeApplicationConfig(appConfig, {<br>  providers: [provideServerRendering()],<br>});</pre><h3>3. Swallowing errors in production</h3><p>A common mistake is catching everything in handleError without re-throwing during development. This makes debugging nearly impossible.</p><pre>handleError(error: unknown): void {<br>  this.loggingService.logError(error);<br><br>// Always surface errors in development<br>  if (!environment.production) {<br>    throw error; // Re-throw so DevTools shows a real stack trace<br>  }<br>}</pre><h3>4. Angular v20+ includes it by default for new projects</h3><p>From Angular v20 onwards, the CLI includes provideBrowserGlobalErrorListeners automatically in new project scaffolds. If you are upgrading an existing project, you need to add it manually — the migration guide does not always flag this.</p><h3>Writing Unit Tests for Your Error Handler</h3><p>Testing error handling is one of those things teams consistently skip. Here is a solid testing setup.</p><h3>Testing the custom ErrorHandler</h3><pre>// global-error-handler.service.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { ErrorHandler } from &#39;@angular/core&#39;;<br>import { GlobalErrorHandler } from &#39;./global-error-handler.service&#39;;<br>import { ErrorLoggingService } from &#39;./error-logging.service&#39;;<br>import { NotificationService } from &#39;../notifications/notification.service&#39;;<br>import { HttpErrorResponse } from &#39;@angular/common/http&#39;;<br><br>describe(&#39;GlobalErrorHandler&#39;, () =&gt; {<br>  let handler: GlobalErrorHandler;<br>  let loggingSpy: jasmine.SpyObj&lt;ErrorLoggingService&gt;;<br>  let notificationSpy: jasmine.SpyObj&lt;NotificationService&gt;;<br>  beforeEach(() =&gt; {<br>    loggingSpy = jasmine.createSpyObj(&#39;ErrorLoggingService&#39;, [&#39;logError&#39;]);<br>    notificationSpy = jasmine.createSpyObj(&#39;NotificationService&#39;, [&#39;showError&#39;]);<br>    TestBed.configureTestingModule({<br>      providers: [<br>        { provide: ErrorHandler, useClass: GlobalErrorHandler },<br>        { provide: ErrorLoggingService, useValue: loggingSpy },<br>        { provide: NotificationService, useValue: notificationSpy },<br>      ],<br>    });<br>    handler = TestBed.inject(ErrorHandler) as GlobalErrorHandler;<br>  });<br>  it(&#39;should log client-side errors and show notification&#39;, () =&gt; {<br>    const error = new Error(&#39;Something went wrong&#39;);<br>    handler.handleError(error);<br>    expect(loggingSpy.logError).toHaveBeenCalledWith(<br>      jasmine.objectContaining({ type: &#39;client&#39;, message: &#39;Something went wrong&#39; })<br>    );<br>    expect(notificationSpy.showError).toHaveBeenCalled();<br>  });<br>  it(&#39;should handle HTTP 500 errors and show notification&#39;, () =&gt; {<br>    const httpError = new HttpErrorResponse({ status: 500, statusText: &#39;Internal Server Error&#39; });<br>    handler.handleError(httpError);<br>    expect(loggingSpy.logError).toHaveBeenCalledWith(<br>      jasmine.objectContaining({ type: &#39;http&#39;, status: 500 })<br>    );<br>    expect(notificationSpy.showError).toHaveBeenCalled();<br>  });<br>  it(&#39;should handle HTTP 404 gracefully&#39;, () =&gt; {<br>    const httpError = new HttpErrorResponse({ status: 404, url: &#39;/api/user&#39; });<br>    handler.handleError(httpError);<br>    expect(loggingSpy.logError).toHaveBeenCalled();<br>  });<br>  it(&#39;should handle unknown error types&#39;, () =&gt; {<br>    handler.handleError(&#39;just a string error&#39;);<br>    expect(loggingSpy.logError).toHaveBeenCalledWith(<br>      jasmine.objectContaining({ type: &#39;unknown&#39; })<br>    );<br>  });<br>});</pre><h3>Testing that unhandledrejection is caught end-to-end</h3><pre>// integration: verify global listener is active<br>it(&#39;should catch unhandled promise rejections via global listener&#39;, async () =&gt; {<br>  const handleErrorSpy = spyOn(TestBed.inject(ErrorHandler), &#39;handleError&#39;);<br><br>// Simulate an unhandled rejection<br>  const rejectionEvent = new PromiseRejectionEvent(&#39;unhandledrejection&#39;, {<br>    promise: Promise.reject(new Error(&#39;async failure&#39;)),<br>    reason: new Error(&#39;async failure&#39;),<br>  });<br>  window.dispatchEvent(rejectionEvent);<br>  // Allow microtask queue to flush<br>  await Promise.resolve();<br>  expect(handleErrorSpy).toHaveBeenCalledWith(<br>    jasmine.objectContaining({ message: &#39;async failure&#39; })<br>  );<br>});</pre><h3>How This Fits into the Modern Angular Architecture</h3><p>Angular’s trajectory is clear: signals-based reactivity, standalone component architecture, and a zoneless future. provideBrowserGlobalErrorListeners is part of that story.</p><p>In the zoneless world, Angular trades implicit magic for explicit control. You get:</p><ul><li>Smaller bundles (no zone.js overhead)</li><li>More predictable change detection</li><li>Better performance in CPU-intensive scenarios</li></ul><p>But explicit control means you have to own things that used to be automatic. Error forwarding is one of them. provideBrowserGlobalErrorListeners is how Angular says: &quot;we recognize you still need this — here is the explicit, supported way to get it.&quot;</p><p>Think of it as part of your application’s provider composition — sitting alongside provideZonelessChangeDetection(), provideRouter(), and your custom ErrorHandler.</p><h3>Traditional Approaches vs. The Right Way</h3><p>Let’s be direct about why you should not roll your own solution:</p><p><strong>Option A: Raw window.onerror</strong></p><pre>// Works, but disconnected from Angular&#39;s DI system<br>window.onerror = (message, source, line, col, error) =&gt; {<br>  myLogger.log(error); // No access to Angular services here<br>};</pre><p><strong>Option B: Manual APP_INITIALIZER</strong></p><pre>// Fragile and verbose — you have to manage cleanup yourself<br>{<br>  provide: APP_INITIALIZER,<br>  useFactory: (handler: ErrorHandler) =&gt; () =&gt; {<br>    window.addEventListener(&#39;unhandledrejection&#39;, (e) =&gt; handler.handleError(e.reason));<br>    window.addEventListener(&#39;error&#39;, (e) =&gt; handler.handleError(e.error));<br>  },<br>  deps: [ErrorHandler],<br>  multi: true,<br>}</pre><p><strong>Option C: provideBrowserGlobalErrorListeners (correct approach)</strong></p><pre>// Clean, composable, officially maintained, SSR-aware<br>provideBrowserGlobalErrorListeners()</pre><p>Option C is not just shorter — it is the only option the Angular team will maintain going forward. Options A and B create hidden state that is easy to get wrong and hard to test.</p><h3>Bonus Tips</h3><p><strong>Tip 1: Filter noise before logging.</strong><br> Not every error deserves a Sentry ticket. HTTP 401 (unauthorized) and 403 (forbidden) errors are often expected. Add a filter layer in your handler before calling your logging service.</p><p><strong>Tip 2: Add context to your errors.</strong><br> A raw stack trace is rarely enough. Add user context (anonymized), current route, and app version to every error payload. This dramatically speeds up debugging.</p><pre>this.loggingService.logError({<br>  ...payload,<br>  route: this.router.url,<br>  appVersion: environment.version,<br>  userId: this.authService.currentUserId(), // anonymized<br>});</pre><p><strong>Tip 3: Use structured logging formats.</strong><br> If you are building your own logging backend, structure your error payloads as JSON from the start. This makes them queryable in tools like Elasticsearch or CloudWatch.</p><p><strong>Tip 4: Never show raw error messages to end users.</strong><br> Map technical errors to user-friendly messages. “TypeError: Cannot read properties of undefined” means nothing to your users. “Something went wrong. Please refresh and try again.” is actionable.</p><p><strong>Tip 5: Test your error handler in production-like conditions.</strong><br> Your development environment might mask errors that only appear in production builds. Add a dedicated test route that intentionally triggers different error types so your QA team can verify the full pipeline.</p><h3>Recap</h3><p>Here is everything we covered, condensed:</p><ul><li>zone.js was intercepting async errors and routing them to Angular&#39;s ErrorHandler behind the scenes.</li><li>Removing zone.js (via provideZonelessChangeDetection) cuts that pipeline. Async errors become invisible to Angular.</li><li>provideBrowserGlobalErrorListeners explicitly re-establishes that pipeline by listening to window.onerror and window.unhandledrejection and forwarding them to your ErrorHandler.</li><li>It belongs in your bootstrapApplication providers alongside provideZonelessChangeDetection.</li><li>It does not work in SSR — keep it in browser-only config files.</li><li>Angular v20+ new projects get this automatically. Existing projects upgrading to zoneless must add it manually.</li><li>A good error strategy combines this provider with a typed custom ErrorHandler, a logging service, and meaningful user notifications.</li></ul><p>The bottom line: if you are going zoneless and you are not using this provider, your error monitoring is broken right now — you just do not know it yet.</p><h3>Let’s Talk</h3><p>What did you think of this one?</p><p>Have you already hit this issue in production? I would genuinely love to hear your story. Did you catch it before deployment, or did users find it first? Drop a comment below — that kind of real-world context helps everyone.</p><p><strong>Here is a specific question to kick off the discussion:</strong><br> When you migrated to zoneless (or when you do), what was the first thing you audited in your error handling pipeline? Was it HTTP errors, async promises, or something else entirely?</p><p>If this saved you from a sleepless debugging session, consider giving it a clap — it helps other developers find articles like this on Medium, and honestly, it makes my day.</p><p>Let’s keep building better apps — one deliberate architecture decision at a time.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/"><strong>Reddit</strong></a><strong> </strong>— Developer blog posts &amp; tech discussions</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67efabc3367a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angulars-providebrowserglobalerrorlisteners-the-missing-piece-in-your-zoneless-error-strategy-67efabc3367a">Angular’s provideBrowserGlobalErrorListeners: The Missing Piece in Your Zoneless Error Strategy</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Losing Errors to the Void: Handling Unhandled Promise Rejections Globally in JavaScript…]]></title>
            <link>https://javascript.plainenglish.io/stop-losing-errors-to-the-void-handling-unhandled-promise-rejections-globally-in-javascript-cc321b4e237c?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc321b4e237c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 11:37:08 GMT</pubDate>
            <atom:updated>2026-09-29T11:37:08.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Losing Errors to the Void: Handling Unhandled Promise Rejections Globally in JavaScript, Angular, and React</h3><h4><em>A practical, copy-paste guide to catching the promise rejections your app is currently swallowing without you knowing it</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdjjp3i6152V4hFdqWOBWA.png" /></figure><p>Have you ever had a user tell you “the button just didn’t do anything” — and when you checked the console, there was a red error sitting there that nobody ever saw? That’s usually an unhandled promise rejection, quietly failing in the background while your app pretends everything is fine.</p><p>By the end of this article, you’ll know how to:</p><ul><li>Catch every unhandled promise rejection in a browser app, globally, in one place</li><li>Understand exactly what triggers unhandledrejection versus a regular try/catch</li><li>Wire this into an Angular app using the new control flow syntax and signals</li><li>Wire this into a React app using a clean custom hook</li><li>Write unit tests for both so this doesn’t silently break later</li><li>Avoid the handful of mistakes that make this “solution” useless in production</li></ul><p>If you’ve ever shipped a feature, felt good about your error handling, and then found out three weeks later that a whole class of failures was never being logged anywhere — this one’s for you.</p><p>If this kind of “here’s the gap in your error handling” deep-dive is useful, go ahead and hit follow — I write one of these every week, and the next one is about a related blind spot in error boundaries.</p><blockquote><em>Before we dive into the examples, a quick note: the code snippets here are meant purely for understanding the concept. Some syntax may reflect patterns from earlier Angular or React versions by the time you’re reading this. Always check the official docs for the current API and syntax.</em></blockquote><h3>What “Unhandled Promise Rejection” Actually Means</h3><p>A promise rejection is “unhandled” when a promise fails and nothing in the chain has a .catch() or a try/catch around an await to deal with it. JavaScript doesn&#39;t throw immediately — it waits until the current microtask queue drains, and if the rejection still has no handler attached, the runtime fires an unhandledrejection event on the global object.</p><p>That’s the key detail most people miss: it’s not the same mechanism as a thrown synchronous error, and window.onerror will not catch it. These are two separate reporting channels, and a lot of &quot;global error handling&quot; setups only wire up one of them.</p><p>Here’s the plain vanilla JS version, no framework involved:</p><pre>window.addEventListener(&#39;unhandledrejection&#39;, (event) =&gt; {<br>  console.error(&#39;Unhandled promise rejection:&#39;, event.reason);<br><br>// Optional: stop the browser from also logging its own default message<br>  event.preventDefault();<br>  // This is where you&#39;d send it to Sentry, LogRocket, your own logging endpoint, etc.<br>});</pre><p>You can also assign it as a property instead of an event listener:</p><pre>window.onunhandledrejection = (event) =&gt; {<br>  console.error(&#39;Unhandled promise rejection:&#39;, event.reason);<br>};</pre><p>The event-listener version is generally the better choice, because onunhandledrejection gets overwritten if two parts of your codebase both try to set it. addEventListener lets multiple listeners coexist.</p><p>There’s also a companion event worth knowing: rejectionhandled. It fires if a promise was initially unhandled but <em>later</em> got a .catch() attached (common with async timing quirks). If you&#39;re building serious error tracking, you&#39;ll want to listen for both so you don&#39;t log false positives.</p><h3>Wiring This Into an Angular App</h3><p>In Angular, zone.js patches Promise under the hood, which means unhandled rejections inside the zone still bubble up to the same window unhandledrejection event — so the approach above works without modification. The cleanest way to use it is a small injectable service that exposes the last error as a signal, so any component can react to it.</p><pre>// error-tracking.service.ts<br>import { Injectable, signal } from &#39;@angular/core&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class ErrorTrackingService {<br>  readonly lastError = signal&lt;string | null&gt;(null);<br>  constructor() {<br>    window.addEventListener(&#39;unhandledrejection&#39;, this.handleRejection);<br>  }<br>  private handleRejection = (event: PromiseRejectionEvent) =&gt; {<br>    const message = event.reason?.message ?? String(event.reason);<br>    console.error(&#39;Unhandled promise rejection:&#39;, event.reason);<br>    this.lastError.set(message);<br>    event.preventDefault();<br>  };<br>}</pre><p>And a small component that surfaces it, using the new @if control flow and an input() signal for styling flexibility:</p><pre>// error-banner.component.ts<br>import { Component, inject, input } from &#39;@angular/core&#39;;<br>import { ErrorTrackingService } from &#39;./error-tracking.service&#39;;<br><br>@Component({<br>  selector: &#39;app-error-banner&#39;,<br>  template: `<br>    @if (errorTracking.lastError(); as error) {<br>      &lt;div [class]=&quot;bannerClass()&quot;&gt;<br>        {{ error }}<br>      &lt;/div&gt;<br>    }<br>  `,<br>})<br>export class ErrorBannerComponent {<br>  protected errorTracking = inject(ErrorTrackingService);<br>  bannerClass = input(&#39;error-banner&#39;);<br>}</pre><p>Because ErrorTrackingService is providedIn: &#39;root&#39;, its constructor runs once, the first time it&#39;s injected anywhere — which in practice means as soon as your app bootstraps and something requests it. Drop &lt;app-error-banner /&gt; near the root of your app and you have a working global catch-all.</p><h3>Unit Testing the Angular Version</h3><p>The tricky part of testing this is that PromiseRejectionEvent isn&#39;t something you can construct with a plain object — you have to build a regular Event and attach a reason property to it, then dispatch it on window:</p><pre>// error-tracking.service.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { ErrorTrackingService } from &#39;./error-tracking.service&#39;;<br><br>describe(&#39;ErrorTrackingService&#39;, () =&gt; {<br>  let service: ErrorTrackingService;<br>  beforeEach(() =&gt; {<br>    TestBed.configureTestingModule({});<br>    service = TestBed.inject(ErrorTrackingService);<br>  });<br>  it(&#39;captures an unhandled promise rejection from window&#39;, () =&gt; {<br>    const rejectionEvent = new Event(&#39;unhandledrejection&#39;) as PromiseRejectionEvent;<br>    Object.defineProperty(rejectionEvent, &#39;reason&#39;, {<br>      value: new Error(&#39;Something broke&#39;),<br>    });<br>    window.dispatchEvent(rejectionEvent);<br>    expect(service.lastError()).toBe(&#39;Something broke&#39;);<br>  });<br>});</pre><p>Quick, answerable one for you: have you ever shipped a “silent” promise rejection to production and only found out about it from a confused user report instead of your monitoring tool? Drop the story in the comments — I want to hear how you eventually tracked it down.</p><h3>Wiring This Into a React App</h3><p>React doesn’t patch promises, so the pattern is simpler: a custom hook that attaches the listener on mount and cleans it up on unmount.</p><pre>// useUnhandledRejection.js<br>import { useEffect, useState, useCallback } from &#39;react&#39;;<br><br>export function useUnhandledRejection() {<br>  const [lastError, setLastError] = useState(null);<br>  const handleRejection = useCallback((event) =&gt; {<br>    const message = event.reason?.message ?? String(event.reason);<br>    console.error(&#39;Unhandled promise rejection:&#39;, event.reason);<br>    setLastError(message);<br>    event.preventDefault();<br>  }, []);<br>  useEffect(() =&gt; {<br>    window.addEventListener(&#39;unhandledrejection&#39;, handleRejection);<br>    return () =&gt; window.removeEventListener(&#39;unhandledrejection&#39;, handleRejection);<br>  }, [handleRejection]);<br>  return lastError;<br>}</pre><p>And a component that uses it:</p><pre>// ErrorBanner.jsx<br>import { useUnhandledRejection } from &#39;./useUnhandledRejection&#39;;<br><br>export function ErrorBanner() {<br>  const lastError = useUnhandledRejection();<br>  if (!lastError) return null;<br>  return &lt;div className=&quot;error-banner&quot;&gt;{lastError}&lt;/div&gt;;<br>}</pre><p>Mount &lt;ErrorBanner /&gt; once, near the top of your component tree, and every unhandled rejection anywhere in the app surfaces through it.</p><h3>Unit Testing the React Version</h3><p>Using React Testing Library, you dispatch the same kind of synthetic event and assert the banner shows up:</p><pre>// ErrorBanner.test.jsx<br>import { render, screen, act } from &#39;@testing-library/react&#39;;<br>import { ErrorBanner } from &#39;./ErrorBanner&#39;;<br><br>test(&#39;shows the error banner after an unhandled promise rejection&#39;, () =&gt; {<br>  render(&lt;ErrorBanner /&gt;);<br>  act(() =&gt; {<br>    const event = new Event(&#39;unhandledrejection&#39;);<br>    event.reason = new Error(&#39;Something broke&#39;);<br>    window.dispatchEvent(event);<br>  });<br>  expect(screen.getByText(&#39;Something broke&#39;)).toBeInTheDocument();<br>});</pre><p>One gotcha worth flagging here: if you’re running tests under jsdom, its support for a real PromiseRejectionEvent constructor is limited, which is why both examples above build a plain Event and manually attach reason rather than trying to construct the browser-native event class directly.</p><h3>Bonus Tips</h3><p>A few things that tend to separate a “works in the demo” version of this from one that actually holds up in production:</p><ul><li>Call event.preventDefault() only after you&#39;ve logged the error somewhere durable — it suppresses the browser&#39;s own default console warning, which is convenient once you have your own logging in place, but a footgun if you add it before you&#39;re actually capturing anything.</li><li>Pair unhandledrejection with window.onerror (or a window.addEventListener(&#39;error&#39;, ...) listener) so you&#39;re covering both synchronous throws and rejected promises — they are genuinely separate mechanisms.</li><li>Listen for rejectionhandled too if you&#39;re building anything resembling real error monitoring, so a late .catch() doesn&#39;t get logged as a permanent failure.</li><li>If any part of your stack runs in Node (an SSR layer, an API route, a script), remember the API there is different: process.on(&#39;unhandledRejection&#39;, handler), not window.</li><li>Route the captured error into whatever tool you already use for monitoring (Sentry, LogRocket, your own backend) rather than leaving it in console.error — the whole point of this pattern is that a developer isn&#39;t watching the console when it happens.</li></ul><h3>Recap</h3><p>Unhandled promise rejections fail silently by design, and neither Angular’s zone patching nor React’s rendering model catches them for you automatically — you have to opt in with a global window listener. Once that listener is in place, wrapping it in a service (Angular) or a hook (React) makes it reusable, testable, and easy to hook into whatever logging or monitoring tool you already rely on.</p><p>Did this approach match how you’re already solving it, or do you have a different take? Drop a comment — I genuinely read every single one.</p><p><strong>Found this helpful?</strong><br> If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong><br> I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let’s connect — find me on LinkedIn or GitHub and let’s keep the conversation going.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">**Reddit</a>** — Developer blog posts &amp; tech discussions</li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc321b4e237c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/stop-losing-errors-to-the-void-handling-unhandled-promise-rejections-globally-in-javascript-cc321b4e237c">Stop Losing Errors to the Void: Handling Unhandled Promise Rejections Globally in JavaScript…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Leaking Memory in Angular: withExperimentalAutoCleanupInjectors Explained]]></title>
            <link>https://javascript.plainenglish.io/stop-leaking-memory-in-angular-withexperimentalautocleanupinjectors-explained-557a5b89fa4a?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/557a5b89fa4a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 12:40:49 GMT</pubDate>
            <atom:updated>2026-09-22T12:40:49.602Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stop leaking memory on every route change — Angular’s new withExperimentalAutoCleanupInjectors fixes the problem you didn’t know you had</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXLjCHRGCNgN4rtPUp8OQQ.png" /></figure><p>Stop leaking memory on every route change — Angular’s new withExperimentalAutoCleanupInjectors fixes the problem you didn&#39;t know you had</p><p>Have you ever wondered why your Angular app slowly feels heavier the longer a user navigates around? Why services that should be “route-specific” seem to stick around forever? If you’ve used takeUntilDestroyed() inside a route-level service and had a nagging feeling it wasn&#39;t truly cleaning up — you were right.</p><p>Angular 21.1 shipped a feature that solves exactly this: withExperimentalAutoCleanupInjectors. It&#39;s experimental, it&#39;s opt-in, and it might be the most important router addition this year.</p><p>Before we dive in, drop a quick comment: <strong>Have you ever hit a memory leak caused by route-level services in Angular? How did you handle it?</strong> I’m genuinely curious — and your experience might help someone else reading this.</p><h3>What You Will Learn</h3><p>By the end of this article, you’ll understand:</p><ul><li>Why Angular route injectors used to leak memory silently</li><li>What withExperimentalAutoCleanupInjectors actually does</li><li>How to enable and configure it in a modern Angular 21+ standalone app</li><li>How to work with it alongside a custom RouteReuseStrategy</li><li>Patterns like takeUntilDestroyed() and Signals that now work correctly in route-level services</li><li>How to write unit tests that verify injector cleanup behavior</li></ul><h3>The Problem Nobody Talked About (But Everyone Hit)</h3><p>When you add providers to a route, or use lazy loading, Angular creates a dedicated EnvironmentInjector for that route. That injector hosts the services defined at that route level. Makes sense, right?</p><p>The problem? Until Angular 21.1, <strong>those injectors were never destroyed</strong>. Ever.</p><p>You navigate to /dashboard, Angular creates a route injector for it. You navigate away to /profile. The /dashboard injector? Still alive. Navigate to ten more routes? All ten injectors, still alive, services still ticking, subscriptions still running.</p><p>Here’s what that meant in practice:</p><pre>// This service lives at route level in your routes config<br>@Injectable()<br>export class DashboardPollingService {<br>  private data = signal&lt;DashboardData[]&gt;([]);<br><br>constructor() {<br>    // You THINK this stops when you leave the route.<br>    // Before Angular 21.1? It never did.<br>    interval(3000)<br>      .pipe(takeUntilDestroyed())<br>      .subscribe(() =&gt; this.fetchData());<br>  }<br>  private fetchData() {<br>    // Keeps running forever...<br>  }<br>}</pre><p>The takeUntilDestroyed() operator works by listening to the injector&#39;s destroy signal. But if the injector is never destroyed, the signal never fires. Your polling keeps running, your HTTP calls keep happening, and your memory keeps growing.</p><h3>Enter withExperimentalAutoCleanupInjectors</h3><p>Angular 21.1 introduces this as an <strong>opt-in router feature</strong> that automatically destroys EnvironmentInjectors associated with routes that are no longer active and not stored for reuse.</p><p>After each successful navigation (specifically after NavigationEnd when the router stabilizes), Angular walks the route tree and destroys injectors for any routes that are no longer part of the active tree — unless your RouteReuseStrategy says to keep them.</p><p>The cleanup is hierarchical too: if a parent route’s injector gets destroyed, all descendant injectors are destroyed with it, maintaining the integrity of the injection tree.</p><h3>Setting It Up: One Line in Your App Config</h3><p>Here’s the beautiful part. Enabling it takes a single addition to your provideRouter call:</p><pre>// app.config.ts<br>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideRouter, withExperimentalAutoCleanupInjectors } from &#39;@angular/router&#39;;<br>import { routes } from &#39;./app.routes&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter(<br>      routes,<br>      withExperimentalAutoCleanupInjectors()  // &lt;-- that&#39;s it<br>    )<br>  ]<br>};</pre><p>No module changes. No additional configuration. Just one function call and your route injectors now get properly cleaned up.</p><h3>The Real-World Impact: Before and After</h3><p>Let’s look at a realistic example. Say you have a route-level service for a dashboard feature that polls for notifications and exposes a signal:</p><p><strong>Before (broken cleanup, pre 21.1 or without the feature):</strong></p><pre>// dashboard/dashboard-notifications.service.ts<br>@Injectable()<br>export class DashboardNotificationsService implements OnDestroy {<br>  notifications = signal&lt;Notification[]&gt;([]);<br>  private subscription!: Subscription;<br><br>constructor(private http: HttpClient) {<br>    // You had to manually manage this AND it still<br>    // didn&#39;t work reliably because ngOnDestroy wasn&#39;t called<br>    this.subscription = interval(5000).subscribe(() =&gt; this.loadNotifications());<br>  }<br>  private loadNotifications() {<br>    this.http.get&lt;Notification[]&gt;(&#39;/api/notifications&#39;).subscribe(data =&gt; {<br>      this.notifications.set(data);<br>    });<br>  }<br>  ngOnDestroy() {<br>    // This was never reliably called for route-level services<br>    this.subscription.unsubscribe();<br>  }<br>}</pre><p><strong>After (clean, Angular 21.1+ with auto cleanup):</strong></p><pre>// dashboard/dashboard-notifications.service.ts<br>@Injectable()<br>export class DashboardNotificationsService {<br>  notifications = signal&lt;Notification[]&gt;([]);<br>  private http = inject(HttpClient);<br><br>constructor() {<br>    // takeUntilDestroyed now works correctly because<br>    // the injector IS destroyed when you leave the route<br>    interval(5000)<br>      .pipe(<br>        takeUntilDestroyed(),<br>        switchMap(() =&gt; this.http.get&lt;Notification[]&gt;(&#39;/api/notifications&#39;))<br>      )<br>      .subscribe(data =&gt; this.notifications.set(data));<br>  }<br>}</pre><p>And the route definition that makes this service route-scoped:</p><pre>// app.routes.ts<br>import { Routes } from &#39;@angular/router&#39;;<br>import { DashboardComponent } from &#39;./dashboard/dashboard.component&#39;;<br>import { DashboardNotificationsService } from &#39;./dashboard/dashboard-notifications.service&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;dashboard&#39;,<br>    component: DashboardComponent,<br>    providers: [DashboardNotificationsService]  // Route-scoped service<br>  },<br>  {<br>    path: &#39;profile&#39;,<br>    loadComponent: () =&gt; import(&#39;./profile/profile.component&#39;)<br>  }<br>];</pre><p>When the user navigates away from /dashboard, the DashboardNotificationsService injector is destroyed, takeUntilDestroyed() fires, and your polling stops. Clean. Predictable. How it always should have worked.</p><h3>Quick mid-article check-in</h3><p>If this is already making you think about services in your own app that might be leaking — give this article a clap so more Angular devs can find it. And if you’re wondering whether your current project is affected, keep reading — I’ll show you how to verify it.</p><h3>Working with Lazy-Loaded Routes</h3><p>The feature works equally well with lazy-loaded routes, which is where you’re most likely to benefit from it:</p><pre>// app.routes.ts<br>export const routes: Routes = [<br>  {<br>    path: &#39;admin&#39;,<br>    loadChildren: () =&gt; import(&#39;./admin/admin.routes&#39;).then(m =&gt; m.ADMIN_ROUTES)<br>    // The entire lazy chunk gets its own injector.<br>    // With auto-cleanup, it&#39;s destroyed when you leave.<br>  },<br>  {<br>    path: &#39;home&#39;,<br>    loadComponent: () =&gt; import(&#39;./home/home.component&#39;)<br>  }<br>];</pre><pre>// admin/admin.routes.ts<br>import { Routes } from &#39;@angular/router&#39;;<br>import { AdminDashboardComponent } from &#39;./admin-dashboard.component&#39;;<br>import { AdminDataService } from &#39;./admin-data.service&#39;;<br><br>export const ADMIN_ROUTES: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    component: AdminDashboardComponent,<br>    providers: [AdminDataService]<br>  }<br>];</pre><pre>// admin/admin-data.service.ts<br>@Injectable()<br>export class AdminDataService {<br>  private users = signal&lt;User[]&gt;([]);<br>  private http = inject(HttpClient);<br><br>readonly users$ = this.users.asReadonly();<br>  constructor() {<br>    // toSignal and toObservable now clean up correctly<br>    // when this route&#39;s injector is destroyed<br>    this.loadInitialData();<br>  }<br>  private loadInitialData() {<br>    this.http.get&lt;User[]&gt;(&#39;/api/admin/users&#39;)<br>      .pipe(takeUntilDestroyed())<br>      .subscribe(users =&gt; this.users.set(users));<br>  }<br>  refreshUsers() {<br>    this.http.get&lt;User[]&gt;(&#39;/api/admin/users&#39;)<br>      .pipe(take(1))<br>      .subscribe(users =&gt; this.users.set(users));<br>  }<br>}</pre><h3>Custom RouteReuseStrategy: What You Need to Implement</h3><p>If your app doesn’t use a custom RouteReuseStrategy, or it extends BaseRouteReuseStrategy, you&#39;re done — injectors are automatically destroyed for inactive routes. The BaseRouteReuseStrategy already implements shouldDestroyInjector returning true.</p><p>If you have a <strong>fully custom</strong> RouteReuseStrategy that doesn&#39;t extend BaseRouteReuseStrategy, you need to implement two additional methods:</p><h3>shouldDestroyInjector</h3><p>Tells the router whether to destroy the injector for a given route. Return true to allow destruction.</p><h3>retrieveStoredRouteHandles</h3><p>If your strategy stores detached route handles, this method lets the router know which routes are stored so it doesn’t destroy their injectors.</p><pre>// custom-route-reuse-strategy.ts<br>import {<br>  RouteReuseStrategy,<br>  ActivatedRouteSnapshot,<br>  DetachedRouteHandle,<br>  Route<br>} from &#39;@angular/router&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br><br>@Injectable()<br>export class CustomRouteReuseStrategy implements RouteReuseStrategy {<br>  private storedHandles = new Map&lt;string, { handle: DetachedRouteHandle; route: Route }&gt;();<br>  shouldDetach(route: ActivatedRouteSnapshot): boolean {<br>    return route.data[&#39;reuseComponent&#39;] === true;<br>  }<br>  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {<br>    const key = this.getRouteKey(route);<br>    if (handle &amp;&amp; key) {<br>      this.storedHandles.set(key, { handle, route: route.routeConfig! });<br>    } else if (key) {<br>      this.storedHandles.delete(key);<br>    }<br>  }<br>  shouldAttach(route: ActivatedRouteSnapshot): boolean {<br>    const key = this.getRouteKey(route);<br>    return !!key &amp;&amp; this.storedHandles.has(key);<br>  }<br>  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {<br>    const key = this.getRouteKey(route);<br>    return key ? (this.storedHandles.get(key)?.handle ?? null) : null;<br>  }<br>  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {<br>    return future.routeConfig === curr.routeConfig;<br>  }<br>  // Required for withExperimentalAutoCleanupInjectors:<br>  // Tell the router which routes have stored handles<br>  retrieveStoredRouteHandles(): DetachedRouteHandle[] {<br>    return Array.from(this.storedHandles.values()).map(entry =&gt; entry.handle);<br>  }<br>  // Required for withExperimentalAutoCleanupInjectors:<br>  // Decide per-route whether its injector can be destroyed<br>  shouldDestroyInjector(route: Route): boolean {<br>    // Preserve the injector if this route has a stored handle<br>    const hasStoredHandle = Array.from(this.storedHandles.values())<br>      .some(entry =&gt; entry.route === route);<br>    return !hasStoredHandle;<br>  }<br>  private getRouteKey(route: ActivatedRouteSnapshot): string | null {<br>    return route.routeConfig?.path ?? null;<br>  }<br>}</pre><p>Register it in your app config:</p><pre>// app.config.ts<br>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import {<br>  provideRouter,<br>  withExperimentalAutoCleanupInjectors,<br>  RouteReuseStrategy<br>} from &#39;@angular/router&#39;;<br>import { routes } from &#39;./app.routes&#39;;<br>import { CustomRouteReuseStrategy } from &#39;./custom-route-reuse-strategy&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter(routes, withExperimentalAutoCleanupInjectors()),<br>    {<br>      provide: RouteReuseStrategy,<br>      useClass: CustomRouteReuseStrategy<br>    }<br>  ]<br>};</pre><h3>Signals and Reactive Primitives Now Work as Expected</h3><p>One of the biggest wins here is that Angular’s modern reactive primitives finally work correctly inside route-level services.</p><h3>toSignal in a Route-Scoped Service</h3><pre>// products/products.service.ts<br>@Injectable()<br>export class ProductsService {<br>  private http = inject(HttpClient);<br>  private route = inject(ActivatedRoute);<br><br>// toSignal requires an injection context.<br>  // It also subscribes internally - and previously never cleaned up<br>  // for route-level services. Now it does.<br>  readonly queryParam = toSignal(<br>    this.route.queryParamMap.pipe(map(params =&gt; params.get(&#39;category&#39;) ?? &#39;all&#39;)),<br>    { initialValue: &#39;all&#39; }<br>  );<br>  readonly products = toSignal(<br>    this.route.queryParamMap.pipe(<br>      map(params =&gt; params.get(&#39;category&#39;) ?? &#39;all&#39;),<br>      distinctUntilChanged(),<br>      switchMap(category =&gt; this.http.get&lt;Product[]&gt;(`/api/products?category=${category}`))<br>    ),<br>    { initialValue: [] }<br>  );<br>}</pre><h3>toObservable Works Correctly Too</h3><pre>// cart/cart.service.ts<br>@Injectable()<br>export class CartService {<br>  readonly items = signal&lt;CartItem[]&gt;([]);<br>  readonly totalCount = computed(() =&gt; this.items().reduce((sum, i) =&gt; sum + i.qty, 0));<br><br>// Previously, toObservable subscriptions leaked if this service was route-scoped.<br>  // Now the injector cleanup handles it automatically.<br>  readonly totalCount$ = toObservable(this.totalCount);<br>}</pre><h3>Writing Unit Tests for Injector Cleanup</h3><p>Testing that your services clean up properly is important, especially with this feature. Here’s how to verify it:</p><pre>// dashboard-notifications.service.spec.ts<br>import { TestBed, fakeAsync, tick, discardPeriodicTasks } from &#39;@angular/core/testing&#39;;<br>import { HttpClientTestingModule, HttpTestingController } from &#39;@angular/common/http/testing&#39;;<br>import { DashboardNotificationsService } from &#39;./dashboard-notifications.service&#39;;<br><br>describe(&#39;DashboardNotificationsService&#39;, () =&gt; {<br>  let service: DashboardNotificationsService;<br>  let httpMock: HttpTestingController;<br>  beforeEach(() =&gt; {<br>    TestBed.configureTestingModule({<br>      imports: [HttpClientTestingModule],<br>      providers: [DashboardNotificationsService]<br>    });<br>    service = TestBed.inject(DashboardNotificationsService);<br>    httpMock = TestBed.inject(HttpTestingController);<br>  });<br>  afterEach(() =&gt; {<br>    httpMock.verify();<br>  });<br>  it(&#39;should initialize with empty notifications&#39;, () =&gt; {<br>    expect(service.notifications()).toEqual([]);<br>  });<br>  it(&#39;should stop polling when the injector is destroyed&#39;, fakeAsync(() =&gt; {<br>    // Simulate one polling cycle<br>    tick(5000);<br>    const req = httpMock.expectOne(&#39;/api/notifications&#39;);<br>    req.flush([{ id: 1, message: &#39;Test notification&#39; }]);<br>    expect(service.notifications().length).toBe(1);<br>    // Destroy the TestBed (simulates injector destruction)<br>    TestBed.resetTestingModule();<br>    // Tick further - no more HTTP requests should be made<br>    // (this would throw if polling were still active)<br>    discardPeriodicTasks();<br>  }));<br>  it(&#39;should update notifications signal when data arrives&#39;, fakeAsync(() =&gt; {<br>    tick(5000);<br>    const mockNotifications = [<br>      { id: 1, message: &#39;First notification&#39; },<br>      { id: 2, message: &#39;Second notification&#39; }<br>    ];<br>    const req = httpMock.expectOne(&#39;/api/notifications&#39;);<br>    req.flush(mockNotifications);<br>    expect(service.notifications().length).toBe(2);<br>    expect(service.notifications()[0].message).toBe(&#39;First notification&#39;);<br>    discardPeriodicTasks();<br>  }));<br>});</pre><p>Testing the CustomRouteReuseStrategy with the new methods:</p><pre>// custom-route-reuse-strategy.spec.ts<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { ActivatedRouteSnapshot, DetachedRouteHandle, Route } from &#39;@angular/router&#39;;<br>import { CustomRouteReuseStrategy } from &#39;./custom-route-reuse-strategy&#39;;<br><br>describe(&#39;CustomRouteReuseStrategy&#39;, () =&gt; {<br>  let strategy: CustomRouteReuseStrategy;<br>  beforeEach(() =&gt; {<br>    TestBed.configureTestingModule({<br>      providers: [CustomRouteReuseStrategy]<br>    });<br>    strategy = TestBed.inject(CustomRouteReuseStrategy);<br>  });<br>  it(&#39;should return empty array when no handles are stored&#39;, () =&gt; {<br>    expect(strategy.retrieveStoredRouteHandles()).toEqual([]);<br>  });<br>  it(&#39;should return stored handles via retrieveStoredRouteHandles&#39;, () =&gt; {<br>    const mockRoute = { routeConfig: { path: &#39;test&#39;, data: { reuseComponent: true } } } as ActivatedRouteSnapshot;<br>    const mockHandle = {} as DetachedRouteHandle;<br>    strategy.store(mockRoute, mockHandle);<br>    const handles = strategy.retrieveStoredRouteHandles();<br>    expect(handles.length).toBe(1);<br>    expect(handles[0]).toBe(mockHandle);<br>  });<br>  it(&#39;shouldDestroyInjector should return true for non-stored routes&#39;, () =&gt; {<br>    const route: Route = { path: &#39;some-route&#39; };<br>    expect(strategy.shouldDestroyInjector(route)).toBe(true);<br>  });<br>  it(&#39;shouldDestroyInjector should return false for stored route handles&#39;, () =&gt; {<br>    const mockRoute = {<br>      routeConfig: { path: &#39;cached&#39;, data: { reuseComponent: true } }<br>    } as ActivatedRouteSnapshot;<br>    const mockHandle = {} as DetachedRouteHandle;<br>    strategy.store(mockRoute, mockHandle);<br>    // The route from routeConfig should be preserved<br>    const storedRoute = mockRoute.routeConfig!;<br>    expect(strategy.shouldDestroyInjector(storedRoute)).toBe(false);<br>  });<br>  it(&#39;should clean up stored handle on null store call&#39;, () =&gt; {<br>    const mockRoute = {<br>      routeConfig: { path: &#39;test&#39;, data: { reuseComponent: true } }<br>    } as ActivatedRouteSnapshot;<br>    const mockHandle = {} as DetachedRouteHandle;<br>    strategy.store(mockRoute, mockHandle);<br>    expect(strategy.retrieveStoredRouteHandles().length).toBe(1);<br>    strategy.store(mockRoute, null);<br>    expect(strategy.retrieveStoredRouteHandles().length).toBe(0);<br>  });<br>});</pre><h3>Bonus Tips</h3><p><strong>Tip 1: Pair with </strong><strong>DestroyRef for fine-grained control.</strong><br> Inside your route-scoped services, inject DestroyRef directly and run your own cleanup logic on top of what Angular does automatically:</p><pre>@Injectable()<br>export class FeatureService {<br>  private destroyRef = inject(DestroyRef);<br><br>constructor() {<br>    this.destroyRef.onDestroy(() =&gt; {<br>      console.log(&#39;FeatureService cleaned up - route injector was destroyed&#39;);<br>      // Any additional cleanup not covered by takeUntilDestroyed<br>    });<br>    interval(2000)<br>      .pipe(takeUntilDestroyed(this.destroyRef))<br>      .subscribe(() =&gt; this.poll());<br>  }<br>  private poll() { /* ... */ }<br>}</pre><p><strong>Tip 2: It’s experimental, not unstable.</strong><br> The “experimental” label means the API might change in minor ways before stabilization. The core behavior is already solid. Add it to greenfield projects and new route features now — just watch the Angular changelog for any API updates.</p><p><strong>Tip 3: Parent injector destruction cascades.</strong><br> If a parent route’s injector is destroyed, all child route injectors are destroyed regardless of their individual shouldDestroyInjector return values. Design your route hierarchy with this in mind.</p><p><strong>Tip 4: Don’t put it in a </strong><strong>@NgModule.</strong><br> This is a provider function for the functional provideRouter API. If you&#39;re still using RouterModule.forRoot(), this won&#39;t work. Time to migrate if you haven&#39;t already.</p><h3>Recap: What We Covered</h3><p>Here’s the full picture in one place:</p><p><strong>The problem:</strong> Route-level EnvironmentInjectors were never destroyed in Angular, causing memory leaks and making takeUntilDestroyed(), toSignal(), and toObservable() unreliable in route-scoped services.</p><p><strong>The fix:</strong> withExperimentalAutoCleanupInjectors() — one call in provideRouter — enables automatic destruction of route injectors after navigation, when routes are no longer active and not stored for reuse.</p><p><strong>How it works:</strong> After NavigationEnd, Angular checks each route&#39;s injector against the active route tree and the RouteReuseStrategy. Injectors for inactive, non-reused routes are destroyed. Parent destruction cascades to children.</p><p><strong>What you need for custom strategies:</strong> Implement shouldDestroyInjector() and retrieveStoredRouteHandles() in any custom RouteReuseStrategy that doesn&#39;t extend BaseRouteReuseStrategy.</p><p><strong>The payoff:</strong> Modern Angular APIs like Signals, takeUntilDestroyed(), toSignal(), and ngOnDestroy work correctly and reliably in route-scoped services.</p><h3>Let’s Talk</h3><p>What did you think? Have you already hit this exact issue in production, or is this something you’ll proactively add to your next project? Vote in the comments:</p><ul><li>A: Already hit this issue and solved it manually</li><li>B: Did not know about this leak — applying the fix now</li><li>C: Still on an older Angular version and need to migrate first</li></ul><p>If this saved you from a subtle memory leak, hit that clap button — it takes one second and helps other Angular devs find this article. You’d be doing the community a real favor.</p><p>Follow Me for More Angular &amp; Frontend Goodness:</p><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/"><strong>Reddit</strong></a>— Developer blog posts &amp; tech discussions</li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=557a5b89fa4a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/stop-leaking-memory-in-angular-withexperimentalautocleanupinjectors-explained-557a5b89fa4a">Stop Leaking Memory in Angular: withExperimentalAutoCleanupInjectors Explained</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular CDK Got Better in Angular 22: Host Directive De-Duplication and Portal Directives Explained…]]></title>
            <link>https://javascript.plainenglish.io/angular-cdk-got-better-in-angular-22-host-directive-de-duplication-and-portal-directives-explained-3f3c1b50dcc9?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f3c1b50dcc9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 13:39:50 GMT</pubDate>
            <atom:updated>2026-09-15T13:39:50.122Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular CDK Got Better in Angular 22: Host Directive De-Duplication and Portal Directives Explained -What Changes in NG 22 (Part 11)</h3><h4>Why composing small, reusable directives used to break in surprising ways and how the CDK’s dynamic component rendering just got a lot more capable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmVYtsFVnSDOIDA3BZV31w.png" /></figure><p>Ever built two small, focused host directives, only to slap them both on the same element and get a duplicate directive error that made no sense at first glance? If you’ve spent time with Angular’s Directive Composition API, there’s a good chance you’ve hit exactly this wall — two directives that each quietly pull in the same shared behavior, and Angular refusing to let them coexist.</p><p>Angular 22 fixes that, and pairs it with a second, less talked-about improvement: the CDK’s ComponentPortal can now attach directives to a component it renders dynamically. Both changes are aimed at the same underlying problem — composing behavior without duplicating it or baking it into components that shouldn&#39;t need to know about it. This one&#39;s a bit more advanced than the usual &quot;here&#39;s a new signal function&quot; post, so it&#39;ll appeal most if you write shared directives, build component libraries, or lean on the CDK&#39;s Portal API for dynamic rendering. By the end, you&#39;ll know:</p><ul><li>Why two directives that both use hostDirectives to pull in the same shared directive used to conflict</li><li>How Angular 22’s de-duplication resolves that, and the one rule you still have to follow</li><li>How ComponentPortal can now apply directives to a dynamically rendered component&#39;s host element</li><li>How the same directive can travel with a component across both CdkPortalOutlet and DomPortalOutlet</li><li>How to unit test both patterns</li></ul><p>If you’ve been following the rest of this Angular 22 series — resources, the router, templates, the AI tooling — this is the entry aimed squarely at library authors and anyone building serious component composition. If none of that rings a bell yet, it’s worth a look too; these patterns show up the moment your app grows past a handful of components.</p><p>One thing before we dig in: this is the kind of topic that doesn’t get nearly enough coverage, so if it’s useful, following me here means you catch the next one of these instead of scrolling past it later.</p><blockquote><em>Before we dive into the examples, a quick note: the code snippets provided here are meant purely for understanding the concept. Some syntax shown may reflect patterns from earlier Angular versions. Always refer to the official documentation for the most current API and syntax.</em></blockquote><h3>The problem: shared behavior, duplicated by accident</h3><p>Angular’s Directive Composition API lets a directive pull in another directive’s behavior through hostDirectives, which is a great way to keep each directive small and focused instead of writing one directive that does everything. The trouble starts when two <em>different</em> higher-level directives both happen to reuse the same lower-level one — a pattern that&#39;s common the moment you&#39;re building a small internal library rather than a one-off feature.</p><p>Say you’ve got a shared directive that manages a transient, accessible status message on whatever element it’s attached to:</p><pre>import { computed, DestroyRef, Directive, inject, input, signal } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appStatusMessage]&#39;,<br>  host: {<br>    &#39;aria-live&#39;: &#39;polite&#39;,<br>    &#39;[attr.data-status]&#39;: &#39;visibleMessage()&#39;,<br>    &#39;[class.show-status]&#39;: &#39;hasMessage()&#39;,<br>  },<br>})<br>export class StatusMessageDirective {<br>  readonly idleLabel = input(&#39;&#39;);<br>  private readonly temporaryMessage = signal&lt;string | null&gt;(null);<br>  private timeoutId: ReturnType&lt;typeof setTimeout&gt; | null = null;<br>  private readonly destroyRef = inject(DestroyRef);<br>  constructor() {<br>    this.destroyRef.onDestroy(() =&gt; this.clear());<br>  }<br>  protected readonly hasMessage = computed(() =&gt; this.temporaryMessage() !== null);<br>  protected readonly visibleMessage = computed(<br>    () =&gt; this.temporaryMessage() ?? this.idleLabel(),<br>  );<br>  announce(message: string, duration = 2000): void {<br>    this.clear();<br>    this.temporaryMessage.set(message);<br>    this.timeoutId = setTimeout(() =&gt; this.temporaryMessage.set(null), duration);<br>  }<br>  private clear(): void {<br>    if (this.timeoutId !== null) {<br>      clearTimeout(this.timeoutId);<br>      this.timeoutId = null;<br>    }<br>  }<br>}</pre><p>Now build two independent, higher-level directives on top of it — one that toggles a favorite state, one that copies a share link — and have each of them compose StatusMessageDirective to announce what just happened.</p><pre>import { Directive, inject, input, signal } from &#39;@angular/core&#39;;<br>import { StatusMessageDirective } from &#39;./status-message.directive&#39;;<br><br>@Directive({<br>  selector: &#39;[appFavoriteToggle]&#39;,<br>  hostDirectives: [{ directive: StatusMessageDirective, inputs: [&#39;idleLabel: status&#39;] }],<br>  host: {<br>    &#39;(click)&#39;: &#39;toggle()&#39;,<br>    &#39;[class.is-favorited]&#39;: &#39;favorited()&#39;,<br>  },<br>})<br>export class FavoriteToggleDirective {<br>  readonly itemId = input.required&lt;string&gt;();<br>  protected readonly favorited = signal(false);<br>  private readonly status = inject(StatusMessageDirective);<br>  protected toggle(): void {<br>    this.favorited.update((current) =&gt; !current);<br>    this.status.announce(<br>      this.favorited() ? &#39;Added to favorites&#39; : &#39;Removed from favorites&#39;,<br>    );<br>  }<br>}</pre><pre>import { Directive, inject, input } from &#39;@angular/core&#39;;<br>import { StatusMessageDirective } from &#39;./status-message.directive&#39;;<br><br>@Directive({<br>  selector: &#39;[appShareLink]&#39;,<br>  hostDirectives: [{ directive: StatusMessageDirective, inputs: [&#39;idleLabel: status&#39;] }],<br>  host: {<br>    &#39;(click)&#39;: &#39;share()&#39;,<br>  },<br>})<br>export class ShareLinkDirective {<br>  readonly url = input.required&lt;string&gt;();<br>  private readonly status = inject(StatusMessageDirective);<br>  protected async share(): Promise&lt;void&gt; {<br>    try {<br>      await navigator.clipboard.writeText(this.url());<br>      this.status.announce(&#39;Link copied&#39;);<br>    } catch {<br>      this.status.announce(&#39;Unable to copy link&#39;);<br>    }<br>  }<br>}</pre><p>Both directives are small, focused, and independently useful. Naturally, you’ll want to apply both to the same action bar so a card’s footer can both favorite and share, sharing one status announcement region:</p><pre>&lt;div<br>  appFavoriteToggle<br>  [itemId]=&quot;item.id&quot;<br>  appShareLink<br>  [url]=&quot;item.shareUrl&quot;<br>  status=&quot;Card actions&quot;<br>  class=&quot;card-actions&quot;<br>&gt;<br>  &lt;button aria-label=&quot;Favorite&quot;&gt;Favorite&lt;/button&gt;<br>  &lt;button aria-label=&quot;Share&quot;&gt;Share&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Before Angular 22, this setup throws a duplicate directive error. Angular sees appFavoriteToggle bringing in StatusMessageDirective, sees appShareLink bringing in the very same directive, and concludes — incorrectly, from your point of view — that the same directive is being matched twice on one element. You weren&#39;t trying to create two separate status regions; you were composing two independent behaviors that happen to share one lower-level dependency, which is exactly the kind of thing you&#39;d expect the Directive Composition API to support cleanly.</p><h3>Angular 22 de-duplicates shared host directives</h3><p>Angular 22 fixes this directly: when the same directive shows up more than once in the resolved host directive tree, Angular merges those matches into a single shared instance instead of treating them as a conflict. The two action-bar directives above now work together without any code changes on your part — the composition just works the way you’d expect.</p><p>There’s one rule worth keeping in mind, though. Angular still has to reconcile the input and output aliases from every place the shared directive is composed, so if two directives expose the same underlying input under two different aliases, you’re back to an error — this time NG8024, conflicting host directive binding. In the example above, both FavoriteToggleDirective and ShareLinkDirective alias idleLabel to status, which is exactly why they merge cleanly. If one of them had aliased it to something else instead, Angular wouldn&#39;t be able to decide which public name should win.</p><p>So the practical rule is simple: if multiple directives in your library reuse the same shared host directive, keep their aliases for that directive’s inputs and outputs consistent across the board.</p><p>Have you run into this exact duplicate-directive error before finding out why it was happening? I’d genuinely like to know whether people worked around it by merging directives into one, or just avoided composing them on the same element entirely.</p><h3>Dynamic component rendering gets more capable: directives on ComponentPortal</h3><p>The CDK’s Portal API is Angular’s lower-level tool for dynamic component rendering — instead of declaring a component in a template, you describe it as a ComponentPortal and hand it to a PortalOutlet to actually create and attach. Until this release, a component rendered this way had no clean way to receive host-level behavior specific to <em>where</em> it was being rendered — you either baked that behavior into the component itself, which coupled it to one particular context, or you left it out.</p><p>Say you have a small NotificationPanel component that needs to behave like an accessible live region — role=&quot;status&quot;, aria-live=&quot;polite&quot;, and focus when it appears — but you render it in two different places: inline inside a page, and as a floating panel attached directly to the document body.</p><p>A directive is the right home for that host-level behavior, since it keeps NotificationPanel itself free of any assumptions about where it&#39;s rendered:</p><pre>import { afterNextRender, Directive, ElementRef, inject, input } from &#39;@angular/core&#39;;<br><br><br>@Directive({<br>  selector: &#39;[appLiveRegion]&#39;,<br>  host: {<br>    role: &#39;status&#39;,<br>    &#39;aria-live&#39;: &#39;polite&#39;,<br>    &#39;[attr.aria-label]&#39;: &#39;label()&#39;,<br>    tabindex: &#39;-1&#39;,<br>  },<br>})<br>export class LiveRegionDirective {<br>  readonly label = input(&#39;&#39;);<br>  private readonly elementRef = inject(ElementRef);<br>  constructor() {<br>    afterNextRender(() =&gt; this.elementRef.nativeElement.focus());<br>  }<br>}</pre><p>Angular 22 lets ComponentPortal apply directives like this one directly to the component it creates. The directive configuration is passed as an additional argument alongside the existing portal options, using inputBinding() to feed values into the directive:</p><pre>import { ComponentPortal } from &#39;@angular/cdk/portal&#39;;<br>import { inputBinding } from &#39;@angular/core&#39;;<br>import { NotificationPanel } from &#39;./notification-panel&#39;;<br>import { LiveRegionDirective } from &#39;./live-region.directive&#39;;<br><br>protected readonly notificationPortal = computed(() =&gt;<br>  this.showNotification()<br>    ? new ComponentPortal(<br>        NotificationPanel,<br>        null, // viewContainerRef<br>        null, // injector<br>        null, // projectableNodes<br>        undefined, // bindings<br>        [<br>          {<br>            type: LiveRegionDirective,<br>            bindings: [inputBinding(&#39;label&#39;, () =&gt; &#39;Order status update&#39;)],<br>          },<br>        ],<br>      )<br>    : null,<br>);</pre><p>The inline version renders through a template outlet, just like any other ComponentPortal usage:</p><pre>&lt;ng-template [cdkPortalOutlet]=&quot;notificationPortal()&quot;&gt;&lt;/ng-template&gt;</pre><p>For the floating version, you attach the same kind of portal — with the same directive, but a different label — to a DomPortalOutlet targeting an element appended straight to the document body:</p><pre>import { DomPortalOutlet } from &#39;@angular/cdk/portal&#39;;<br><br>private openFloatingNotification(): void {<br>  const hostElement = this.document.createElement(&#39;div&#39;);<br>  hostElement.classList.add(&#39;floating-notification&#39;);<br>  this.document.body.append(hostElement);<br>  const outlet = new DomPortalOutlet(hostElement, this.appRef, this.injector);<br>  outlet.attach(<br>    new ComponentPortal(<br>      NotificationPanel,<br>      null,<br>      null,<br>      null,<br>      undefined,<br>      [<br>        {<br>          type: LiveRegionDirective,<br>          bindings: [inputBinding(&#39;label&#39;, () =&gt; &#39;Floating order update&#39;)],<br>        },<br>      ],<br>    ),<br>  );<br>}</pre><p>Same component, same directive, two different rendering contexts, two different accessible labels — and NotificationPanel itself never has to know any of that. The portal, not the component, decides what host-level behavior fits the place it&#39;s being rendered.</p><h3>Unit testing both patterns</h3><p>Testing host directive composition is straightforward: mount a host component that applies both directives, trigger the interaction, and check the shared directive’s effect on the DOM.</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { FavoriteToggleDirective } from &#39;./favorite-toggle.directive&#39;;<br>import { ShareLinkDirective } from &#39;./share-link.directive&#39;;<br><br>@Component({<br>  selector: &#39;app-test-host&#39;,<br>  imports: [FavoriteToggleDirective, ShareLinkDirective],<br>  template: `<br>    &lt;div<br>      appFavoriteToggle<br>      itemId=&quot;item-1&quot;<br>      appShareLink<br>      [url]=&quot;shareUrl()&quot;<br>      status=&quot;Card actions&quot;<br>    &gt;&lt;/div&gt;<br>  `,<br>})<br>class TestHost {<br>  protected readonly shareUrl = signal(&#39;&lt;https://example.com/item-1&gt;&#39;);<br>}<br>describe(&#39;FavoriteToggleDirective and ShareLinkDirective composition&#39;, () =&gt; {<br>  it(&#39;applies without a duplicate directive error and shares one status region&#39;, () =&gt; {<br>    const fixture = TestBed.createComponent(TestHost);<br>    fixture.detectChanges();<br>    const host = fixture.nativeElement.querySelector(&#39;[appFavoriteToggle]&#39;);<br>    expect(host.getAttribute(&#39;data-status&#39;)).toBe(&#39;Card actions&#39;);<br>    host.dispatchEvent(new Event(&#39;click&#39;));<br>    fixture.detectChanges();<br>    expect(host.getAttribute(&#39;data-status&#39;)).toBe(&#39;Added to favorites&#39;);<br>  });<br>});</pre><p>For the Portal directive, the useful thing to verify is that the directive’s host attributes actually land on the dynamically rendered component, not just that the portal attaches without throwing.</p><pre>import { Component, ViewChild } from &#39;@angular/core&#39;;<br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { CdkPortalOutlet, ComponentPortal, PortalModule } from &#39;@angular/cdk/portal&#39;;<br>import { inputBinding } from &#39;@angular/core&#39;;<br>import { NotificationPanel } from &#39;./notification-panel&#39;;<br>import { LiveRegionDirective } from &#39;./live-region.directive&#39;;<br><br>@Component({<br>  selector: &#39;app-portal-host&#39;,<br>  imports: [PortalModule],<br>  template: `&lt;ng-template [cdkPortalOutlet]=&quot;portal&quot;&gt;&lt;/ng-template&gt;`,<br>})<br>class PortalHost {<br>  @ViewChild(CdkPortalOutlet) outlet!: CdkPortalOutlet;<br>  protected readonly portal = new ComponentPortal(<br>    NotificationPanel,<br>    null,<br>    null,<br>    null,<br>    undefined,<br>    [<br>      {<br>        type: LiveRegionDirective,<br>        bindings: [inputBinding(&#39;label&#39;, () =&gt; &#39;Order status update&#39;)],<br>      },<br>    ],<br>  );<br>}<br>describe(&#39;NotificationPanel rendered through a portal&#39;, () =&gt; {<br>  it(&#39;receives the live region directive on its host element&#39;, () =&gt; {<br>    const fixture = TestBed.createComponent(PortalHost);<br>    fixture.detectChanges();<br>    const panel = fixture.nativeElement.querySelector(&#39;app-notification-panel&#39;);<br>    expect(panel.getAttribute(&#39;role&#39;)).toBe(&#39;status&#39;);<br>    expect(panel.getAttribute(&#39;aria-label&#39;)).toBe(&#39;Order status update&#39;);<br>  });<br>});</pre><p>Both tests check the same kind of thing, really: that behavior composed from the outside actually lands on the element it’s supposed to, without requiring the component underneath to know anything about it.</p><h3>Bonus tips</h3><ul><li><strong>Keep shared host directives narrow.</strong> The de-duplication fix makes sharing a common directive across multiple composed directives safe, but it’s still easiest to reason about if that shared directive does one well-defined thing — a status message, a focus behavior — rather than several.</li><li><strong>Watch for </strong><strong>NG8024 after upgrading, not before.</strong> If you already had multiple directives quietly composing the same shared directive under different aliases, that setup was probably throwing the old duplicate-directive error already — this is a good moment to align those aliases rather than something that suddenly needs fixing.</li><li><strong>ComponentPortal&#39;s directive argument is verbose on purpose — wrap it if you use it often.</strong> Passing null through several unused constructor arguments just to reach the new directives array gets old fast; a small helper function that fills in the boilerplate arguments is worth writing if you&#39;re doing this more than once or twice.</li><li><strong>Pair Portal directives with </strong><strong>ApplicationRef.bootstrap()&#39;s new config object for micro frontends.</strong> Angular 22 also lets bootstrap() accept a configuration object, including a hostElement, which is a natural complement to Portal-based dynamic rendering when you&#39;re mounting Angular components into DOM the framework didn&#39;t create.</li><li><strong>Don’t reach for Portal directives just to avoid passing an </strong><strong>@Input.</strong> This pattern earns its complexity when the same component genuinely needs different host behavior in different rendering contexts — for a component that always needs the same behavior everywhere, a plain input is still simpler.</li></ul><h3>Recap</h3><p>Angular 22’s CDK improvements are both about the same idea from different angles: composing behavior without duplicating it. Host directive de-duplication means small, focused directives that share a common dependency no longer conflict just because two higher-level directives happen to need the same lower-level one — as long as their aliases agree. And ComponentPortal accepting directives means a dynamically rendered component can pick up context-specific host behavior from wherever it&#39;s being rendered, without that behavior getting baked into the component itself.</p><p>Neither change is something you’ll hit on day one with a simple app, but the moment you’re building a shared directive library, or rendering the same component through more than one Portal outlet, both of these are exactly the kind of fix that turns “this shouldn’t be this hard” into “oh, that’s clean.”</p><p><strong>What did you think?</strong><br> Did this approach match how you are solving it, or do you have a different take? Drop a comment — I genuinely read every single one.</p><p><strong>Found this helpful?</strong><br> If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong><br> I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let us connect — find me on LinkedIn or GitHub and let us keep the conversation going.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">*Reddit</a>* — Developer blog posts &amp; tech discussions</li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f3c1b50dcc9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-cdk-got-better-in-angular-22-host-directive-de-duplication-and-portal-directives-explained-3f3c1b50dcc9">Angular CDK Got Better in Angular 22: Host Directive De-Duplication and Portal Directives Explained…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Is Preparing for AI Agents: WebMCP, MCP Tooling, and Agent Skills in Angular 22 — — What…]]></title>
            <link>https://javascript.plainenglish.io/angular-is-preparing-for-ai-agents-webmcp-mcp-tooling-and-agent-skills-in-angular-22-what-875fc0bfca8e?source=rss-f0de257e3ede------2</link>
            <guid isPermaLink="false">https://medium.com/p/875fc0bfca8e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Rajat]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 12:59:26 GMT</pubDate>
            <atom:updated>2026-09-08T13:08:48.000Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Is Preparing for AI Agents: WebMCP, MCP Tooling, and Agent Skills in Angular 22 — — What Changes in NG 22 (Part 10)</h3><p>How Angular 22 lets AI coding agents build your app faster, debug it live, and with WebMCP actually call it like a tool</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SNpLWqKUQPhx48lFDLx4g.png" /></figure><p>What if an AI agent didn’t just help you write your Angular app, but could also use it directly once it’s running — clicking through a form, listing your users, creating a record — the same way it would call an API? That’s not a hypothetical anymore. Angular 22 ships real, if early, plumbing for exactly that, alongside a quieter but more immediately useful set of tools that make AI coding agents genuinely better at writing Angular code today.</p><p>This is a genuinely confusing area of the release if you only skim the changelog, because “AI features” in Angular 22 actually means two very different things bundled together. One half is about agents that help <em>you</em> build and debug your app. The other half — WebMCP — is about your app becoming something an agent can operate on its own. We’re going to untangle both, with working code for each. By the end you’ll know:</p><ul><li>What Agent Skills are and how they change what your coding agent does when it generates Angular code</li><li>How the Angular CLI’s MCP server plugs your agent into your actual project instead of its training data</li><li>How Angular exposes a live signal graph and dependency injection graph for AI-assisted debugging</li><li>What WebMCP is, and how to declare a tool an agent can call directly from a component</li><li>How to auto-generate a WebMCP tool straight from a Signal Form</li><li>How to unit test the logic behind a WebMCP tool like you would any other method</li></ul><p>If you’ve been following this series on Angular 22 — the stable Resource API, the router changes, the template improvements — this is the odd one out, and arguably the one worth paying closest attention to if you think agentic tooling is going to matter for frontend work over the next couple of years.</p><p>Quick ask before we get into it: this is a fast-moving corner of the framework, and I’ll be writing more as WebMCP matures past experimental status. Follow along here if you’d rather not have to go digging for the next update yourself.</p><blockquote><em>Before we dive into the examples, a quick note: the code snippets provided here are meant purely for understanding the concept. Some syntax shown may reflect patterns from earlier Angular versions, and a few APIs covered here are explicitly experimental as of this writing. Always refer to the official documentation for the most current API and syntax.</em></blockquote><h3>Two different problems, both labeled “AI”</h3><p>Worth being precise about this before any code, because the two halves of Angular’s AI story solve genuinely different problems:</p><ul><li><strong>Agents that build and debug your app.</strong> This is the Angular CLI’s MCP server, the new Agent Skills, and in-browser debugging tools exposed through Chrome DevTools. None of this ships in your production bundle — it’s tooling that makes Claude, or whichever coding agent you use, better at working inside an Angular codebase.</li><li><strong>Your app as something an agent can operate.</strong> This is WebMCP. It ships in your application code, and it’s about exposing specific capabilities — “list users,” “create a booking” — that an agent visiting your site can call directly, instead of having to simulate clicks on your UI.</li></ul><p>Let’s take them in that order.</p><h3>Agent Skills: teaching your coding agent how Angular actually works</h3><p>The Angular CLI has shipped an MCP server since v20.1, giving coding agents a way to interact with your project directly rather than guessing from general training data. Angular 22 adds Agent Skills on top of that — a packaged set of guidelines that teach an agent how to generate idiomatic, current Angular code and provide architectural guidance, rather than falling back on outdated patterns it may have picked up from older tutorials.</p><pre>npx skills add &lt;https://github.com/angular/skills&gt;</pre><p>That command installs two skills: one focused on scaffolding new Angular projects correctly, and a second, broader one covering code generation and architecture guidance across the framework. Once installed, an agent working in your repository picks up the relevant skill automatically when you ask it to generate Angular code — you don’t have to reference it explicitly in every prompt.</p><p>One side effect worth knowing about: with skills now handling code-generation guidance, the CLI’s MCP server dropped its find_examples and modernize tools, since the skill covers that ground more thoroughly than a lookup tool could. If you had scripts or workflows depending on those specific tools, that&#39;s worth double-checking after upgrading.</p><h3>Debugging with AI: exposing the signal graph and the DI graph</h3><p>Angular 22 also registers two debugging tools that a development build exposes for tooling to consume: a signal graph and a dependency injection graph, the same data Angular DevTools already visualizes. These are registered in Chrome DevTools as third-party tools, which means an agent connected through <a href="https://github.com/ChromeDevTools/chrome-devtools-mcp">chrome-devtools-mcp</a> can query your application&#39;s actual runtime state — which signals exist, how they&#39;re connected, what&#39;s injected where — instead of trying to infer it from source code alone.</p><p>This does need a bit of setup, since third-party DevTools tools require enabling specific MCP flags, but once wired up, an agent debugging a signal that isn’t updating the way you expect can look at the real dependency graph rather than guessing from a stack trace.</p><h3>WebMCP: your app as a tool an agent can call</h3><p>Here’s the part that’s genuinely new territory. <a href="https://developer.chrome.com/docs/ai/webmcp">WebMCP</a> is a proposed web standard — not an Angular-specific idea — that lets a website expose Model Context Protocol capabilities directly from the page itself. Instead of an agent needing a separate MCP server running somewhere on your machine or in the cloud, the website becomes the tool: an agent visiting your app can call a capability you’ve explicitly exposed, the same way it would call any other MCP tool.</p><p>As of this release it’s early: WebMCP is only available behind a flag in Chrome Beta, and the Angular APIs built around it are explicitly marked experimental. That said, the shape of the API is worth understanding now, because it’s a genuinely different way to think about what a component exposes.</p><h3>Declaring a tool imperatively</h3><p>declareExperimentalWebMcpTool(), available in @angular/core, lets you register a callable tool directly inside a component.</p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { declareExperimentalWebMcpTool } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Component({<br>  selector: &#39;app-users&#39;,<br>  template: `&lt;p&gt;User management is available to connected agents.&lt;/p&gt;`,<br>})<br>export class Users {<br>  constructor() {<br>    declareExperimentalWebMcpTool({<br>      name: &#39;list_users&#39;,<br>      description: &#39;List users with a specific status&#39;,<br>      inputSchema: {<br>        type: &#39;object&#39;,<br>        properties: {<br>          status: { type: &#39;string&#39;, enum: [&#39;ADMINS&#39;, &#39;STUDENTS&#39;] },<br>        },<br>        required: [&#39;status&#39;],<br>        additionalProperties: false,<br>      },<br>      execute: ({ status }) =&gt; {<br>        return inject(UserService).list(status);<br>      },<br>    });<br>  }<br>}</pre><p>Two things worth calling out. First, inject() works inside the tool&#39;s execute function, so the tool can lean on Angular&#39;s dependency injection exactly like any other piece of component logic — you&#39;re not reaching outside the framework to wire this up. Second, Angular destroys the tool automatically when the component is destroyed, so a tool scoped to a page that&#39;s no longer active stops being callable without any manual cleanup on your part.</p><p>If you’d rather register a tool at the application level instead of tying it to a specific component’s lifecycle, provideExperimentalWebMcpTool() does that from your app config.</p><pre>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideExperimentalWebMcpTool } from &#39;@angular/core&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideExperimentalWebMcpTool([<br>      {<br>        name: &#39;list_users&#39;,<br>        description: &#39;List users with a specific status&#39;,<br>        inputSchema: {<br>          type: &#39;object&#39;,<br>          properties: {<br>            status: { type: &#39;string&#39;, enum: [&#39;ADMINS&#39;, &#39;STUDENTS&#39;] },<br>          },<br>          required: [&#39;status&#39;],<br>          additionalProperties: false,<br>        },<br>        execute: ({ status }) =&gt; {<br>          return inject(UserService).list(status);<br>        },<br>      },<br>    ]),<br>  ],<br>};</pre><p>Would you actually expose write operations — creating or deleting records — through something like this today, or only read-only capabilities until the standard and the tooling around it mature? I lean toward read-only for now, but I’m curious where other people draw that line.</p><h3>The declarative path: auto-registering tools from Signal Forms</h3><p>The second half of WebMCP’s proposal is a declarative API, where a plain HTML form gets marked up with toolname and tooldescription attributes to become agent-callable automatically. Angular&#39;s Signal Forms integrate with this directly, so if your form is already built with form(), you don&#39;t need to hand-write a schema at all.</p><p>Enable it once, at the application level:</p><pre>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideExperimentalWebMcpForms } from &#39;@angular/forms/signal&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [provideExperimentalWebMcpForms()],<br>};</pre><p>Then describe the tool as part of the form definition itself:</p><pre>import { Component, signal } from &#39;@angular/core&#39;;<br>import { form, required } from &#39;@angular/forms/signals&#39;;<br><br>interface NewUser {<br>  name: string;<br>  email: string;<br>}<br>@Component({<br>  selector: &#39;app-user-creation&#39;,<br>  template: `<br>    &lt;form&gt;<br>      &lt;input [formField]=&quot;userForm.name&quot; placeholder=&quot;Name&quot; /&gt;<br>      &lt;input [formField]=&quot;userForm.email&quot; placeholder=&quot;Email&quot; /&gt;<br>    &lt;/form&gt;<br>  `,<br>})<br>export class UserCreation {<br>  protected readonly model = signal&lt;NewUser&gt;({ name: &#39;&#39;, email: &#39;&#39; });<br>  protected readonly userForm = form(<br>    this.model,<br>    (path) =&gt; {<br>      required(path.name);<br>      required(path.email);<br>    },<br>    {<br>      experimentalWebMcpTool: {<br>        name: &#39;user_creation&#39;,<br>        description: &#39;Form to create a new user&#39;,<br>      },<br>    },<br>  );<br>}</pre><p>Angular takes care of the rest: it generates the tool’s input schema from the form fields themselves, and when an agent calls the tool, it fills the form with the provided input and submits it — the same validation your human users go through applies to the agent too. That last part matters more than it might seem: an agent can’t bypass your required() and other validators just because it&#39;s calling the form programmatically instead of clicking through it.</p><h3>Testing the logic behind a WebMCP tool</h3><p>You don’t need anything WebMCP-specific to test this — the execute function of a tool is just a function, and the interesting behavior almost always lives in the service it delegates to. Test that directly.</p><pre>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>describe(&#39;UserService list()&#39;, () =&gt; {<br>  it(&#39;returns only users matching the requested status&#39;, () =&gt; {<br>    TestBed.configureTestingModule({<br>      providers: [UserService],<br>    });<br>    const service = TestBed.inject(UserService);<br>    const admins = service.list(&#39;ADMINS&#39;);<br>    expect(admins.every((user) =&gt; user.status === &#39;ADMINS&#39;)).toBe(true);<br>  });<br>});</pre><p>For the Signal Forms version, the thing actually worth testing is that the form’s own validation still runs correctly — since that’s exactly what protects you when an agent submits the form instead of a person.</p><pre>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { UserCreation } from &#39;./user-creation&#39;;<br><br>describe(&#39;UserCreation form&#39;, () =&gt; {<br>  it(&#39;is invalid when required fields are empty&#39;, () =&gt; {<br>    const fixture = TestBed.createComponent(UserCreation);<br>    fixture.detectChanges();<br>    const formState = fixture.componentInstance[&#39;userForm&#39;]();<br>    expect(formState.invalid()).toBe(true);<br>  });<br>  it(&#39;is valid once name and email are filled in&#39;, () =&gt; {<br>    const fixture = TestBed.createComponent(UserCreation);<br>    const component = fixture.componentInstance;<br>    component[&#39;model&#39;].set({ name: &#39;Ada Lovelace&#39;, email: &#39;ada@example.com&#39; });<br>    fixture.detectChanges();<br>    const formState = component[&#39;userForm&#39;]();<br>    expect(formState.invalid()).toBe(false);<br>  });<br>});</pre><p>Neither test touches WebMCP directly, and that’s deliberate — the tool declaration is just a thin wrapper around logic you should already be testing regardless of whether an agent or a person is the one triggering it.</p><h3>Bonus tips</h3><ul><li><strong>Treat experimental APIs as exactly that.</strong> declareExperimentalWebMcpTool, provideExperimentalWebMcpTool, and provideExperimentalWebMcpForms all carry the experimental naming for a reason — expect the shape of these APIs to shift before they stabilize, and avoid building critical functionality on top of them just yet.</li><li><strong>Scope tools to the narrowest lifecycle that makes sense.</strong> A component-level tool that’s cleaned up automatically on destroy is usually safer than an app-wide one that stays registered for the entire session.</li><li><strong>Pair route-level providers with </strong><strong>withExperimentalAutoCleanupInjectors.</strong> If you&#39;re registering WebMCP tools through route-scoped providers, this router feature ensures the tools — and everything else in that environment injector — are actually torn down when the user navigates away, rather than lingering.</li><li><strong>Read-only tools are the lower-risk place to start.</strong> Exposing a “list” or “search” capability carries a lot less downside than exposing something that mutates data, especially while the surrounding security model for WebMCP is still taking shape.</li><li><strong>The Agent Skills package is worth adopting even if you have no interest in WebMCP.</strong> It’s the part of this release most likely to quietly improve your day-to-day experience, since it changes what your coding agent produces by default, not just what your production app can do.</li></ul><h3>Recap</h3><p>Angular 22’s AI story splits cleanly into two halves once you look past the shared label: Agent Skills and the CLI’s MCP server make coding agents better at building and debugging your app, while WebMCP is about your running app exposing capabilities an agent can call directly. The first half is low-risk and immediately useful — install the skills package and your agent’s output quietly gets better. The second half is early, genuinely experimental, and worth understanding now specifically so you’re not starting from zero once it stabilizes.</p><p>If you’re curious where this goes next, keep an eye on how the WebMCP standard itself matures outside of Angular — the framework APIs here are clearly built to track it closely, which means they’ll likely keep changing until the underlying browser proposal settles down.</p><p><strong>What did you think?</strong><br> Did this approach match how you are solving it, or do you have a different take? Drop a comment — I genuinely read every single one.</p><p><strong>Found this helpful?</strong><br> If this saved you even a few minutes of debugging or confusion, hit that clap button so others can find it too. It really does make a difference.</p><p><strong>Want more tips like this?</strong><br> I share one practical dev insight every week. Follow me here on Medium or subscribe to my newsletter so you never miss one.</p><p>Let us connect — find me on LinkedIn or GitHub and let us keep the conversation going.</p><h3>Follow Me for More Angular &amp; Frontend Goodness:</h3><p>I regularly share hands-on tutorials, clean code tips, scalable frontend architecture, and real-world problem-solving guides.</p><ul><li>💼 <a href="https://www.linkedin.com/in/errajatmalik/"><strong>LinkedIn</strong></a> — Let’s connect professionally</li><li>🎥 <a href="https://www.threads.net/@er.rajatmalik"><strong>Threads</strong></a> — Short-form frontend insights</li><li>🐦 <a href="https://twitter.com/er_rajatmalik"><strong>X (Twitter)</strong></a> — Developer banter + code snippets</li><li>👥 <a href="http://devrajat.bsky.social/"><strong>BlueSky</strong></a> — Stay up to date on frontend trends</li><li>🌟 <a href="https://github.com/malikrajat"><strong>GitHub Projects</strong></a> — Explore code in action</li><li>🌐 <a href="https://malikrajat.github.io/"><strong>Website</strong></a> — Everything in one place</li><li>📚 <a href="https://medium.com/@codewithrajat/"><strong>Medium Blog</strong></a> — Long-form content and deep-dives</li><li>💬 <a href="https://dev.to/codewithrajat"><strong>Dev Blog</strong></a> — Free Long-form content and deep-dives</li><li>✉️ <a href="https://codewithrajat.substack.com/"><strong>Substack</strong></a> — Weekly frontend stories &amp; curated resources</li><li>🧩 <a href="https://rajatmalik.dev/"><strong>Portfolio</strong></a> — Projects, talks, and recognitions</li><li>✍️ <a href="https://hashnode.com/@codeswithrajat"><strong>Hashnode</strong></a> — Developer blog posts &amp; tech discussions</li><li>✍️ <a href="https://www.reddit.com/user/codewithrajat/submitted/">Reddit</a> — Developer blog posts &amp; tech discussions</li></ul><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875fc0bfca8e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/angular-is-preparing-for-ai-agents-webmcp-mcp-tooling-and-agent-skills-in-angular-22-what-875fc0bfca8e">Angular Is Preparing for AI Agents: WebMCP, MCP Tooling, and Agent Skills in Angular 22 — — What…</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>