<?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 Faisal Mujtaba on Medium]]></title>
        <description><![CDATA[Stories by Faisal Mujtaba on Medium]]></description>
        <link>https://medium.com/@faisalmujtaba?source=rss-196f4d4e1b79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rpv2ha4FbKQhAHXQ</url>
            <title>Stories by Faisal Mujtaba on Medium</title>
            <link>https://medium.com/@faisalmujtaba?source=rss-196f4d4e1b79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:15:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@faisalmujtaba/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[I Tabbed Through My Own Editor Toolbar and Felt Embarrassed]]></title>
            <link>https://medium.com/@faisalmujtaba/i-tabbed-through-my-own-editor-toolbar-and-felt-embarrassed-1ae7aabcefbb?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae7aabcefbb</guid>
            <category><![CDATA[tiptap]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 04:54:44 GMT</pubDate>
            <atom:updated>2026-11-20T04:54:44.927Z</atom:updated>
            <content:encoded><![CDATA[<p>A keyboard pass found four bugs in our Tiptap toolbar. Vercel’s new UI SDK fixed them, with a few beta caveats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69kn5ht7tmfOJsE1K5qX3w.jpeg" /></figure><p>I unplugged my mouse on a Tuesday afternoon, opened our document editor, and pressed Tab. I wanted to know how far I could get with just a keyboard.</p><p>I got as far as the toolbar, and then I kept pressing Tab. And pressing it. Bold, Italic, Bulleted list, Numbered list, Undo, Redo, Link. Seven presses before the caret finally landed in the document. I run a collaborative editor built on React, Next.js and Tiptap, with comments and realtime editing, and I had never once tested the toolbar without a mouse.</p><p>That was the first of four problems. This post walks through all of them and the rebuild I did with Vercel’s UI SDK, which was announced on 12 November 2026. It is in beta, so I’ll be upfront about what that means near the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nK8ixIIqELzdDDdbXedVTg.jpeg" /></figure><h3>The four things the keyboard pass found</h3><p>Here is the honest list, in the order I found them.</p><p><strong>Every button was its own Tab stop.</strong> A keyboard user had to tab through the entire toolbar just to reach the document. Do that on every page load and it stops being an inconvenience and becomes a reason to leave.</p><p><strong>Bold and Italic “active” state was only a CSS class.</strong> Sighted users saw a highlighted button. Screen reader users got nothing, because there was no aria-pressed. The button looked pressed to me and was silent to everyone else.</p><p><strong>Undo and Redo used the native disabled attribute.</strong> That removes a button from the focus order entirely. A keyboard user could not even discover that Undo existed, because focus skipped right over it while it was disabled.</p><p><strong>The Link popover dropped focus on close.</strong> You’d open it, type a URL, hit Save, and focus fell to &lt;body&gt;. The caret in the editor was gone. You had to find your place in the document again.</p><p>None of these are exotic. They are the default result of writing &lt;button onClick={...}&gt; seven times and moving on.</p><p>Here is roughly what the old toolbar looked like:</p><pre>// components/EditorToolbar.tsx (before)<br>export function EditorToolbar({ editor }: { editor: Editor }) {<br>  return (<br>    &lt;div className=&quot;toolbar&quot;&gt;<br>      &lt;button<br>        className={editor.isActive(&quot;bold&quot;) ? &quot;active&quot; : &quot;&quot;}<br>        onClick={() =&gt; editor.chain().focus().toggleBold().run()}<br>      &gt;<br>        B<br>      &lt;/button&gt;<br>      &lt;button<br>        disabled={!editor.can().undo()}<br>        onClick={() =&gt; editor.chain().focus().undo().run()}<br>      &gt;<br>        Undo<br>      &lt;/button&gt;<br>      {/* ...five more buttons just like these */}<br>    &lt;/div&gt;<br>  )<br>}<br></pre><p>Look at it for a second. The “active” state is a class name. The disabled state is the native attribute. Every button is a normal tab stop. The code is simple and it is wrong in all four ways.</p><h3>I had already fixed this once, and it rotted</h3><p>I should admit something. I had hand-rolled roving-tabindex code for this toolbar before. It worked for a while.</p><p>Then someone added a button. Someone else wrapped a few buttons in a group for layout. A popover trigger got added that didn’t register with the arrow-key logic. Within a couple of months the roving focus was half-working, and nobody wanted to touch it because nobody remembered how it fit together.</p><p>That experience shaped how I looked at this problem the second time. I did not want to own the focus-management code again. I wanted to own the markup and the styles, and borrow the behavior.</p><h3>What UI SDK actually is</h3><p>UI SDK is a library of headless UI behaviors, things like createRovingFocus, createTypeahead and createPopup, more than 50 of them. On top of those sit more than 50 unstyled components. It comes from the shadcn and Vercel Labs team, and the packages are @ui-sdk/core and @ui-sdk/react. I used version 0.1.0-beta.13.</p><p>Setup is short:</p><pre>npm install @ui-sdk/react @ui-sdk/core</pre><p>@ui-sdk/core is a peer dependency, so you install both. You need React 19 or newer, and if you use TypeScript you need @types/react 19.2.10 or newer. Each component has its own entry point, and there is no root import. So you import from @ui-sdk/react/toolbar, @ui-sdk/react/toggle and so on. In Next.js these go inside &quot;use client&quot; components.</p><p>The components ship unstyled. If you want a starting point, there is an optional stylesheet at @ui-sdk/core/web.css. I’ll come back to styling in the pitfalls.</p><p>I only needed three components: Toolbar, Toggle and Popover. Each one maps to one of my problems.</p><h3>Problem one: a single Tab stop</h3><p>Toolbar is the piece that fixes the “seven Tab presses” problem. It gives the whole toolbar one tab stop. Once focus is inside, Left and Right arrows move between items, and Home and End jump to the ends. If you want a vertical toolbar, orientation=&quot;vertical&quot; switches to Up and Down.</p><p>The part I liked is what I did not have to wire up. Toggles and ToggleGroups placed inside a Toolbar join its arrow-key navigation on their own. For menu, select and popover triggers, you render them through ToolbarButton, like &lt;ToolbarButton render={&lt;PopoverTrigger /&gt;}&gt;. That is the exact spot where my old hand-rolled code had rotted, and here it is a documented pattern.</p><p>Two small rules: give the toolbar an aria-label, and give every icon-only control its own aria-label. The toolbar gets role=&quot;toolbar&quot;, and a name like “Formatting” tells screen reader users what they just landed on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pa5ISUstqZ56zAeUhEOU0w.jpeg" /></figure><h3>Problem two: pressed state that screen readers can hear</h3><p>This is where I want to slow down, because the pattern matters more than the component.</p><p>Toggle renders a button, handles Enter and Space, and sets aria-pressed along with a data-pressed attribute you can style. That alone fixes the silent-highlight problem. But how you feed it state is the important decision.</p><p>I used the controlled form: pressed plus onPressedChange. One thing to understand is that the component only requests the next value. It does not own it. If you keep passing the old pressed value, the toggle stays where it was.</p><p>For an editor, that is exactly what you want. Tiptap is the source of truth. Whether text is bold is a fact about the document and the current selection, not a fact about a button. So pressed comes from editor.isActive(&quot;bold&quot;), and onPressedChange just runs the command. It never tries to track state itself.</p><p>The payoff is that the toggle stays correct when the selection moves, when you press Cmd+B instead of clicking, or when a collaborator’s change lands. There is no second copy of the state to drift out of sync. That is the failure mode the CSS-class version quietly had.</p><p>One more rule: keep the accessible label stable. The label stays “Bold”. The state lives in aria-pressed. If you change the label to “Bold on” and “Bold off”, screen readers announce something confusing on top of the pressed state.</p><p>Here is the core of the new toolbar:</p><pre>// components/EditorToolbar.tsx<br>&quot;use client&quot;<br>import { useState } from &quot;react&quot;<br>import { useEditorState, type Editor } from &quot;@tiptap/react&quot;<br>import { Toggle, ToggleGroup } from &quot;@ui-sdk/react/toggle&quot;<br>import { Toolbar, ToolbarButton, ToolbarGroup, ToolbarSeparator } from &quot;@ui-sdk/react/toolbar&quot;<br>import { Popover, PopoverClose, PopoverContent, PopoverTitle, PopoverTrigger } from &quot;@ui-sdk/react/popover&quot;<br><br>export function EditorToolbar({ editor }: { editor: Editor }) {<br>  const state = useEditorState({<br>    editor,<br>    selector: ({ editor }) =&gt; ({<br>      bold: editor.isActive(&quot;bold&quot;),<br>      italic: editor.isActive(&quot;italic&quot;),<br>      list: editor.isActive(&quot;bulletList&quot;) ? [&quot;bullet&quot;] : editor.isActive(&quot;orderedList&quot;) ? [&quot;ordered&quot;] : [],<br>      canUndo: editor.can().undo(),<br>      canRedo: editor.can().redo(),<br>      href: (editor.getAttributes(&quot;link&quot;).href as string | undefined) ?? &quot;&quot;,<br>    }),<br>  })<br>  const [href, setHref] = useState(&quot;&quot;)<br>  return (<br>    &lt;Toolbar aria-label=&quot;Formatting&quot;&gt;<br>      &lt;Toggle aria-label=&quot;Bold&quot; pressed={state.bold} onPressedChange={() =&gt; editor.chain().focus().toggleBold().run()}&gt;B&lt;/Toggle&gt;<br>      &lt;Toggle aria-label=&quot;Italic&quot; pressed={state.italic} onPressedChange={() =&gt; editor.chain().focus().toggleItalic().run()}&gt;I&lt;/Toggle&gt;<br>      &lt;ToolbarSeparator /&gt;<br>      {/* list group, history group and link popover follow below */}<br>    &lt;/Toolbar&gt;<br>  )<br>}</pre><p>Notice useEditorState. I’ll explain why I used it instead of calling editor.isActive directly in render when we get to the pitfalls.</p><h3>Lists: a ToggleGroup with a twist</h3><p>Bulleted and numbered lists are mutually exclusive, so they are a ToggleGroup. The value of a ToggleGroup is always an array of strings, and each Toggle inside gets a value prop. deselectable={false} would keep one item pressed at all times, but I left it off because “no list” is a valid state.</p><pre>// components/EditorToolbar.tsx (list group)<br>&lt;ToggleGroup<br>  aria-label=&quot;List&quot;<br>  value={state.list}<br>  onValueChange={([value]) =&gt; {<br>    if (value === &quot;bullet&quot;) editor.chain().focus().toggleBulletList().run()<br>    else if (value === &quot;ordered&quot;) editor.chain().focus().toggleOrderedList().run()<br>    else editor.chain().focus().liftListItem(&quot;listItem&quot;).run()<br>  }}<br>&gt;<br>  &lt;Toggle value=&quot;bullet&quot; aria-label=&quot;Bulleted list&quot;&gt;•&lt;/Toggle&gt;<br>  &lt;Toggle value=&quot;ordered&quot; aria-label=&quot;Numbered list&quot;&gt;1.&lt;/Toggle&gt;<br>&lt;/ToggleGroup&gt;</pre><p>Same idea as Bold: the value is derived from the editor, and the callback only runs a command. When the array comes back empty, it means “nothing pressed,” and I lift the item out of the list.</p><h3>Problem three: Undo and Redo you can actually find</h3><p>This one was the quiet embarrassment. A native disabled button is removed from the tab order. For a mouse user that is fine, the button is just grayed out. For a keyboard user, it means the control does not exist.</p><p>A disabled ToolbarButton behaves differently. It stays focusable, gets aria-disabled, and ignores presses. A keyboard or screen reader user arrowing through the toolbar lands on Undo, hears that it is unavailable, and moves on. They now know the feature exists.</p><pre>// components/EditorToolbar.tsx (history group)<br>&lt;ToolbarGroup aria-label=&quot;History&quot;&gt;<br>  &lt;ToolbarButton aria-label=&quot;Undo&quot; disabled={!state.canUndo} onClick={() =&gt; editor.chain().focus().undo().run()}&gt;Undo&lt;/ToolbarButton&gt;<br>  &lt;ToolbarButton aria-label=&quot;Redo&quot; disabled={!state.canRedo} onClick={() =&gt; editor.chain().focus().redo().run()}&gt;Redo&lt;/ToolbarButton&gt;<br>&lt;/ToolbarGroup&gt;</pre><p>It looks like the same disabled prop I had before, and the behavior underneath is different. If you do want a disabled item skipped entirely, focusableWhenDisabled={false} does that. I would only reach for it when the action is truly irrelevant, not just temporarily unavailable.</p><h3>Problem four: the caret that fell on the floor</h3><p>The Link popover was the bug that annoyed me most, because it made the editor feel broken. You finish typing a URL, press Save, and your place in the document is gone.</p><p>PopoverContent has initialFocus and finalFocus props. finalFocus accepts &quot;trigger&quot;, &quot;none&quot;, a selector string, an HTMLElement, or a function that returns one. I passed a function that returns the editable element:</p><pre>// components/EditorToolbar.tsx (link popover)<br>&lt;Popover onOpenChange={(open) =&gt; { if (open) setHref(state.href) }}&gt;<br>  &lt;ToolbarButton render={&lt;PopoverTrigger /&gt;} aria-label=&quot;Link&quot;&gt;Link&lt;/ToolbarButton&gt;<br>  &lt;PopoverContent finalFocus={() =&gt; editor.view.dom as HTMLElement}&gt;<br>    &lt;PopoverTitle&gt;Link&lt;/PopoverTitle&gt;<br>    &lt;input aria-label=&quot;URL&quot; value={href} onChange={(e) =&gt; setHref(e.target.value)} /&gt;<br>    &lt;PopoverClose onClick={() =&gt; editor.chain().focus().extendMarkRange(&quot;link&quot;).setLink({ href }).run()}&gt;Save&lt;/PopoverClose&gt;<br>  &lt;/PopoverContent&gt;<br>&lt;/Popover&gt;</pre><p>editor.view.dom is the editable element, so when the popover closes, focus goes straight back to the document. Escape and outside click both close the popover, and both return focus there too. I seed the input from the current link with onOpenChange, so editing an existing link starts with its URL filled in.</p><p>If you need finer control over closing, onOpenChange receives details, and details.reason can be something like &quot;outside-press&quot;. Calling details.cancel() keeps the popover open.</p><h3>A bonus I did not expect: letting an AI assistant press the buttons</h3><p>I did not go looking for this, but it turned out to be relevant to us. We have an in-app AI assistant, and I wanted it to be able to apply formatting without being able to do anything else.</p><p>UI SDK has an agent module for this. You create an agent with an allow function that decides, step by step, whether an action is permitted:</p><pre>// agent.ts<br>import { createAgent } from &quot;@ui-sdk/react/agent&quot;<br><br>export const agent = createAgent({<br>  allow: (step) =&gt; {<br>    if (step.confirm) return false<br>    return step.component === &quot;toggle&quot; &amp;&amp; step.action === &quot;setPressed&quot; &amp;&amp; [&quot;Bold&quot;, &quot;Italic&quot;].includes(step.label ?? &quot;&quot;)<br>  },<br>})<br>// later: await agent.act({ steps: [{ ref: &quot;Bold&quot;, action: &quot;setPressed&quot;, args: [true] }] })</pre><p>My rule is blunt: the assistant may press the Bold and Italic toggles, and nothing else. The first line matters. If a step requires confirmation, the allow function refuses it, so the assistant can never skip a human check.</p><p>Agent changes go through the same onPressedChange and onValueChange callbacks, with details.source === &quot;agent&quot;. That is another reason the controlled pattern pays off, because there is one code path no matter who pressed the button. You can mark an element with data-agent-confirm to make an action wait for a person, and data-agent-hidden hides a region from the agent. For wiring to a model, agentTools gives you JSON-schema tool definitions.</p><h3>The pitfalls I would warn you about</h3><p><strong>It is a beta.</strong> I used 0.1.0-beta.13. Pin the exact version in your package.json, not a caret range. APIs can move, and a toolbar is not where you want surprises.</p><p><strong>Nothing is styled.</strong> Components are unstyled, so your pressed state will be invisible until you style [data-pressed] (or the data-slot attributes) yourself. Or import @ui-sdk/core/web.css for starter styles. I forgot this on my first run and thought Toggle was broken.</p><p><strong>Use useEditorState, not editor.isActive in render.</strong> Calling editor.isActive directly in render either re-renders on every transaction or gives you stale state, depending on how you set things up. The selector approach subscribes to just what the toolbar needs.</p><p><strong>Always call .focus() in the chain.</strong> Without it, clicking Bold moves focus to the toolbar button and your caret is gone. It is the same kind of bug as the Link popover, just quieter.</p><p><strong>Do not use native disabled for actions people should discover.</strong> I said it above and I’ll say it again, because it is the easiest one to reintroduce.</p><p><strong>Keep aria-labels stable.</strong> State belongs in aria-pressed.</p><p><strong>Next.js needs two things.</strong> Put the toolbar in a &quot;use client&quot; component, and create the editor with useEditor({ extensions: [StarterKit], immediatelyRender: false }) to avoid hydration mismatches.</p><p><strong>Check step.confirm in your agent’s allow.</strong> An allow function that forgets this defeats the confirmation feature.</p><h3>How I tested it</h3><p>No tooling here, just a keyboard and a screen reader.</p><p>I tabbed once into the toolbar and confirmed the next Tab went to the document, not another button. I used the arrow keys to move across items, including Undo and Redo when they were unavailable. I pressed Space on Bold and Italic and watched the state flip. I opened the Link popover, typed a URL, pressed Escape, and confirmed the caret was back in the editor. Then I did it again with Save.</p><p>Then I turned VoiceOver on and checked that the toggles reported their pressed state and that Undo read as unavailable instead of vanishing. Screen readers vary, so I would not trust my notes over your own test run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9g-04MUTTDJi2bLiAdwM-w.jpeg" /></figure><h3>When I would use it, and when I would not</h3><p>If you own your markup and styles, UI SDK fits well. Editor and canvas toolbars are a natural home, because they are dense, keyboard-heavy and rarely look like a stock component library. It is also appealing if you want UI that an agent can operate under rules you set.</p><p>If you already use Radix or React Aria and it is working, I would not rip it out. A rebuild is real work, and you would be trading a stable library for a beta. The accessibility problems I found were mine, not Radix’s.</p><p>For me, the deciding factor was avoiding my own rotted roving-tabindex code. I got a documented pattern for focus, pressed state and popover return focus, and I kept control of the markup.</p><p>It is beta, so pin the version, run your own keyboard pass, and do it before a user does it for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae7aabcefbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The useEffect That Threw Halfway and Left a Ghost in Our Document]]></title>
            <link>https://medium.com/@faisalmujtaba/the-useeffect-that-threw-halfway-and-left-a-ghost-in-our-document-c73847d56871?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/c73847d56871</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 04:26:02 GMT</pubDate>
            <atom:updated>2026-11-18T04:26:02.729Z</atom:updated>
            <content:encoded><![CDATA[<p>The useEffect That Threw Halfway and Left a Ghost in Our Document</p><p>How DisposableStack fixed the one cleanup bug I kept reintroducing in a realtime React app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGLGU5XTMsfhHxx_" /></figure><p>A few weeks ago a teammate sent me a screenshot of a document with two copies of her own avatar in the presence bar. One of them never blinked, never moved its cursor, and refused to leave. Reloading the page made it vanish. Of course it did.</p><p>I checked the server logs next. One browser tab, two live connections for the same user and the same document. The second connection wasn’t a stray tab or a reconnect. It was a socket our own code had opened and then forgot about.</p><p>I build a collaborative document app in React and Next.js: Tiptap for the editor, Yjs with Hocuspocus for realtime, a comments sidebar, presence avatars. The ghost was ours, and it took me longer than I’d like to admit to see why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GszbzdS5eyvLZxH5" /></figure><h3>Why the cleanup never ran</h3><p>Here is the effect that wires up collaboration on the document page, trimmed but faithful to the original.</p><pre>// components/DocumentCollab.tsx<br>useEffect(() =&gt; {<br>  const provider = new HocuspocusProvider({ url, name: docId, document: ydoc });<br> <br>  const onPresence = () =&gt; setPeers(readPeers(provider));<br>  provider.awareness.on(&#39;change&#39;, onPresence);<br> <br>  const onOnline = () =&gt; setOnline(true);<br>  window.addEventListener(&#39;online&#39;, onOnline);<br> <br>  const observer = new ResizeObserver(() =&gt; syncEditorHeight(editorEl));<br>  observer.observe(editorEl);<br> <br>  const controller = new AbortController();<br>  loadThreads(docId, controller.signal).then(setThreads).catch(ignoreAbort);<br> <br>  const saved = localStorage.getItem(`draft:${docId}`);<br>  if (saved) restoreDraft(JSON.parse(saved)); // can throw<br> <br>  return () =&gt; {<br>    controller.abort();<br>    observer.disconnect();<br>    window.removeEventListener(&#39;online&#39;, onOnline);<br>    provider.awareness.off(&#39;change&#39;, onPresence);<br>    provider.destroy();<br>  };<br>}, [docId, ydoc, url, editorEl]);</pre><p>Five things get created, and five things get torn down by hand, in reverse. That alone is a maintenance tax. Twice, someone (once me) added a new resource to the setup half and forgot the matching line in the cleanup half. Code review missed it both times because the two halves sit twenty lines apart.</p><p>But the ghost came from somewhere nastier. See the JSON.parse(saved) line near the bottom? One user had a locally saved draft that got corrupted. JSON.parse threw. By then the provider was connected, the awareness listener was attached, the observer was observing.</p><p>An effect that throws never returns its cleanup function. React gets nothing back, so it has nothing to call. The socket stayed open, the awareness state stayed published, and the next successful mount created a second provider for the same user. Hence the ghost, until a full reload killed the old socket.</p><p>Strict Mode in dev actually made this easy to reproduce. It mounts, cleans up, and mounts again, so a throwing effect leaves one orphan right in front of you. I had seen duplicate avatars in dev before and written them off as a Strict Mode quirk. They weren’t. Strict Mode was telling me the truth and I wasn’t listening.</p><h3>What Safari 27.3 changed</h3><p>Explicit Resource Management is the proposal behind using, await using, DisposableStack, AsyncDisposableStack and SuppressedError. Chrome 134, Firefox 141, Node.js 24 and Deno 2.2.10 already ship it. This week Safari 27.3 beta adds it, which makes it the last major engine to get there.</p><p>That was my push. I’d been meaning to fix this effect properly, and “every engine will have this soon” is a decent reason to look at a feature you’ve been ignoring.</p><p>The idea is small. A DisposableStack is a collection of cleanup callbacks. You register things as you create them, and stack.dispose() runs the callbacks in reverse registration order. Disposing twice is a no-op. And using stack = new DisposableStack() disposes the stack automatically when the enclosing block exits, including when it exits by throwing.</p><p>That last sentence is the whole fix. The block exits by throwing, and the cleanup runs anyway.</p><p>The three methods I use:</p><ul><li>stack.defer(fn) registers a plain callback.</li><li>stack.adopt(value, (v) =&gt; cleanup(v)) registers a value that has no Symbol.dispose and returns the value, so you can create and register in one expression.</li><li>stack.use(value) only accepts objects with a [Symbol.dispose]() method and throws a TypeError otherwise.</li></ul><p>HocuspocusProvider, ResizeObserver and AbortController don&#39;t implement Symbol.dispose, so for my case it&#39;s adopt and defer all the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RU5qMFW8eL253opx" /></figure><h3>Fix 1: the same effect with a stack</h3><p>Here is the same effect, rewritten.</p><pre>// components/DocumentCollab.tsx<br>useEffect(() =&gt; {<br>  using stack = new DisposableStack();<br> <br>  const provider = stack.adopt(<br>    new HocuspocusProvider({ url, name: docId, document: ydoc }),<br>    (p) =&gt; p.destroy(),<br>  );<br> <br>  const onPresence = () =&gt; setPeers(readPeers(provider));<br>  provider.awareness.on(&#39;change&#39;, onPresence);<br>  stack.defer(() =&gt; provider.awareness.off(&#39;change&#39;, onPresence));<br> <br>  const onOnline = () =&gt; setOnline(true);<br>  window.addEventListener(&#39;online&#39;, onOnline);<br>  stack.defer(() =&gt; window.removeEventListener(&#39;online&#39;, onOnline));<br> <br>  const observer = stack.adopt(<br>    new ResizeObserver(() =&gt; syncEditorHeight(editorEl)),<br>    (o) =&gt; o.disconnect(),<br>  );<br>  observer.observe(editorEl);<br> <br>  const saved = localStorage.getItem(`draft:${docId}`);<br>  if (saved) restoreDraft(JSON.parse(saved)); // may throw, stack still disposes<br> <br>  const cleanup = stack.move();<br>  return () =&gt; cleanup.dispose();<br>}, [docId, ydoc, url, editorEl]);</pre><p>Each cleanup now sits right next to the line that creates the thing. That alone would have prevented the two forgotten-cleanup bugs.</p><p>The important part is the last two lines. stack.move() returns a new DisposableStack holding all the registered disposers, and marks the original as disposed without running anything. So there are two outcomes:</p><ul><li>If anything throws before move(), the using declaration disposes everything registered so far, in reverse. No orphaned socket, no ghost.</li><li>If setup finishes, ownership moves out to cleanup, and React&#39;s cleanup function disposes it on unmount or when deps change.</li></ul><p>I left the comments fetch out of this snippet on purpose. It gets its own treatment below.</p><h3>Fix 2: a tiny hook so nobody has to remember</h3><p>The using plus move() dance is easy to get subtly wrong, and I didn&#39;t want every effect in the codebase to carry it. So I pulled it into one small hook.</p><pre>// hooks/useDisposableEffect.ts<br>import { useEffect, type DependencyList } from &#39;react&#39;;<br> <br>export function runSetup(setup: (stack: DisposableStack) =&gt; void): () =&gt; void {<br>  using stack = new DisposableStack();<br>  setup(stack);<br>  const cleanup = stack.move();<br>  return () =&gt; cleanup.dispose();<br>}<br> <br>export function useDisposableEffect(<br>  setup: (stack: DisposableStack) =&gt; void,<br>  deps: DependencyList,<br>) {<br>  // eslint-disable-next-line react-hooks/exhaustive-deps<br>  useEffect(() =&gt; runSetup(setup), deps);<br>}</pre><p>runSetup is exported separately so I can test it without React, which matters in a minute. The disable comment is there because the rule can&#39;t see through a deps parameter inside the hook itself. At call sites, though, I still want deps checked, so I added the hook to the rule&#39;s additionalHooks option:</p><pre>// eslint.config.js (rules excerpt)<br>&#39;react-hooks/exhaustive-deps&#39;: [&#39;warn&#39;, {<br>  additionalHooks: &#39;(useDisposableEffect)&#39;,<br>}],</pre><p>The rule treats the first argument as the callback and the second as the dependency array, which happens to match the shape of useDisposableEffect. Now the document page looks like this:</p><pre>// components/DocumentCollab.tsx<br>useDisposableEffect((stack) =&gt; {<br>  const provider = stack.adopt(<br>    new HocuspocusProvider({ url, name: docId, document: ydoc }),<br>    (p) =&gt; p.destroy(),<br>  );<br> <br>  const onPresence = () =&gt; setPeers(readPeers(provider));<br>  provider.awareness.on(&#39;change&#39;, onPresence);<br>  stack.defer(() =&gt; provider.awareness.off(&#39;change&#39;, onPresence));<br> <br>  const onOnline = () =&gt; setOnline(true);<br>  window.addEventListener(&#39;online&#39;, onOnline);<br>  stack.defer(() =&gt; window.removeEventListener(&#39;online&#39;, onOnline));<br> <br>  const saved = localStorage.getItem(`draft:${docId}`);<br>  if (saved) restoreDraft(JSON.parse(saved));<br>}, [docId, ydoc, url]);</pre><p>No using, no move(), no return statement. You get a stack and you register things on it. The two lines that caused the bug can&#39;t be forgotten because they aren&#39;t in the call site anymore.</p><h3>Fix 3: the comments fetch and the async trap</h3><p>The comments fetch is where I almost made a new mistake. My first instinct was to make the effect async so I could await the threads. Don&#39;t. A using declaration in an async function disposes when that async function finishes, not when the component unmounts. Everything would be torn down the moment the await chain completed.</p><p>The rule I follow now: keep the effect body synchronous, adopt an AbortController, and hand its signal to the async work.</p><pre>// hooks/useCommentThreads.ts<br>useDisposableEffect((stack) =&gt; {<br>  const controller = stack.adopt(new AbortController(), (c) =&gt; c.abort());<br> <br>  fetch(`/api/documents/${docId}/threads`, { signal: controller.signal })<br>    .then((res) =&gt; res.json())<br>    .then(setThreads)<br>    .catch((err) =&gt; {<br>      if (err.name !== &#39;AbortError&#39;) console.error(err);<br>    });<br>}, [docId, setThreads]);</pre><p>The effect returns immediately. The fetch lives on its own, and when the component unmounts or docId changes, the abort fires and the promise rejects with an AbortError that I ignore on purpose. The async work sits outside the using scope entirely, which is where it belongs.</p><h3>How I tested it</h3><p>I wanted a test that failed against the old effect and passes against the new one. The scenario is exactly the production bug: register some resources, then throw.</p><pre>// hooks/useDisposableEffect.test.ts<br>import { expect, it, vi } from &#39;vitest&#39;;<br>import { runSetup } from &#39;./useDisposableEffect&#39;;<br> <br>it(&#39;disposes everything registered when setup throws&#39;, () =&gt; {<br>  const order: string[] = [];<br>  const first = vi.fn(() =&gt; order.push(&#39;first&#39;));<br>  const second = vi.fn(() =&gt; order.push(&#39;second&#39;));<br> <br>  expect(() =&gt;<br>    runSetup((stack) =&gt; {<br>      stack.defer(first);<br>      stack.defer(second);<br>      throw new Error(&#39;corrupt draft&#39;);<br>    }),<br>  ).toThrow(&#39;corrupt draft&#39;);<br> <br>  expect(first).toHaveBeenCalledTimes(1);<br>  expect(second).toHaveBeenCalledTimes(1);<br>  expect(order).toEqual([&#39;second&#39;, &#39;first&#39;]);<br>});<br> <br>it(&#39;keeps resources alive until the returned cleanup runs&#39;, () =&gt; {<br>  const dispose = vi.fn();<br>  const cleanup = runSetup((stack) =&gt; stack.defer(dispose));<br> <br>  expect(dispose).not.toHaveBeenCalled();<br>  cleanup();<br>  cleanup();<br>  expect(dispose).toHaveBeenCalledTimes(1);<br>});</pre><p>The first test is the ghost avatar in miniature, plus it pins down reverse order. The second test guards against the biggest pitfall (more on that below) and confirms that calling cleanup twice is harmless. This runs on Node 24, which has DisposableStack natively, so no polyfill is needed in the test environment.</p><p>I tested runSetup directly rather than rendering a component because an error thrown inside an effect gets routed through React&#39;s error reporting, and I didn&#39;t want my assertion to depend on that. The wiring from useEffect to runSetup is one line. For that part I rely on Strict Mode in dev, which exercises mount, cleanup, mount on every page load.</p><h3>Setup and compatibility</h3><p>Three things to sort out.</p><p><strong>TypeScript.</strong> using is supported since TypeScript 5.2. Add the disposable lib to tsconfig.json:</p><pre>// tsconfig.json<br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext.disposable&quot;, &quot;es2022&quot;]<br>  }<br>}</pre><p>Using &quot;esnext&quot; in lib also works if you&#39;d rather not list it explicitly.</p><p><strong>Next.js.</strong> The using syntax is compiled by SWC, which downlevels it. That handles the syntax, but it does not create the runtime globals. DisposableStack and Symbol.dispose still have to exist in the browser, and until Safari stable ships them, older Safari versions won&#39;t have them.</p><p><strong>Polyfill.</strong> I use core-js, imported once, early, on the client:</p><pre>// components/Providers.tsx (top of file, a client component near the root)<br>import &#39;core-js/actual/disposable-stack&#39;;<br>import &#39;core-js/actual/symbol/dispose&#39;;</pre><p>If you prefer loading it conditionally, feature-detect with typeof DisposableStack === &#39;function&#39;. Just make sure the polyfill is in place before any effect that uses it runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qkw7iUsu4x6ufUyO" /></figure><h3>Pitfalls I hit or nearly hit</h3><p><strong>Forgetting </strong><strong>move() tears everything down.</strong> This is the big one. If you write using stack = ... in an effect and return () =&gt; stack.dispose() without moving, the stack is disposed the moment the effect function returns. The socket opens and closes right away. I did this once while prototyping and watched a provider connect and immediately die. Always move() before returning. This is also why runSetup exists: the correct shape is written once.</p><p><strong>use() is not </strong><strong>adopt().</strong> stack.use(value) only accepts values with a [Symbol.dispose]() method, and throws a TypeError otherwise (null and undefined are fine). AbortController, ResizeObserver and HocuspocusProvider don&#39;t have that method, so adopt and defer are your tools. adopt also returns the value, which keeps the code tidy.</p><p><strong>Async functions change when disposal happens.</strong> Covered above. Keep the effect body synchronous.</p><p><strong>Disposers can throw.</strong> If one throws, the rest still run. When more than one fails, you get a SuppressedError where .error is the most recent failure and .suppressed is the earlier one. I like this behavior: one bad destroy() can&#39;t strand the other resources.</p><p><strong>Don’t keep the stack in state or a ref.</strong> Create one stack per effect run. A stack that lives across renders is a stack that gets registered into after it’s disposed, and registering after dispose throws a ReferenceError.</p><p><strong>Strict Mode is your friend.</strong> Its mount, cleanup, mount cycle is the cheapest leak detector React gives you. If your presence list shows a duplicate in dev, believe it.</p><p>If you can’t use using syntax in some file, the fallback is plain try/catch:</p><pre>// components/SomeWidget.tsx (no using syntax)<br>useEffect(() =&gt; {<br>  const stack = new DisposableStack();<br>  try {<br>    // register resources on stack...<br>    return () =&gt; stack.dispose();<br>  } catch (e) {<br>    stack.dispose();<br>    throw e;<br>  }<br>}, [deps]);</pre><h3>Where I would use it, and where I wouldn’t</h3><p>I’d reach for this first in two places: effects that create three or more things, and anything that opens a socket or a provider. Those are the effects where a forgotten line or a mid-setup throw costs real money in support tickets and ghost avatars.</p><p>A bonus on the server, briefly. In a Next.js route handler or server action on Node 24, await using with AsyncDisposableStack handles things like a database pool client, and works directly with fs/promises file handles:</p><pre>// app/api/documents/export/route.ts<br>import { open } from &#39;node:fs/promises&#39;;<br>import { tmpdir } from &#39;node:os&#39;;<br>import { join } from &#39;node:path&#39;;<br>import { pool } from &#39;@/lib/db&#39;;<br> <br>export async function POST(req: Request) {<br>  const { docId } = await req.json();<br>  const path = join(tmpdir(), `export-${crypto.randomUUID()}.json`);<br> <br>  await using stack = new AsyncDisposableStack();<br>  const client = stack.adopt(await pool.connect(), (c) =&gt; c.release());<br>  await using file = await open(path, &#39;w&#39;);<br> <br>  const { rows } = await client.query(<br>    &#39;select id, body from comments where doc_id = $1&#39;,<br>    [docId],<br>  );<br>  await file.writeFile(JSON.stringify(rows));<br>  return Response.json({ ok: true });<br>}</pre><p>The file handle implements Symbol.asyncDispose, so await using just works. The client release is adopted. Both clean up on any exit, including errors.</p><p>Where plain return () =&gt; ... is still fine: an effect with one listener and one cleanup line. Wrapping that in a stack is ceremony without payoff. I&#39;m not converting those.</p><p>As for the polyfill, I’ll drop it when Safari stable ships Explicit Resource Management and my own analytics say enough of our users have updated. I’m not going to guess at a number. The dependency is one import in one file, so removing it later is cheap.</p><p>The ghost avatar hasn’t come back. More importantly, the next person who adds a resource to that effect has exactly one place to put it, and the cleanup goes right beside it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c73847d56871" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Finally Deleted Date From Our Due-Date Code, and a California Teammate Was Right All Along]]></title>
            <link>https://medium.com/@faisalmujtaba/i-finally-deleted-date-from-our-due-date-code-and-a-california-teammate-was-right-all-along-6a83e273be4c?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a83e273be4c</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[temporal-api]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 04:31:14 GMT</pubDate>
            <atom:updated>2026-11-13T04:31:14.437Z</atom:updated>
            <content:encoded><![CDATA[<p>Safari 27.3 beta shipping Temporal was the push I needed. Here is the problem-to-fix walkthrough for due dates, comment timestamps, and a snooze button that drifts by an hour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPcNUXGQtQ_lbeCS" /></figure><p>A teammate in California told me, more than once, that her tasks were due a day early. I told her it was probably a cache. It was not a cache.</p><p>She would open our document app, look at a task due on the 13th, and see the 12th. I looked at the same task from India and saw the 13th. Same record, same code, different answer. I only half believed her until I finally sat down and reproduced it.</p><p>This week Safari 27.3 beta added Temporal, the last major engine to do so. I used that as the excuse to rip Date out of our due-date and comment-timestamp code. This post is the walkthrough: three real bugs, the mental model that fixed them, and the pitfalls I hit on the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4VE7uJXdmeI3FB8w" /></figure><h3>The bug that made me believe her</h3><p>We store due dates as plain strings like &quot;2026-11-13&quot;. On the client we did the obvious thing:</p><pre>// components/DueDateBadge.tsx (before)<br>const due = new Date(task.dueDate); // &quot;2026-11-13&quot;<br>return &lt;span&gt;{due.toDateString()}&lt;/span&gt;;</pre><p>Here is the catch. new Date(&quot;2026-11-13&quot;) parses a date-only ISO string as UTC midnight. For anyone west of UTC, local time at that instant is still the previous evening. In America/Los_Angeles, that renders as &quot;Thu Nov 12&quot;. My teammate was not confused. Our code was.</p><p>It gets worse because it only bites some people. I live east of UTC, so it never showed up in my own testing. That is the kind of bug that survives for months.</p><h3>Why Date keeps biting</h3><p>Date is one type doing three different jobs. It can mean a calendar date (&quot;the 13th&quot;, no time, no zone). It can mean an exact moment (&quot;this comment was posted at 04:11 UTC&quot;). And it can mean a local wall-clock time in someone&#39;s zone (&quot;9 AM tomorrow, wherever I am&quot;).</p><p>Those are three different ideas with three different failure modes, and Date quietly converts between them using the machine&#39;s time zone. Our bugs were all the same mistake wearing different clothes.</p><p>The second one showed up as a Next.js hydration warning. We formatted comment timestamps with toLocaleString. On the server that ran in UTC. On the client it ran in the viewer&#39;s zone. Two different strings for the same comment, React complained, and I ignored the warning for longer than I should admit.</p><p>The third was the “Snooze 1 day” button, which did + 86400000 milliseconds. Across a daylight saving change, a day is not 24 hours, so the task landed an hour off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-epX1X53P-NudkYg" /></figure><h3>The mental model</h3><p>Temporal splits that one type into separate ones. I only needed three.</p><p><strong>PlainDate</strong> is for calendar dates. A due date is a PlainDate. It has no time zone, so it cannot shift by a day. That is the whole point.</p><p><strong>Instant</strong> is for “when it happened”. A comment’s created_at is an Instant: one exact moment, the same for everybody on Earth.</p><p><strong>ZonedDateTime</strong> is for display, and I only create it at the edge, in the viewer’s zone. It is an Instant plus a time zone, and it knows about DST.</p><p>The rule I wrote on a sticky note: store PlainDates and Instants, convert to ZonedDateTime only when painting pixels.</p><h3>Setup in a Next.js App Router app</h3><p>Temporal is TC39 Stage 4. Firefox 139 shipped it in May 2025, Chrome and Edge 144 in January 2026, and Node.js 26 in May 2026. Safari stable still does not have it. The 27.3 beta adds Temporal, Date.prototype.toTemporalInstant, and explicit resource management (using, DisposableStack), but it is a beta. Until it reaches stable and your users update, keep a polyfill.</p><pre>npm install temporal-polyfill</pre><p>The package is v1.0.x and about 20 kB. import &#39;temporal-polyfill/global&#39; installs a global Temporal and uses the native one when it exists. If you would rather not touch globals, import { Temporal } from &#39;temporal-polyfill&#39; is a side-effect-free ponyfill that also prefers native.</p><p>My rule for the App Router is simple: import it once before any Temporal call, on both server and client. I made a tiny client module for the browser side:</p><pre>// app/temporal-init.tsx<br>&#39;use client&#39;;<br>import &#39;temporal-polyfill/global&#39;;<br> <br>export default function TemporalInit() {<br>  return null;<br>}</pre><p>Then I render it from the root layout, and import the same package at the top of my server-side date helpers:</p><pre>// app/layout.tsx<br>import TemporalInit from &#39;./temporal-init&#39;;<br> <br>export default function RootLayout({ children }: { children: React.ReactNode }) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;TemporalInit /&gt;<br>        {children}<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>For types, set the lib in tsconfig.json to &quot;esnext&quot; (or &quot;esnext.temporal&quot;). That gets you the global Temporal types without extra packages.</p><h3>Fix 1: due dates with PlainDate</h3><p>The fix is almost boring. Parse the stored string into a PlainDate and never let a time zone near it.</p><pre>// lib/dates.ts<br>import &#39;temporal-polyfill/global&#39;;<br> <br>export function parseDueDate(iso: string): Temporal.PlainDate {<br>  return Temporal.PlainDate.from(iso); // &quot;2026-11-13&quot;<br>}<br> <br>export function formatDueDate(d: Temporal.PlainDate): string {<br>  return d.toLocaleString(&#39;en-US&#39;, { dateStyle: &#39;medium&#39; }); // &quot;Nov 13, 2026&quot;<br>}<br> <br>export function addDays(d: Temporal.PlainDate, n: number) {<br>  return d.add({ days: n }); // 2026-11-13 -&gt; 2026-11-14<br>}</pre><p>Temporal.PlainDate.from(&quot;2026-11-13&quot;).toString() gives back &quot;2026-11-13&quot; for every viewer, in every zone. My California teammate now sees the 13th. I owe her lunch.</p><p>The component got shorter too:</p><pre>// components/DueDateBadge.tsx<br>import { parseDueDate, formatDueDate } from &#39;@/lib/dates&#39;;<br> <br>export function DueDateBadge({ dueDate }: { dueDate: string }) {<br>  return &lt;span&gt;{formatDueDate(parseDueDate(dueDate))}&lt;/span&gt;;<br>}</pre><h3>Fix 2: hydration-safe comment timestamps</h3><p>The server sends the ISO instant string. The comment is stored as an exact moment, for example &quot;2026-11-13T04:11:56Z&quot;. The trick is that both server and client must format it in the same zone.</p><p>Converting that instant to Los Angeles looks like this:</p><pre>Temporal.Instant.from(&#39;2026-11-13T04:11:56Z&#39;)<br>  .toZonedDateTimeISO(&#39;America/Los_Angeles&#39;)<br>  .toString();<br>// &quot;2026-11-12T20:11:56-08:00[America/Los_Angeles]&quot;</pre><p>Notice .toPlainDate() on that result is Nov 12. That is correct: it was still the 12th for her when the comment was posted.</p><p>My main fix uses the user’s saved profile time zone, passed down from the server. Both sides then render the same text, so hydration has nothing to complain about.</p><pre>// components/CommentTime.tsx<br>import &#39;temporal-polyfill/global&#39;;<br> <br>type Props = { createdAt: string; timeZone: string };<br> <br>export function CommentTime({ createdAt, timeZone }: Props) {<br>  const zdt = Temporal.Instant.from(createdAt).toZonedDateTimeISO(timeZone);<br>  const text = zdt.toLocaleString(&#39;en-US&#39;, {<br>    dateStyle: &#39;medium&#39;,<br>    timeStyle: &#39;short&#39;,<br>  }); // &quot;Nov 12, 2026, 8:11 PM&quot;<br> <br>  return &lt;time dateTime={createdAt}&gt;{text}&lt;/time&gt;;<br>}</pre><pre>// app/docs/[id]/page.tsx (excerpt)<br>const profile = await getProfile(); // profile.timeZone, e.g. &quot;America/Los_Angeles&quot;<br>return comments.map((c) =&gt; (<br>  &lt;CommentTime key={c.id} createdAt={c.createdAt} timeZone={profile.timeZone} /&gt;<br>));</pre><p>Two details matter here. First, createdAt is an ISO string, not a Temporal object. Second, ZonedDateTime#toLocaleString does not accept a timeZone option. It already has its own zone, and passing one throws a TypeError. I found that out the hard way.</p><p>What if a user has no saved zone? Then fall back to the viewer’s zone after mount, using Temporal.Now.timeZoneId() in a client component&#39;s effect, and render the neutral ISO value until then. That avoids a mismatch too, at the cost of a brief flash.</p><p>suppressHydrationWarning is a last resort. It hides the warning without fixing the cause, and I only reach for it when I truly cannot control both sides.</p><h3>Fix 3: snooze that survives DST</h3><p>+ 86400000 assumes every day has 24 hours. In New York, March 8, 2026 does not. Here is what ZonedDateTime does with a &quot;one day&quot; snooze:</p><pre>// lib/snooze.ts<br>import &#39;temporal-polyfill/global&#39;;<br> <br>export function snoozeOneDay(isoZoned: string): string {<br>  const zdt = Temporal.ZonedDateTime.from(isoZoned);<br>  return zdt.add({ days: 1 }).toString();<br>}<br> <br>// snoozeOneDay(&quot;2026-03-07T12:00[America/New_York]&quot;)<br>// -&gt; &quot;2026-03-08T12:00:00-04:00[America/New_York]&quot;  (same wall-clock time)<br>//<br>// zdt.add({ hours: 24 }) lands on 13:00 instead.</pre><p>add({ days: 1 }) means &quot;same wall-clock time tomorrow&quot;. add({ hours: 24 }) means &quot;24 elapsed hours&quot;, which across a spring-forward is 13:00. For a snooze button, the first one is what people expect.</p><h3>Fix 4: sorting and “due in N days”</h3><p>Here is the first trap. You cannot compare Temporal objects with &lt; or &gt;. They throw a TypeError (&quot;Cannot use valueOf&quot;), which is a good thing, because silently wrong comparisons are how we got here. And === compares object identity, not value, so two equal PlainDates are not ===.</p><p>Use compare and equals:</p><pre>// lib/tasks.ts<br>import &#39;temporal-polyfill/global&#39;;<br> <br>type Task = { id: string; dueDate: string };<br> <br>export function sortByDue(tasks: Task[]): Task[] {<br>  return [...tasks].sort((a, b) =&gt;<br>    Temporal.PlainDate.compare(<br>      Temporal.PlainDate.from(a.dueDate),<br>      Temporal.PlainDate.from(b.dueDate),<br>    ),<br>  );<br>}<br> <br>export function dueInDays(dueDate: string, from: Temporal.PlainDate): number {<br>  return from.until(Temporal.PlainDate.from(dueDate)).days;<br>}</pre><p>compare returns -1, 0, or 1, which is exactly what Array.prototype.sort wants. And until returns a Duration, so PlainDate 2026-11-13 until 2026-12-01 gives 18 days (.days === 18).</p><p>For “today”, I use the user’s zone rather than the server’s: Temporal.Now.plainDateISO(&quot;Asia/Kolkata&quot;) for someone in India, for example. Temporal.Now.instant() is the current exact moment when you need that.</p><p>During migration, legacy Date values convert with new Date().toTemporalInstant(). That one saved me from rewriting a few older utilities all at once.</p><h3>Pitfalls I actually hit</h3><p>Here is the list I would have wanted before starting.</p><ul><li>&lt; and &gt; throw. Use Temporal.PlainDate.compare(a, b) or a.equals(b). Do not use ===.</li><li>JSON round-trips give strings. JSON.stringify({ d }) produces {&quot;d&quot;:&quot;2026-11-13&quot;}, and parsing gives you a string, not a PlainDate. Store and send ISO strings, and rehydrate with .from() at the edges.</li><li>Do not put Temporal objects into server-to-client props or query caches. Pass ISO strings. It keeps serialization boring and cache keys stable.</li><li>ZonedDateTime#toLocaleString throws a TypeError if you pass a timeZone option. The zone is already on the object.</li><li>Safari 27.3 is a beta. Keep the polyfill, and feature-detect if you want to branch on native support.</li><li>React Native’s Hermes has no Temporal, so RN apps need the polyfill as well.</li></ul><p>The polyfill also ships a tree-shakeable function API (temporal-polyfill/fns/PlainDate and friends) and a codemod. I did not need either for our app, but if bundle size is your concern, look at them before writing your own wrappers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*an7rfdGzfFk1AHZP" /></figure><h3>The order I would migrate in</h3><p>I did not do this in one pull request, and I would not recommend it. Here is the order that worked:</p><ol><li><strong>Due dates first.</strong> This is the user-visible bug and the cleanest conversion. Store ISO strings, parse to PlainDate at the edge.</li><li><strong>Comment timestamps next.</strong> Move to Instant strings plus a profile time zone passed from the server. This clears the hydration warnings.</li><li><strong>Snooze and any “add N days” logic.</strong> Swap millisecond math for ZonedDateTime.add({ days }).</li><li><strong>Sorting and “due in N days”.</strong> Replace ad hoc comparisons with compare and until.</li><li><strong>Everything else, gradually.</strong> Use toTemporalInstant() as a bridge for old code you are not ready to touch.</li></ol><h3>When I would drop the polyfill</h3><p>Not yet. Safari 27.3 is in beta, and it only matters to your users once it reaches stable and they actually update. I would drop the polyfill when Safari 27.3+ stable is the majority of your Safari traffic and Safari is a meaningful share of your total. I cannot give you that number. Check your own analytics, because your audience is not mine.</p><p>Until then, the polyfill costs about 20 kB and uses native Temporal when it is available, so the cost is smaller than the bugs it removed.</p><p>My California teammate has not mentioned a date problem since. I am choosing to read that as a win.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a83e273be4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Comment Saved, the Sidebar Said Otherwise: Upgrading TanStack DB to 1.0 RC]]></title>
            <link>https://medium.com/@faisalmujtaba/the-comment-saved-the-sidebar-said-otherwise-upgrading-tanstack-db-to-1-0-rc-6db536725e2f?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/6db536725e2f</guid>
            <category><![CDATA[tanstack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 04:25:00 GMT</pubDate>
            <atom:updated>2026-11-11T04:25:00.959Z</atom:updated>
            <content:encoded><![CDATA[<p>Resolved comments snapped back to their old state after I upgraded. Nothing threw. Here is what changed and the five fixes that stopped it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M3w7gQA1QXcZW_M2" /></figure><p>The first thing I noticed in staging was a comment that un-resolved itself.</p><p>I clicked Resolve. The comment slid out of the open list, exactly as it should. Half a second later it came back, still open, as if I’d never touched it. I edited another comment’s body and saw the same thing: the new text appeared, then the old text replaced it.</p><p>I refreshed. The edit was there, and so was the resolved flag. The server had them the whole time.</p><p>I wrote about moving our comments sidebar to TanStack DB three weeks ago. That was on 0.9.x, with a Query Collection wrapping our existing queryFn. TanStack DB 1.0 RC1 shipped on 29 Oct 2026, and this post is the upgrade of that same sidebar. Several things broke, but the snap-back is the one that matters.</p><h3>Why this one is sneaky</h3><p>The PATCH succeeded. The transaction settled without an error. The console was clean. If your handlers never returned anything, TypeScript may not complain either.</p><p>It looks like a UI bug, and I spent a few minutes in React DevTools before I thought to look at the handlers. The behavior changed underneath code that didn’t.</p><h3>Installing the RC (and one gotcha)</h3><pre># terminal<br>npm install @tanstack/react-db@rc</pre><p>The adapters are where I’d slow down. @tanstack/query-db-collection and @tanstack/offline-transactions were accidentally released as 1.0 before the RC. They stay on their 1.x line, so update them to the latest 1.x and don&#39;t point them at an RC tag. They use your app&#39;s @tanstack/db as a peer and need ^1.0.0-rc.0, so upgrade everything in one pass.</p><pre># terminal<br>npm install @tanstack/query-db-collection@latest @tanstack/offline-transactions@latest</pre><p>One more dev-time surprise: browser dev builds now throw DuplicateDbInstanceError if two copies of @tanstack/db load. If you see it, dedupe your lockfile.</p><h3>Fix 1: handlers have to synchronize explicitly</h3><p>Here is the rule, plainly. If a Query Collection handler neither refetches nor writes confirmed data, its optimistic changes revert to the previous synced rows when the transaction settles. That holds even when the server accepted the mutation.</p><p>That is exactly what we saw. In 0.x the handler finished and the collection refetched on its own. In the 1.x line of the Query Collection adapter that automatic refetch is gone. The handlers now return Promise&lt;void&gt;, return values are ignored at runtime, and { refetch: false } no longer exists (the types reject it).</p><p>You have two options:</p><ul><li>await collection.utils.refetch(). It&#39;s simple and costs a request.</li><li>await collection.utils.writeUpsert(serverRow), or writeInsert, writeUpdate, writeDelete, with the confirmed server response. No fetch.</li></ul><p>My choice: write the server’s response when the API returns the saved row, which our PATCH and POST do. Refetch only where it doesn’t. Handlers now get collection in their params, so the utils are right there.</p><p>Here is onUpdate before and after:</p><pre>// comments/collection.ts (before, 0.9.x)<br>onUpdate: async ({ transaction }) =&gt; {<br>  const { original, changes } = transaction.mutations[0]<br>  await api.patch(`/comments/${original.id}`, changes)<br>},</pre><pre>// comments/collection.ts (after, 1.0 RC)<br>onUpdate: async ({ transaction, collection }) =&gt; {<br>  const { original, changes } = transaction.mutations[0]<br>  const saved = await api.patch&lt;Comment&gt;(`/comments/${original.id}`, changes)<br>  await collection.utils.writeUpsert(saved)<br>},</pre><p>onInsert and onDelete follow the same pattern:</p><pre>// comments/collection.ts<br>onInsert: async ({ transaction, collection }) =&gt; {<br>  const { modified } = transaction.mutations[0]<br>  const saved = await api.post&lt;Comment&gt;(&#39;/comments&#39;, modified)<br>  await collection.utils.writeUpsert(saved)<br>},<br>onDelete: async ({ transaction, collection }) =&gt; {<br>  const { original } = transaction.mutations[0]<br>  await api.delete(`/comments/${original.id}`)<br>  await collection.utils.writeDelete(original.id)<br>},</pre><p>Our bulk-resolve endpoint returns 204 with no body, so there’s nothing to write. That handler refetches:</p><pre>// comments/collection.ts (bulk resolve, endpoint returns 204)<br>onUpdate: async ({ transaction, collection }) =&gt; {<br>  const ids = transaction.mutations.map((m) =&gt; m.original.id)<br>  await api.post(&#39;/comments/bulk-resolve&#39;, { ids })<br>  await collection.utils.refetch()<br>},</pre><p>Some things to know:</p><ul><li>Direct writes now return promises, and validation errors reject them. For example, writeInsert with an existing key in a persisted collection rejects with DuplicateKeySyncError. Always await them.</li><li>Query’s own polling, focus, reconnect and invalidation still work independently.</li><li>Post-write refetch replacement and error recovery need TanStack Query Core 5.90.15 or later.</li><li>If you use Electric, collection.utils.awaitTxId(txid, 10_000) replaces returning { txid }.</li></ul><p>I’ll be fair about this change. The old auto-refetch quietly spent a request on every mutation. Now the handler says how it synchronizes, and for our API that means fewer requests. The price is that forgetting is silent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AQumDzsWQrb_Q3gD" /></figure><h3>Fix 2: $synced is gone, and its replacement means the opposite</h3><p>We had a small “saving…” dot per comment. The flag behind it is now $hasPendingWrites, and the meaning is inverted: it is true while a pending local optimistic mutation affects the row.</p><pre>// comments/CommentRow.tsx (before)<br>{!comment.$synced &amp;&amp; &lt;SavingDot /&gt;}<br> <br>// comments/CommentRow.tsx (after)<br>{comment.$hasPendingWrites &amp;&amp; &lt;SavingDot /&gt;}</pre><p>Any eq(row.$synced, false) becomes eq(row.$hasPendingWrites, true). If you flip the property and forget to flip the condition, the dot shows on every row that is <em>not</em> saving. I almost shipped that.</p><p>Also, $hasPendingWrites being false does not by itself prove the server confirmed anything. It only says no local optimistic mutation is pending.</p><p>The metadata has to come from somewhere. Names like $hasPendingWrites are reserved, so don&#39;t select a field with that name yourself. Our select spreads the comment row, so the metadata comes from it:</p><pre>// comments/useComments.ts<br>.select(({ comment, user, section }) =&gt; ({<br>  ...comment,<br>  authorName: user.name,<br>  sectionTitle: section.title,<br>}))</pre><p>A structured .select() that returns or spreads a source row retains that row&#39;s metadata. With several source spreads, the last one supplies it. A brand-new object gets the live query&#39;s metadata instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GvgvdxZxex6wOUGS" /></figure><h3>Fix 3: isPersisted.promise becomes when(‘settled’)</h3><p>Our Resolve button used to await transaction.isPersisted.promise before closing the thread. Now:</p><pre>// comments/ResolveButton.tsx<br>const tx = commentsCollection.update(id, (draft) =&gt; {<br>  draft.resolved = true<br>})<br>await tx.when(&#39;settled&#39;)<br>closeThread()</pre><p>when(&#39;settled&#39;) resolves after the handler completes and rejects when the transaction fails or rolls back. It confirms the backend only if the handler waited for that. So this ties straight back to Fix 1: a handler that awaits nothing useful makes settled mean very little.</p><h3>Fix 4: dependency arrays are gone from useLiveQuery</h3><p>This is the compile-time one, and the easy one. The deps array was removed from useLiveQuery, useLiveSuspenseQuery and useLiveInfiniteQuery.</p><pre>// comments/useComments.ts (before)<br>useLiveQuery(<br>  (q) =&gt;<br>    q.from({ comment: commentsCollection })<br>      .join({ user: usersCollection }, /* ... */)<br>      .join({ section: sectionsCollection }, /* ... */)<br>      .where(({ comment }) =&gt; eq(comment.resolved, showResolved))<br>      .orderBy(({ comment }) =&gt; comment.createdAt, &#39;desc&#39;)<br>      .select(/* ... */),<br>  [showResolved]<br>)<br> <br>// comments/useComments.ts (after)<br>useLiveQuery({<br>  query: (q) =&gt;<br>    q.from({ comment: commentsCollection })<br>      .join({ user: usersCollection }, /* ... */)<br>      .join({ section: sectionsCollection }, /* ... */)<br>      .where(({ comment }) =&gt; eq(comment.resolved, showResolved))<br>      .orderBy(({ comment }) =&gt; comment.createdAt, &#39;desc&#39;)<br>      .select(/* ... */),<br>})</pre><p>Structured queries derive their identity from the query itself, captured values like showResolved included, so nothing needs listing.</p><p>Opaque clauses (.fn.where, .fn.select, .fn.having) can&#39;t be inspected. They need an explicit, serializable queryKey that includes the captured values, for example queryKey: [commentsCollection.id, &#39;resolved&#39;, showResolved]. Without a nonempty queryKey (an empty array counts as absent), you get UnhashableQueryIRError.</p><p>Two more changes, which our sidebar doesn’t use. A child query returned directly from .select() now needs include() from @tanstack/db or you get IncludeOperatorRequiredError. A groupBy with no aggregate needs groupKeys(), otherwise GroupingOperatorRequiredError.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qdv6kRNIj9h_wDUE" /></figure><h3>Fix 5: errors got honest</h3><p>isError is gone from the live-query hooks. In its place:</p><ul><li>isLoadingError: the first load failed.</li><li>isCrashed: a local crash. crashed is a new terminal status.</li><li>isSyncError: a problem after rows are ready. The rows stay visible and the status stays &#39;ready&#39;.</li></ul><p>Our old code replaced the whole sidebar with an error screen on any error. One failed background refetch could hide a whole sidebar of perfectly good comments. Now we keep the comments and show a small banner.</p><pre>// comments/CommentsSidebar.tsx<br>const { data, isLoadingError, isCrashed, isSyncError } = useComments(showResolved)<br> <br>if (isLoadingError) {<br>  return &lt;ErrorPanel onRetry={() =&gt; commentsCollection.reload()} /&gt;<br>}<br>if (isCrashed) return &lt;ErrorPanel /&gt;<br> <br>return (<br>  &lt;&gt;<br>    {isSyncError &amp;&amp; (<br>      &lt;StaleBanner onRetry={() =&gt; commentsCollection.utils.refetch({ throwOnError: true })} /&gt;<br>    )}<br>    &lt;CommentList comments={data} /&gt;<br>  &lt;/&gt;<br>)</pre><p>Query Collection’s utils.lastError, isError and errorCount moved to collection.health. clearError() is replaced by collection.reload() for a failed first load, or utils.refetch({ throwOnError: true }) to retry. There is also findProblems(health) from @tanstack/db if you want to inspect the problems yourself.</p><h3>Smaller things I tripped over or checked</h3><ul><li>Joined row keys are now JSON arrays of source keys. Read row.$key instead of building a key to call collection.get().</li><li>getKey must return a string or a number (UndefinedKeyError or InvalidKeyError otherwise).</li><li>cleanup() rejects with CollectionHasSubscribersError while live queries read the collection. cleanup({ dependents: true }) ends them.</li><li>Production error messages now carry a short code and a link, so don’t match on message text.</li></ul><h3>How I checked it</h3><p>I wanted one test that would have caught the snap-back. It updates a comment, waits for the transaction to settle, and asserts the collection still holds the new value.</p><pre>// comments/collection.test.ts<br>import { it, expect, vi } from &#39;vitest&#39;<br>import { api } from &#39;../api&#39;<br>import { commentsCollection } from &#39;./collection&#39;<br> <br>vi.mock(&#39;../api&#39;)<br> <br>it(&#39;keeps the edited body after the transaction settles&#39;, async () =&gt; {<br>  const saved = { id: &#39;c1&#39;, body: &#39;Updated body&#39;, resolved: false }<br>  vi.mocked(api.patch).mockResolvedValue(saved)<br> <br>  // assumes commentsCollection is seeded with c1 and its old body<br>  const tx = commentsCollection.update(&#39;c1&#39;, (draft) =&gt; {<br>    draft.body = &#39;Updated body&#39;<br>  })<br>  await tx.when(&#39;settled&#39;)<br> <br>  expect(commentsCollection.get(&#39;c1&#39;)?.body).toBe(&#39;Updated body&#39;)<br>})</pre><p>On the old handler, this fails. The row reverts to the previous synced value when the transaction settles. With writeUpsert(saved) in the handler it passes. If you only add one test for the upgrade, add this one.</p><h3>Pitfalls</h3><ul><li>Handlers that only await the API. This is the silent snap-back.</li><li>Returning { refetch: false } out of habit.</li><li>Calling writeUpsert with data you didn&#39;t get from the server. You are then writing your guess as &quot;synced&quot;.</li><li>Not awaiting direct writes.</li><li>Flipping $synced without flipping the condition.</li><li>Treating $hasPendingWrites false as server confirmation.</li><li>Awaiting when(&#39;settled&#39;) while the handler doesn&#39;t wait for confirmation.</li><li>Keeping deps arrays, or using .fn.where without a queryKey.</li><li>Hiding ready rows on isSyncError.</li><li>Upgrading query-db-collection to an RC tag instead of its 1.x line.</li><li>Two copies of @tanstack/db.</li><li>Building joined keys by hand.</li></ul><h3>What I’d do before upgrading</h3><p>It’s an RC, so read the migration guide. It is long but precise, and everything here comes from it. Then, in this order:</p><ol><li>Install @tanstack/react-db@rc, and move query-db-collection and offline-transactions to their latest 1.x versions in the same pass. Check Query Core is 5.90.15 or later.</li><li>Grep for onInsert, onUpdate and onDelete in every queryCollectionOptions. Add writeUpsert, writeDelete or refetch to each, and remove any { refetch: false }.</li><li>Grep for $synced and rewrite the conditions along with the property.</li><li>Grep for isPersisted and switch to await tx.when(&#39;settled&#39;).</li><li>Remove deps arrays and move to the config-object form. Add a queryKey to any .fn clause.</li><li>Replace isError with isLoadingError, isCrashed and isSyncError, and keep ready rows on screen.</li><li>Run the settle test.</li></ol><p>One optional feature: pooling, with pool: pooledLiveQueries, for screens with many same-shape queries. We didn&#39;t need it.</p><p>For us the upgrade was mostly mechanical, and the one non-obvious part was the snap-back. The sidebar stopped snapping back once the handlers wrote the server’s response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6db536725e2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who Is This Cache Entry For? The Audit I Ran the Morning After Next.js’s November Security Release]]></title>
            <link>https://medium.com/@faisalmujtaba/who-is-this-cache-entry-for-the-audit-i-ran-the-morning-after-next-jss-november-security-release-7bcc6a64cb67?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bcc6a64cb67</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[multi-tenant]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 04:31:24 GMT</pubDate>
            <atom:updated>2026-11-04T04:31:24.200Z</atom:updated>
            <content:encoded><![CDATA[<p>Four of the seven advisories were about use cache serving one tenant’s result to someone else. Upgrading fixes the framework bugs. Here’s the audit I ran on our multi-tenant workspace app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E4NOd3VyuYNSk-pA" /></figure><p>The Next.js security release landed late on 3 November, my time. I read the list the way you read a list like that: top to bottom, looking for the words that apply to you. Seven advisories. Four of them said use cache.</p><p>Our app is a document workspace built on Next.js, with Tiptap, comments, Yjs through Hocuspocus, and an AI panel. Customers are organised into workspaces, and a workspace must only ever see its own documents. We cache workspace data in a handful of places.</p><p>My first reaction wasn’t “are we being exploited?” It was quieter and more uncomfortable. I couldn’t say, from memory, what the cache key was for about half of our cached functions.</p><p>To be clear up front, <strong>we found no evidence of any leak.</strong> Nothing in this post is an incident report. It’s about the gap between “I believe it’s fine” and “I can show you why it’s fine”, and how I closed that gap in one morning.</p><h3>Step 0: upgrade before you read anything else</h3><p>The patched versions are next@16.4.5 (Active LTS) and next@15.5.29 (Maintenance LTS).</p><pre>npm ls next<br>npm install next@16.4.5   # or next@15.5.29 on 15.x</pre><p>Then redeploy. Don’t spend your morning matching your exact version against each advisory’s affected range, and don’t talk yourself out of it because “we don’t use that shape.” The shapes in these advisories are subtle, and I’d already shown I didn’t know all of mine.</p><p>If you self-host, there are two extra items. One is a response-injection issue when an attacker-controlled fetched Response is returned unchanged behind certain HTTP/1.1 pipelining reverse proxies. The other is shell cache poisoning, which I come back to below. There&#39;s also an SVG rejection bypass in Image Optimization when images.dangerouslyAllowSVG is false. Read the release post for those.</p><p>Upgrading fixes the framework bugs. It doesn’t answer the question I’d started asking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7a1cobOtPhi0WUHy" /></figure><h3>What a cache key is actually made of</h3><p>I’m not re-teaching Cache Components here (I wrote about migrating to it back in October). One paragraph is enough.</p><p>According to the docs, a use cache key is the build ID (or deploymentId if you configured one), plus a function ID, plus the serializable arguments. Variables from outer scopes that the function references are captured and bound as arguments, so they join the key too. If the function reads root params, only the ones it actually reads are included.</p><p>That gives you the audit question. <strong>Everything that makes an entry belong to one workspace has to be in that list.</strong> If the workspace isn’t in the key, the entry is shared with every workspace.</p><p>The framework bugs this week were all cases where a thing that should have been in the key wasn’t. My job was to make sure our own code never depended on that being true.</p><h3>Audit pass 1: one caching mechanism per function</h3><p>Our app still had an unstable_cache wrapper from before we turned on Cache Components. It was a sidebar helper, the kind of thing nobody touches because it works. Next to it were newer functions using use cache.</p><p>Here’s the advisory I’d rate highest, in plain words. It’s GHSA-mfr8–8qww-v76h, and the Next.js blog rated it High. With Cache Components on, suppose the same public use cache function is called both directly and from inside unstable_cache, and it reads a root param like a tenant identifier. During a cold cache fill, a concurrent call through unstable_cache can get another request&#39;s result without its root params being checked. That result is then stored and served to later callers until it&#39;s revalidated or evicted.</p><p>The GitHub advisory adds that outside this race, the nesting already throws &#39;use cache&#39; inside unstable_cache() is unsupported. Avoiding the nesting is a complete workaround.</p><p>I didn’t find the exact shape, but I found the ingredients: a wrapper and a cached function a few files apart, with nothing stopping someone from composing them. Here’s the fix.</p><pre>// before: two mechanisms stacked on one function<br>export const getSidebar = unstable_cache(<br>  async (workspaceId: string) =&gt; getSidebarDocs(workspaceId), // has &#39;use cache&#39; inside<br>  [&#39;sidebar&#39;]<br>)<br> <br>// after: delete the wrapper, keep only the `use cache` function<br>export async function getSidebarDocs(workspaceId: string) {<br>  &#39;use cache&#39;<br>  // ...<br>}</pre><p>The rule is <strong>one caching mechanism per function, and never call a </strong><strong>use cache function from inside </strong><strong>unstable_cache.</strong></p><p>This isn’t “unstable_cache is evil.&quot; The use cache docs still point you to it when non-fetch data has to persist across deploys, because use cache entries never carry over to a new deployment. That&#39;s a legitimate reason to keep it. Just don&#39;t mix the two on the same function.</p><h3>Audit pass 2: where does the tenant id come from?</h3><p>Closures and root params get captured automatically. That’s convenient, and it’s also where two of the four bugs lived.</p><p>GHSA-vc7v-qv4w-wrv8 is the nested one. An outer public use cache function calls an inner one that reads a root param through next/root-params. The inner function returns something ready immediately alongside a slower async value, so there are pending promises. The outer function finishes without waiting, and its entry is stored before the inner function&#39;s root-param dependencies are recorded. One entry can then be reused across tenant, site, or locale values. Entries written that way can also ignore the tag invalidation and cache lifetimes of the nested caches.</p><p>The leaked content is generated by the app, so an attacker can’t choose it. It’s still someone else’s workspace, rendered for you.</p><p>I can’t audit “which implicit things get captured” by squinting at code. So here’s the rule we adopted, and it’s a preference, not an official requirement. <strong>The workspace id is an explicit string argument to every cached function that returns workspace data, and it’s also in the </strong><strong>cacheTag.</strong></p><pre>// lib/data/workspace-docs.ts<br>import &#39;server-only&#39;<br>import { cacheLife, cacheTag } from &#39;next/cache&#39;<br> <br>export async function getWorkspaceDocList(workspaceId: string) {<br>  &#39;use cache&#39;<br>  cacheLife(&#39;minutes&#39;)<br>  // workspaceId is an explicit argument AND in the tag.<br>  // The function returns only workspace-level data.<br>  cacheTag(`workspace:${workspaceId}:docs`)<br> <br>  return db.document.findMany({<br>    where: { workspaceId },<br>    select: { id: true, title: true, updatedAt: true },<br>  })<br>}</pre><p>Being explicit costs one parameter. In exchange, I can read the function signature and know who the entry is for. The tag has the same property. When one workspace’s docs change and I revalidate workspace:&lt;id&gt;:docs, I&#39;m not nuking everyone else&#39;s entries, and I&#39;m not missing anyone&#39;s.</p><p>Using rg -n &quot;next/root-params&quot; I found places where we read root params in cached code. I didn&#39;t remove them all, but each one now has a comment saying what it contributes to the key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWJNtYqfcfwk0PmU" /></figure><h3>Audit pass 3: authorization outside, sharing inside</h3><p>Cached functions can’t call cookies() or headers() or read searchParams, and the restriction follows the call stack (the error is next-request-in-use-cache). The docs warn that on a dynamic route this can pass next build and fail under next start. So you read those things outside and pass values in.</p><p>That restriction pushes you toward the right shape anyway. Read the session and check membership in the uncached component, then call the cached function with the workspace id:</p><pre>// app/w/[workspaceId]/Sidebar.tsx (a Server Component, not cached)<br>export async function Sidebar({ params }: { params: Promise&lt;{ workspaceId: string }&gt; }) {<br>  const { workspaceId } = await params<br>  const session = await requireSession()<br>  await assertWorkspaceMember(session.userId, workspaceId)<br>  // Auth happens outside the cache, on every request.<br>  // The cached entry is shared only among members of this workspace.<br>  const docs = await getWorkspaceDocList(workspaceId)<br>  return &lt;DocList docs={docs} /&gt;<br>}</pre><p>(requireSession and assertWorkspaceMember are our helpers, not library APIs.)</p><p>That sharing is the point. The cache entry is for the workspace, and it contains only workspace-level data, so serving it to any member is correct. The membership check runs on every request and never hides inside a cache. If you put the check inside a cached function, it runs once per entry rather than once per request.</p><p>Per-user data is a different category: my notifications, my unread count, my drafts. Plain use cache and use cache: remote are both shared. The docs say remote is stored in a remote cache handler, shared across all users and instances, and that for user-specific data you should use use cache: private.</p><pre>import { cookies } from &#39;next/headers&#39;<br>import { cacheLife } from &#39;next/cache&#39;<br> <br>async function getMyUnreadCount(workspaceId: string) {<br>  &#39;use cache: private&#39;<br>  cacheLife({ stale: 60 })<br>  const sessionId = (await cookies()).get(&#39;session&#39;)?.value<br>  // ... query unread count for this session in this workspace<br>}</pre><p>Per the docs, use cache: private can read cookies() and headers(). It isn&#39;t stored in a server cache across requests, though matching calls within one request can reuse the result, and the client router can keep the output in browser memory for the stale time. Or simply don&#39;t cache that data on the server at all. For an unread badge I&#39;m happy with that.</p><h3>Audit pass 4: the Uint8Array trap</h3><p>GHSA-rhh4-g77r-r9qj says distinct binary arguments, such as Uint8Array or Blob, passed to a use cache function could produce the same cache identity. If those arguments distinguish users or accounts, a caller can receive another user&#39;s cached result or poison theirs.</p><p>For most apps that’s an odd edge case. For a Yjs app it’s an invitation. Document state <em>is</em> a Uint8Array, and it&#39;s tempting to pass a snapshot straight into a cached renderer, like a document preview or a link-card.</p><p>I want to be precise: this is <strong>the shape I found one refactor away from.</strong> I did not find a shipped leak. But I found a preview component where passing the bytes in would have been the obvious next step.</p><pre>// before: the cache identity depends on binary arguments<br>async function DocPreview({ snapshot }: { snapshot: Uint8Array }) {<br>  &#39;use cache&#39;<br>  return renderPreview(snapshot)<br>}<br> <br>// after: small string ids in, bytes loaded inside<br>async function DocPreview({<br>  workspaceId, documentId, version,<br>}: { workspaceId: string; documentId: string; version: number }) {<br>  &#39;use cache&#39;<br>  cacheTag(`workspace:${workspaceId}:doc:${documentId}`)<br>  const snapshot = await loadDocSnapshot(workspaceId, documentId, version)<br>  return renderPreview(snapshot)<br>}</pre><p>Now the key is three small values I can reason about, the tag carries the workspace, and the version means a new snapshot is a new entry. This is the pattern I’d use even without the advisory.</p><p>The same reasoning applies to anything in rg -l &quot;use cache&quot; that takes Uint8Array, Blob, or ArrayBuffer. Pass ids and load the bytes inside.</p><h3>Audit pass 5: the non-cache items worth five minutes</h3><p>Two other advisories were cheap to check.</p><p><strong>Edge route handlers that set cookies.</strong> GHSA-f3mh-rxg3-f5g2: App Router Edge Route Handlers and Pages Router Edge API routes that set cookies with NextResponse.cookies.set() can expose the serialized cookie in the internal x-middleware-set-cookie response header. Same-origin JavaScript can read that header even if the cookie is HttpOnly. It requires attacker JS already running on your origin, so it&#39;s not a drive-by, but it undermines the point of HttpOnly. The reproduced leak did not affect Node.js Route Handlers or routes setting cookies via cookies().set().</p><p>We had one auth-adjacent Edge route. I moved it to the default Node runtime:</p><pre>// app/api/session/route.ts<br>// deleted: export const runtime = &#39;edge&#39;<br>import { cookies } from &#39;next/headers&#39;<br> <br>export async function POST(req: Request) {<br>  const token = await createSession(req) // our helper<br>  ;(await cookies()).set(&#39;session&#39;, token, { httpOnly: true, secure: true, sameSite: &#39;lax&#39;, path: &#39;/&#39; })<br>  return new Response(null, { status: 204 })<br>}</pre><p><strong>Shell cache poisoning, if you self-host.</strong> GHSA-vvgp-ww4w-46vf affects self-hosted next start with Cache Components enabled and Partial Prefetching disabled or unset, on specific dynamic route shapes. A crafted URL can store request-specific values in a shared shell, causing wrong server-rendered content or a persistent 404. The advisory&#39;s workaround is a one-line config change. The docs say partialPrefetching: true requires cacheComponents, and that unset behaves like false and logs a warning.</p><pre>// next.config.ts<br>const nextConfig = {<br>  cacheComponents: true,<br>  partialPrefetching: true,<br>}<br>export default nextConfig</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Eza0PONh-tsJRZsT" /></figure><h3>How I checked</h3><h4>The grep checklist</h4><p>This is the whole audit in one block:</p><pre>rg -n &quot;unstable_cache&quot;          # any mixing with use cache?<br>rg -l &quot;use cache&quot;               # every cached function, then read each one<br># inside those files: look for Uint8Array|Blob|ArrayBuffer arguments<br>rg -n &quot;next/root-params&quot;        # what implicit values reach a key?<br>rg -n &quot;runtime = &#39;edge&#39;&quot;        # Edge routes that set cookies</pre><p>For each file from the second command, I wrote one comment above the cached function: who is this entry for? If I couldn’t write the sentence, the function wasn’t done.</p><h4>Watching the cache locally</h4><p>NEXT_PRIVATE_DEBUG_CACHE=1 npm run start gives verbose cache logging. It also works in dev, but remember dev adds an HMR refresh hash to the key, so don&#39;t assume dev cache behaviour matches production.</p><h4>A two-workspace smoke test</h4><p>I also wrote a small script. After a <em>fresh</em> next start, so the cache is cold, it fires concurrent requests for two test workspaces and checks that each response only mentions its own workspace. Cold starts matter because two of the advisories involve races during cache fill.</p><pre>// scripts/tenant-smoke.ts<br>const base = process.env.BASE_URL ?? &#39;http://localhost:3000&#39;<br> <br>async function get(path: string, cookie: string) {<br>  const res = await fetch(base + path, { headers: { cookie } })<br>  return res.text()<br>}<br> <br>const [a, b] = await Promise.all([<br>  get(&#39;/w/test-a/docs&#39;, process.env.COOKIE_A!),<br>  get(&#39;/w/test-b/docs&#39;, process.env.COOKIE_B!),<br>])<br> <br>const ok =<br>  a.includes(&#39;test-a&#39;) &amp;&amp; !a.includes(&#39;test-b&#39;) &amp;&amp;<br>  b.includes(&#39;test-b&#39;) &amp;&amp; !b.includes(&#39;test-a&#39;)<br> <br>if (!ok) {<br>  console.error(&#39;tenant smoke test FAILED: cross-workspace content detected&#39;)<br>  process.exit(1)<br>}<br>console.log(&#39;tenant smoke test passed&#39;)</pre><p>This is a smoke test, not proof. It exercises one race on one pair of routes. What it does is keep the question answered. If someone later passes a snapshot into a cached function, or drops the id from a tag, there’s a chance the test catches it.</p><h3>The pitfalls, in one list</h3><ul><li>Reading the advisories and not upgrading because “we don’t use that shape.”</li><li>Assuming “keyed by arguments” means keyed by tenant, when the tenant comes from a closure or a root param you forgot about.</li><li>Calling a use cache function from inside unstable_cache. Pick one per function.</li><li>Doing the membership check inside a cached function. It runs once per entry, not once per request, and cookies() isn&#39;t allowed there anyway.</li><li>Putting per-user data in use cache or use cache: remote. Both are shared.</li><li>Passing Uint8Array or Blob snapshots as cache arguments.</li><li>Returning objects with still-pending promises from nested cached functions that read root params. That was one of the patched shapes. At minimum, be on 16.4.5.</li><li>A cacheTag without the workspace id, so revalidating one workspace nukes or misses others.</li><li>Edge route handlers setting HttpOnly session cookies via NextResponse.cookies.set().</li><li>Self-hosting with Cache Components and partialPrefetching unset.</li><li>Trusting next build success when request-API misuse only fails under next start.</li><li>Assuming dev behaviour matches production.</li></ul><h3>What I’d do this week</h3><p>To be fair to the framework, use cache is still the right tool. These were framework bugs, they&#39;re fixed, and the team shipped patches for both supported lines. But the release made something visible that was always true. <strong>Your app code decides what the key is.</strong> The framework can&#39;t know that a closure variable is a tenant id. You should be able to say, for every cached function, who an entry is for.</p><p>Here’s the order I’d go in.</p><p><strong>Today</strong></p><ul><li>Check npm ls next.</li><li>Upgrade to 16.4.5 (or 15.5.29 on 15.x) and redeploy.</li></ul><p><strong>This week</strong></p><ul><li>Run the grep audit and write the “who is this entry for?” sentence above each cached function.</li><li>Remove any unstable_cache and use cache mixing.</li><li>Make the tenant id an explicit argument and part of the cacheTag on every cached function that returns tenant data.</li><li>Move per-user data to use cache: private, or stop caching it on the server.</li><li>Replace binary arguments with ids and load the bytes inside.</li><li>Move Edge routes that set cookies to Node.</li><li>If you self-host, set partialPrefetching: true.</li></ul><p><strong>After that</strong></p><ul><li>Add the two-tenant smoke test to CI, run against a fresh next start.</li></ul><p>None of this is glamorous. But the morning after the release I wanted to be able to answer a simple question without guessing, and now I can.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bcc6a64cb67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Moved Our Hocuspocus Server Into a Next.js Route Handler. Here’s What Broke First.]]></title>
            <link>https://medium.com/@faisalmujtaba/i-moved-our-hocuspocus-server-into-a-next-js-route-handler-heres-what-broke-first-b24434dea858?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/b24434dea858</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[yj]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 04:25:00 GMT</pubDate>
            <atom:updated>2026-11-02T04:25:00.801Z</atom:updated>
            <content:encoded><![CDATA[<p>WebSockets in Vercel Functions went GA, so I deleted the box we’d been babysitting. Two people in one document stopped seeing each other’s edits within minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c7c5piNHIXKHqrbB" /></figure><p>Our collaboration server was the one piece of the stack that didn’t ship with the app.</p><p>The Next.js app lived on Vercel. Deploys, previews, env vars and rollbacks were all one flow. Then there was the Hocuspocus server on a separate always-on box. It had its own deploy process, its own copy of the auth secret, its own env vars and its own health checks. It existed for one reason: Vercel Functions couldn’t hold a WebSocket open.</p><p>On 20 October 2026, Vercel made WebSocket support in Functions generally available. It had been in public beta since late June. That was the excuse I’d been waiting for.</p><p>I should say up front that I’m not here to tell you to delete your socket server. It removed a moving part for us. It isn’t mandatory, and I’ll get to when I’d keep the box.</p><h3>The first version worked, which is the dangerous part</h3><p>The first version was almost embarrassingly small. I put Hocuspocus in a route handler, pointed the client at it, and opened a document in one tab. It loaded, I typed, and it saved. I opened a second tab on my own machine, and both tabs stayed in sync. I felt very smart for about an hour.</p><p>Then a teammate and I opened the same document in production and started typing.</p><p>Nothing crossed. I could see my own edits and she could see hers. The document looked fine to each of us, and the two copies were drifting apart.</p><p>Nothing was erroring and nothing was crashing. That’s what made it unpleasant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KEITeph9w1LlGTkw" /></figure><h3>Why two people in one doc stopped seeing each other</h3><p>On the old box, there was one process. Every client connected to it, so every client was talking to the same in-memory Y.Doc. Hocuspocus keeps the document in memory, and that was fine because there was only one memory.</p><p>Functions don’t work like that, for three reasons:</p><ul><li>A WebSocket connection is pinned to the single function instance that accepted it, for its whole lifetime.</li><li>One instance can hold many connections at once (that’s Fluid compute), but a new connection can land on any instance.</li><li>Hocuspocus holds the Y.Doc in memory per instance.</li></ul><p>Put those together. She connected and landed on instance A. I connected and landed on instance B. Each instance loaded its own Y.Doc and each did its job correctly, so we had two separate copies of the same document and nothing connecting them.</p><p>My single-tab test and my two-tab test both went to one instance, which is why they passed. Production showed me what my laptop couldn’t.</p><p>Vercel’s docs say this plainly: durable state, presence, rooms and pub/sub coordination belong in an external store such as Redis, not in in-memory variables. I had read that sentence and nodded at it. I hadn’t connected it to a Y.Doc sitting in a module-scope variable.</p><p>So the plan became: get the socket into a route handler, give each instance its own Hocuspocus, and bridge the instances with Redis.</p><h3>Step 1: the route handler</h3><p>Next.js has no built-in WebSocket upgrade API. Vercel’s answer is upgradeWebSocket() from @vercel/functions (3.10.0 or later), with the ws package installed, returned from a route handler&#39;s GET export.</p><p>One naming trap: some older beta-era guides call it experimental_upgradeWebSocket. If you&#39;re following one of those, rename it.</p><p>Here’s the route:</p><pre>// app/api/collab/route.ts<br>import { connection } from &#39;next/server&#39;;<br>import { upgradeWebSocket } from &#39;@vercel/functions&#39;;<br>import { hocuspocus } from &#39;@/lib/collab/hocuspocus&#39;;<br> <br>export const maxDuration = 800; // Pro. Hobby tops out at 300.<br> <br>export async function GET(request) {<br>  await connection();<br> <br>  return upgradeWebSocket(<br>    (ws) =&gt; {<br>      const conn = hocuspocus.handleConnection(ws, request, {});<br> <br>      ws.on(&#39;message&#39;, (data) =&gt; conn.handleMessage(data));<br>      ws.on(&#39;close&#39;, (code, reason) =&gt;<br>        conn.handleClose({ code, reason: reason.toString() })<br>      );<br>    },<br>    { maxPayload: 4 * 1024 * 1024 }<br>  );<br>}</pre><p>A few notes on it.</p><p>await connection() is there because we have Cache Components enabled. Without it, Next can try to prerender the route, and a prerendered WebSocket endpoint doesn&#39;t do anything useful. If you don&#39;t use Cache Components, you may not need it, but I&#39;d rather have it and not need it.</p><p>The message and close wiring matters. When you use new Hocuspocus(...) directly rather than the built-in Server class, nothing forwards socket events for you. You call handleMessage on every message and handleClose on close yourself. Forget the close handler and Hocuspocus never learns the client left.</p><p>The maxDuration and maxPayload lines come back in Steps 4 and 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*84hICfXU_rgL21kH" /></figure><h3>Step 2: one Hocuspocus per instance, bridged by Redis</h3><p>This was the fix for the bug. I made the Hocuspocus instance at module scope, so each function instance builds exactly one and reuses it across all the connections it holds:</p><pre>// lib/collab/hocuspocus.ts<br>import { Hocuspocus } from &#39;@hocuspocus/server&#39;;<br>import { Redis } from &#39;@hocuspocus/extension-redis&#39;;<br>import { Database } from &#39;@hocuspocus/extension-database&#39;;<br>import { verifyCollabToken, canEditDocument } from &#39;@/lib/collab/auth&#39;;<br>import { loadDocState, saveDocState } from &#39;@/lib/collab/storage&#39;;<br> <br>export const hocuspocus = new Hocuspocus({<br>  name: `collab-${crypto.randomUUID()}`,<br>  extensions: [<br>    new Redis({<br>      host: process.env.REDIS_HOST,<br>      port: Number(process.env.REDIS_PORT),<br>    }),<br>    new Database({<br>      fetch: loadDocState,<br>      store: saveDocState,<br>    }),<br>  ],<br>  async onAuthenticate({ token, documentName }) {<br>    const user = await verifyCollabToken(token);<br>    if (!user || !(await canEditDocument(user, documentName))) {<br>      throw new Error(&#39;Not authorized&#39;);<br>    }<br>    return { user };<br>  },<br>});</pre><p>verifyCollabToken, canEditDocument, loadDocState and saveDocState are our own helpers, not library APIs. They wrap our token logic, our permissions and our database.</p><p>Two details here cost me real time.</p><p><strong>The name has to be unique per instance.</strong> The Redis extension requires each server to have its own name. My first attempt used a hard-coded name, because on one box it never mattered. With a fixed name shared across instances, they can&#39;t tell each other apart. A random UUID per instance fixes it.</p><p><strong>Redis does not persist documents.</strong> The Redis extension syncs document updates and awareness (cursors, presence) between instances, and that’s all it does. If every instance restarted at once, anything living only in Redis would be gone. Persistence is the Database extension’s job, which is why both are in the list. In ours, fetch returns the stored state as a Uint8Array or null for a new document, and store writes the state back.</p><p>The extension also handles a case I’d worried about. When an instance loads a document that’s already open on another instance, it waits up to awaitInitialSyncTimeout (default 1000 ms) to get the current state. And once an instance stores a document, it&#39;s locked for other instances, so two of them don&#39;t write over each other.</p><p>After this, my colleague and I landed on different instances and our edits crossed immediately. That “it just works” moment was what convinced me the move was worth finishing.</p><h3>Step 3: auth on the upgrade request</h3><p>On the old box, we had a copy of the auth secret and a hand-rolled check. Now the socket is just another route in the app, so it’s authenticated the way the app authenticates things.</p><p>The client asks our own /api/collab-token endpoint for a short-lived token and hands it to the provider:</p><pre>import { HocuspocusProvider } from &#39;@hocuspocus/provider&#39;;<br> <br>const { token } = await fetch(&#39;/api/collab-token&#39;, {<br>  method: &#39;POST&#39;,<br>  body: JSON.stringify({ documentId }),<br>}).then((r) =&gt; r.json());<br> <br>const provider = new HocuspocusProvider({<br>  url: &#39;wss://our-domain.example/api/collab&#39;,<br>  name: documentId,<br>  token,<br>});</pre><p>Short-lived matters. It’s tempting to put a long-lived secret in the provider URL. URLs get logged and pasted into places they shouldn’t. A token that expires quickly is a much smaller problem if it leaks.</p><p>In Hocuspocus v4, hooks receive web-standard Request and Headers, so if you want a header you call requestHeaders.get(&#39;authorization&#39;). And onAuthenticate rejects by throwing, which is what the code above does.</p><p>One thing worth knowing: the upgrade request is an HTTP GET with an Upgrade header, and it goes through Routing Middleware, rewrites, Firewall rules and rate limits before it upgrades. Rate limits apply to each upgrade request. That&#39;s mostly good news, since your existing protections apply. But if you have a middleware that redirects unauthenticated requests or a tight rate limit, check that it isn&#39;t also catching your socket route.</p><h3>Step 4: disconnects are the normal case now</h3><p>This was the biggest mindset change.</p><p>A connection to a function closes when the function reaches its maximum duration. On Hobby, the default and the maximum are both 300 seconds. On Pro and Enterprise, the default is 300 and the max is 800, with 1800 available in beta. You set it per function, which is why the route exports maxDuration.</p><p>If you forget to set it, you get the default: a reconnect every five minutes, for everyone, forever.</p><p>The good news is that the data side is fine. HocuspocusProvider reconnects automatically, and Yjs resyncs on reconnect, so nobody loses edits.</p><p>What broke was our own UI. We had a “reconnecting” banner that appeared on every close event, because on the old box a close meant something was wrong. Now a close happens on a schedule. People watched a red banner flash on every few minutes of normal work.</p><p>The fix was to stop treating a close as an error and only show the banner if the socket stays down for more than a few seconds:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br> <br>function useShowReconnecting(provider) {<br>  const [show, setShow] = useState(false);<br> <br>  useEffect(() =&gt; {<br>    let timer;<br> <br>    const onStatus = ({ status }) =&gt; {<br>      clearTimeout(timer);<br>      if (status === &#39;connected&#39;) {<br>        setShow(false);<br>      } else {<br>        timer = setTimeout(() =&gt; setShow(true), 4000);<br>      }<br>    };<br> <br>    provider.on(&#39;status&#39;, onStatus);<br>    return () =&gt; {<br>      clearTimeout(timer);<br>      provider.off(&#39;status&#39;, onStatus);<br>    };<br>  }, [provider]);<br> <br>  return show;<br>}</pre><p>The delay is a number I picked, not a recommendation. Tune it to what feels calm in your product. The point is that a normal reconnect finishes before the timer fires, and a real outage doesn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HVPWEU3HHvGUWwIm" /></figure><h3>Step 5: deploys overlap</h3><p>This one is easy to miss, because it only matters when you ship.</p><p>After a deployment, new connections may reach the new deployment, while existing connections stay on the previous one until they close. So for a while, old-deployment sockets and new-deployment sockets are open on the same documents.</p><p>Because both talk to the same Redis, they still sync with each other. That part holds up.</p><p>The risk is what you send across. If you change the document schema or the shape of an awareness payload in a way the old code can’t read, you have two code versions exchanging messages in the same room. I’d now treat that as two separate deploys: first make readers tolerant of the new shape, then start writing it. Don’t put a breaking collab change and a normal release in the same push.</p><h3>Step 6: payload size</h3><p>upgradeWebSocket takes an options object with maxPayload. The default is 262144 bytes, or 256 KiB.</p><p>For a small document, you’ll never notice. For a large one, the first sync can arrive as one big message, and a message over the limit won’t make it through.</p><p>I raised it deliberately, to 4 MiB in the route above. I don’t claim that’s the right number for you. Look at how big your largest real document’s initial sync gets, set the limit with headroom, and write down why. A larger limit means a larger message the server will accept from any client, so it should be a choice rather than a copy-paste.</p><h3>Step 7: local dev</h3><p>This one cost me a confused afternoon.</p><p>upgradeWebSocket only works on the Vercel platform. next dev doesn&#39;t run it, so locally the route just doesn&#39;t upgrade, and you conclude your code is broken. It isn&#39;t. You need vc dev (Vercel CLI 54.14.2 or above) instead:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;next dev&quot;,<br>    &quot;dev:collab&quot;: &quot;vc dev&quot;<br>  }<br>}</pre><p>I kept dev as it was and added dev:collab for when I&#39;m working on anything realtime. Most of the day I don&#39;t need the socket.</p><h3>The pitfalls, in one place</h3><p>If you remember nothing else:</p><ul><li>Keeping the Y.Doc in memory per instance without Redis. This was our headline bug.</li><li>Reusing one hard-coded Hocuspocus name across instances.</li><li>Thinking Redis persists documents. It doesn’t; use the Database extension.</li><li>Treating every close as an outage.</li><li>Forgetting maxDuration, which means a reconnect every five minutes on the default.</li><li>Shipping a breaking schema or awareness change while old-deployment sockets are still open.</li><li>Leaving maxPayload at 256 KiB when your documents are bigger.</li><li>Testing with next dev and deciding it&#39;s broken.</li><li>Forgetting await connection() when Cache Components is on.</li><li>Putting a long-lived secret in the provider URL instead of a short-lived token.</li><li>Assuming idle sockets are free. While a connection is open, its instance’s Provisioned Memory stays billable, shared across all the connections on that instance. Active CPU is billed only while processing messages, and the pricing is otherwise the same as other Function invocations.</li><li>Following beta-era docs that call it experimental_upgradeWebSocket.</li></ul><h3>Should you move yours?</h3><p>It depends, and I don’t think there’s a universal answer.</p><p>I’d keep a separate long-running server if your sessions are very long and you don’t want constant reconnects, if each message needs heavy CPU, or if you’re not on a plan where you can set a long enough maxDuration. Vercel&#39;s own docs note that handling WebSockets with native Node.js APIs gives you more control where that&#39;s possible. upgradeWebSocket is the workaround for Next.js, not the ideal API.</p><p>I’d move if your socket server is the one thing that doesn’t deploy with the app and you’re tired of maintaining it, and if you can tolerate reconnects as a normal event. For us, losing the second set of deploys, env vars and secrets was worth the new things we had to think about.</p><p><strong>This week</strong>, if you’re considering it:</p><ol><li>Add Redis and give every Hocuspocus instance a unique name.</li><li>Set maxDuration on the route.</li><li>Make your UI tolerate reconnects, with a debounced banner instead of one on every close.</li><li>Raise maxPayload deliberately, based on your largest documents.</li></ol><p><strong>Rollout order:</strong></p><ol><li>Shadow a test document first. Point a throwaway doc at the new route and have two people hammer it.</li><li>Move internal documents next.</li><li>Then everyone.</li><li>Keep the old box running until reconnect behaviour looks boring.</li></ol><p>That last one is the real test. Don’t judge the move by the day it works. Judge it by the day nobody mentions it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b24434dea858" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our AI Panel Could Rewrite a Document Without Asking. TanStack AI 1.0 Fixed That]]></title>
            <link>https://medium.com/@faisalmujtaba/our-ai-panel-could-rewrite-a-document-without-asking-tanstack-ai-1-0-fixed-that-885452a2b2ff?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/885452a2b2ff</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[tanstack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 04:22:59 GMT</pubDate>
            <atom:updated>2026-11-01T04:22:59.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Tool approvals turned my pile of confirm-dialog state into a real pause in the run. Here’s how I wired it into a Next.js document workspace, and what bit me during the 1.0 upgrade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YZ9lwL3QqCt22kcB" /></figure><p>The Ask AI panel in our document workspace started out harmless. You could ask it to summarize a page or explain a paragraph, and it only ever read things.</p><p>Then we added a “rewrite this section” tool. That’s when things got interesting.</p><p>In testing, I asked the panel a question about a section, something like “is this paragraph clear?”, and it answered by rewriting the section. The edit landed in the editor before I’d finished reading its reply. Nothing was lost, because we keep version history. But it was the wrong default, and I felt it in my stomach anyway. A tool that can change someone’s document shouldn’t be allowed to decide on its own that it should.</p><p>TanStack AI 1.0 shipped on 23 Oct 2026 with the core APIs marked stable, and its tool approvals were exactly what I needed. This post covers how I used them, plus the upgrade gotchas that bit me along the way.</p><h3>Why my first fix was bad</h3><p>My first attempt was the obvious one. I added a pendingEdit piece of state in the panel, rendered an &quot;Are you sure?&quot; box when it was set, and applied the edit when the user clicked Approve.</p><p>It worked for the happy path and fell apart almost immediately.</p><p>The confirmation lived outside the model run. Reload the page and the pending state vanished, but the conversation still showed the AI proposing something. If the model made two tool calls in one turn, I needed a queue, and then a way to tell the model what happened to each. I was rebuilding a worse version of a protocol that the library should own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ywZvLFkgjdxsQ_mG" /></figure><h3>Step 1: Decide which tools need a person</h3><p>The rule of thumb from the TanStack docs is to use approval for actions you can’t undo, like sending, paying or deleting. I’d extend that to anything where the user would be surprised by the result.</p><p>Here’s how our tools came out:</p><ul><li><strong>replace_section</strong> changes the user&#39;s text. It needs approval. It&#39;s a client tool, because it touches the editor.</li><li><strong>delete_block</strong> is also a client tool and needs approval.</li><li><strong>share_document</strong> is a server tool that gives someone else access. It needs approval.</li><li><strong>summarize_doc</strong> only reads, so it needs no approval.</li></ul><p>That last one matters. If everything asks for permission, people stop reading the prompts and click Approve on reflex. Approval fatigue is a real failure mode, and it makes the whole thing worthless. Approvals only mean something if they’re rare.</p><h3>Step 2: One shared definition file</h3><p>Every tool gets defined once, in a file that both the server and the browser import. That way the types match on both sides.</p><pre>// lib/ai/tools.ts<br>import { toolDefinition } from &#39;@tanstack/ai&#39;<br>import { z } from &#39;zod&#39;<br> <br>const approvalSchema = {<br>  approve: z.object({ note: z.string() }),<br>  reject: z.object({ reason: z.string() }),<br>}<br> <br>export const replaceSectionDef = toolDefinition({<br>  name: &#39;replace_section&#39;,<br>  description: &#39;Replace the text of one section of the document.&#39;,<br>  inputSchema: z.object({<br>    sectionId: z.string(),<br>    newText: z.string(),<br>    summary: z.string(),<br>  }),<br>  outputSchema: z.object({ applied: z.boolean() }),<br>  needsApproval: true,<br>  approvalSchema,<br>})<br> <br>export const deleteBlockDef = toolDefinition({<br>  name: &#39;delete_block&#39;,<br>  description: &#39;Delete one block from the document.&#39;,<br>  inputSchema: z.object({ blockId: z.string() }),<br>  outputSchema: z.object({ deleted: z.boolean() }),<br>  needsApproval: true,<br>})<br> <br>export const shareDocumentDef = toolDefinition({<br>  name: &#39;share_document&#39;,<br>  description: &#39;Share the document with another person.&#39;,<br>  inputSchema: z.object({ email: z.string() }),<br>  outputSchema: z.object({ shared: z.boolean() }),<br>  needsApproval: true,<br>})</pre><p>summarizeDocDef looks the same minus needsApproval, so I&#39;ve left it out. Without that flag, a client tool runs on its own and never pauses.</p><p>One detail worth knowing: approvalSchema requires needsApproval: true, and toolDefinition throws if you set it without that flag. I found that out the fast way.</p><h3>Step 3: The route handler</h3><p>The route is smaller than I expected.</p><pre>// app/api/chat/route.ts<br>import { chat, chatParamsFromRequest, toServerSentEventsResponse } from &#39;@tanstack/ai&#39;<br>import { openaiText } from &#39;@tanstack/ai-openai&#39;<br>import { replaceSectionDef, deleteBlockDef, shareDocumentDef } from &#39;@/lib/ai/tools&#39;<br>import { shareDoc } from &#39;@/lib/docs/share&#39;<br> <br>export async function POST(request: Request) {<br>  const params = await chatParamsFromRequest(request)<br> <br>  const shareDocument = shareDocumentDef.server(async ({ email }) =&gt; {<br>    await shareDoc(params.threadId, email) // our own helper; it checks permissions<br>    return { shared: true }<br>  })<br> <br>  const stream = chat({<br>    adapter: openaiText(&#39;gpt-6.1-sol&#39;),<br>    messages: params.messages,<br>    threadId: params.threadId,<br>    runId: params.runId,<br>    parentRunId: params.parentRunId,<br>    ...(params.resume ? { resume: params.resume } : {}),<br>    tools: [replaceSectionDef, deleteBlockDef, shareDocument],<br>  })<br> <br>  return toServerSentEventsResponse(stream)<br>}</pre><p>Two things to notice.</p><p>For the two client tools, I pass the <strong>definitions</strong> to the server, not implementations. The server alone decides which tools the model sees. The browser can’t quietly add one.</p><p>And shareDocument is the only tool with a server-side implementation. It runs only after the user approves.</p><h4>Where the pause actually happens</h4><p>When the model calls a tool marked needsApproval, chat() doesn&#39;t run it. It ends the run with an interrupt. The user&#39;s answer arrives in a second request, and the browser sends the full message history back with it. That&#39;s why a stateless route can rebuild the paused call. I don&#39;t need a database or a pending-actions table for this.</p><p>It also explains why parentRunId and resume have to be forwarded. If you drop them, the second request has no way to continue the first run. I&#39;ll admit I dropped them at first.</p><h3>Step 4: The approval UI</h3><p>On the client, useChat gives me interrupts and resuming. I set threadId to the document id, which gives every document its own stable conversation.</p><p>The tools with a client implementation get their implementations here. We’ll get to that in the next step, but this is where they live:</p><pre>// components/ask-ai/use-doc-chat.ts<br>import { createChatClientOptions } from &#39;@tanstack/ai-client&#39;<br>import { fetchServerSentEvents, useChat } from &#39;@tanstack/ai-react&#39;<br>import { replaceSectionDef, deleteBlockDef, shareDocumentDef } from &#39;@/lib/ai/tools&#39;<br>import { applyReplacement, removeBlock, type OurEditorHandle } from &#39;@/lib/editor/helpers&#39;<br> <br>type ClientContext = { editor: OurEditorHandle }<br> <br>const replaceSection = replaceSectionDef.client&lt;ClientContext&gt;((input, ctx) =&gt; {<br>  return { applied: applyReplacement(ctx.context.editor, input) }<br>})<br> <br>const deleteBlock = deleteBlockDef.client&lt;ClientContext&gt;((input, ctx) =&gt; {<br>  return { deleted: removeBlock(ctx.context.editor, input.blockId) }<br>})<br> <br>export function useDocChat(documentId: string, editor: OurEditorHandle) {<br>  const chatOptions = createChatClientOptions({<br>    connection: fetchServerSentEvents(&#39;/api/chat&#39;),<br>    threadId: documentId,<br>    tools: [replaceSection, deleteBlock, shareDocumentDef],<br>    context: { editor },<br>  })<br>  return useChat(chatOptions)<br>}</pre><p>The panel renders each interrupt of kind &#39;tool-approval&#39;. Each one has an id, a toolName, originalArgs, a canResolve flag that stays false until it&#39;s ready, and a resolveInterrupt function.</p><p>The most important design decision in the whole thing is the preview. <strong>Don’t show raw JSON.</strong> A user can’t judge {&quot;sectionId&quot;:&quot;s_14&quot;,&quot;newText&quot;:&quot;...&quot;}. They can judge a before and after.</p><pre>// components/ask-ai/approval-card.tsx<br>import { useState } from &#39;react&#39;<br> <br>export function ApprovalCard({ interrupt, resuming, editor }: Props) {<br>  const [draft, setDraft] = useState(interrupt.originalArgs.newText)<br>  const [reason, setReason] = useState(&#39;&#39;)<br>  const busy = !interrupt.canResolve || resuming<br>  const args = interrupt.originalArgs<br>  const before = getSectionText(editor, args.sectionId) // our own helper<br> <br>  return (<br>    &lt;div className=&quot;approval-card&quot;&gt;<br>      &lt;p&gt;{args.summary}&lt;/p&gt;<br>      &lt;h4&gt;Now&lt;/h4&gt;<br>      &lt;blockquote&gt;{before}&lt;/blockquote&gt;<br>      &lt;h4&gt;Proposed&lt;/h4&gt;<br>      &lt;textarea value={draft} onChange={(e) =&gt; setDraft(e.target.value)} /&gt;<br> <br>      &lt;button disabled={busy} onClick={() =&gt;<br>        interrupt.resolveInterrupt(true, { payload: { note: &#39;Approved&#39; } })}&gt;<br>        Approve<br>      &lt;/button&gt;<br> <br>      &lt;button disabled={busy} onClick={() =&gt;<br>        interrupt.resolveInterrupt(true, {<br>          editedArgs: { ...args, newText: draft },<br>          payload: { note: &#39;Edited before approving&#39; },<br>        })}&gt;<br>        Edit, then approve<br>      &lt;/button&gt;<br> <br>      &lt;input value={reason} onChange={(e) =&gt; setReason(e.target.value)} placeholder=&quot;Why not?&quot; /&gt;<br>      &lt;button disabled={busy} onClick={() =&gt;<br>        interrupt.resolveInterrupt(false, { payload: { reason: reason || &#39;No reason given&#39; } })}&gt;<br>        Deny<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>This card is the one for replace_section. Delete and share get simpler cards with the same three buttons, minus the text box.</p><p>The buttons are disabled while !canResolve || resuming. resuming is true while an answer is on its way, so this stops double clicks from sending two answers.</p><h3>Step 5: The edit runs in the browser</h3><p>Look back at replaceSection in the hook file. It&#39;s a client tool made with .client(). Because the definition has needsApproval: true, it only runs after the user approves. The approval UI is identical for client and server tools, which I liked.</p><p>The editor instance reaches the tool through the typed context option. That context belongs to the hook instance and is <strong>not sent to the server</strong>. If you need server-side values, use forwardedProps instead. The model never sees the editor object, and the server never needs to.</p><p>I treat applyReplacement as ours. It&#39;s a plain function that takes the editor handle and the input, and it returns a boolean. All the editor-specific knowledge lives there, and the tool definition doesn&#39;t know any of it.</p><p>That function is also where I handle stale approvals. A user can leave an approval open for a long time, and in a collaborative document the section may have changed or disappeared by then. So applyReplacement first checks that the section still exists. If it doesn&#39;t, it returns false and the tool reports { applied: false } instead of throwing. The docs suggest returning errors as data, and that&#39;s what I did. If a .client() function throws, or its output fails outputSchema, the model gets a tool error instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SFHh3b2Z984mGNkM" /></figure><h3>Step 6: Approve with edits, deny with a reason</h3><p>This is the part I’m most pleased with.</p><p>An approval doesn’t have to be yes or no. The AI proposes a rewrite, the user changes two words, and approves their own version. editedArgs makes that a first-class thing. It <strong>replaces the args in full</strong>, which is why my card spreads ...args and overrides only newText. Send a partial object and you&#39;ve dropped fields.</p><p>Edited args are validated against inputSchema. If they don&#39;t fit, the resume stops with an invalid-edited-args error. A rejection never takes edits.</p><p>Denial is a real answer too. resolveInterrupt(false, { payload: { reason } }) tells the model no, and it sees the reason. It can then respond like a person would: &quot;Got it, I&#39;ll leave that section alone.&quot;</p><p>cancel() is different. It drops the pause with no answer and no payload. I use it when the user closes the panel without deciding. Reject means &quot;I considered it and said no.&quot; Cancel means &quot;I never answered.&quot;</p><p>If several approvals are pending, they wait until all have valid answers and then submit together. resolveInterrupts(...) on the hook answers several at once. A single pending approval submits as soon as it has a valid answer.</p><h3>Step 7: A denial is not an error</h3><p>My first version showed a red toast when the user denied something. That’s wrong. The user did exactly what they intended.</p><p>Denied and cancelled results do come back with state &#39;error&#39;. But the tool-result part carries an outcome of &#39;denied&#39; or &#39;cancelled&#39;. No outcome means a real failure.</p><pre>const wasDenied = message.parts.some(<br>  (part) =&gt; part.type === &#39;tool-result&#39; &amp;&amp; part.outcome === &#39;denied&#39;<br>)<br> <br>{wasDenied &amp;&amp; &lt;p className=&quot;muted&quot;&gt;Nothing changed. You declined that edit.&lt;/p&gt;}</pre><p>“Nothing changed” is the message people actually want. It’s quiet and it’s accurate. Reserve red for real failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UvazKvaGWRrnwCkG" /></figure><h3>The 1.0 upgrade bits that bit me</h3><p>Type checking passing did not mean I was done. Here’s what actually caught me.</p><p><strong>threadId is required, on both sides.</strong> The codemod (npx jscodeshift with the ag-ui-compliance transform) renames body to forwardedProps and conversationId to threadId. It can&#39;t add a threadId you never had. In the browser, pass a stable id per conversation, such as a route id or a database id. On the server, pass params.threadId.</p><pre>- useChat({ connection })<br>+ useChat({ connection, threadId: documentId })</pre><p><strong>addToolApprovalResponse() is gone.</strong> You find the interrupt and resolve it:</p><pre>const { interrupts } = useChat({ connection, threadId: chatId, forwardedProps: { userId } })<br>const approval = interrupts.find((item) =&gt; item.kind === &#39;tool-approval&#39;)<br>if (approval?.kind === &#39;tool-approval&#39;) approval.resolveInterrupt(true)</pre><p><strong>@tanstack/ai-react-ui is removed.</strong> Build your UI with createChatHook from @tanstack/ai-react/ui.</p><p><strong>Custom servers must change how they end a stream.</strong> Stop sending data: [DONE] and end the run with a RUN_FINISHED event. 1.0 uses the open AG-UI protocol for events, and a 1.0 client needs a 1.0 server.</p><p><strong>Stored 0.x conversations aren’t migrated for you.</strong> A passing type check doesn’t touch saved conversations, runs or files. Follow the saved-data steps in the upgrade guide, then open an old conversation and append a message before you call it done. I’d have shipped without doing that.</p><p>Also upgrade every stable @tanstack/ai* package together. @tanstack/ai-harness and its CLI are the exception. They stay on 0.x and experimental.</p><h3>Pitfalls</h3><ul><li><strong>Asking for approval everywhere.</strong> People will click Approve without reading. Keep it for actions that matter.</li><li><strong>Showing raw JSON.</strong> Build a preview.</li><li><strong>Forgetting </strong><strong>parentRunId and </strong><strong>resume in the route.</strong> The second request can&#39;t continue.</li><li><strong>Passing both </strong><strong>.server() and </strong><strong>.client() for one tool name.</strong> Pass only one, and keep tool names unique within a tools array.</li><li><strong>Letting the client declare tools.</strong> The server should decide.</li><li><strong>Using a random </strong><strong>threadId per render.</strong> Use a stable document or conversation id.</li><li><strong>Treating a denial as an error.</strong> No red toast.</li><li><strong>editedArgs that don&#39;t fit </strong><strong>inputSchema.</strong> You get invalid-edited-args.</li><li><strong>Stale approvals.</strong> Re-check that the section still exists before applying.</li><li><strong>Secrets or heavy dependencies in client tools.</strong> They ship to the browser. Keep them small.</li><li><strong>Upgrading only some of the TanStack AI packages.</strong></li><li><strong>Skipping the old 0.x conversation check.</strong></li></ul><p>One more thing I’ll mention but haven’t tried hard yet: fakeText() lets you test chat(), tools and middleware with no network and no API key. Approval flows are exactly the sort of thing you want covered by tests that don&#39;t call a model.</p><p>There’s also the experimental agent harness, @tanstack/ai-harness. It keeps approvals as waits in a session log that can survive restarts with a durable store, which is appealing. But it&#39;s 0.x and experimental, so I&#39;m not putting it in production yet.</p><h3>What I’d do this week</h3><p>Open your tool list and write down every AI tool you have. Next to each, mark whether it changes user data: edits, deletes, sends, shares, pays. That list is the whole job.</p><p>Then:</p><ol><li>Add needsApproval: true to every tool that changes data.</li><li>Make threadId your document or conversation id, on both the client and the server.</li><li>Forward parentRunId and resume in your route.</li><li>Open an old conversation and make sure it still works.</li></ol><p>For the rollout, I’d go in this order:</p><ol><li><strong>Approvals on destructive tools first.</strong> Deletes, shares, rewrites.</li><li><strong>Readable previews.</strong> Before and after, not JSON.</li><li><strong>editedArgs.</strong> Let people fix a proposal instead of only accepting or refusing it.</li><li><strong>The harness, later.</strong> Once it’s out of experimental.</li></ol><p>The panel can still rewrite a section. It just has to ask first now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=885452a2b2ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Lazy-Loaded Our Editor. It Was Still in Every Route’s Bundle.]]></title>
            <link>https://medium.com/@faisalmujtaba/we-lazy-loaded-our-editor-it-was-still-in-every-routes-bundle-2635fe71b073?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/2635fe71b073</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 04:30:06 GMT</pubDate>
            <atom:updated>2026-10-30T04:30:06.220Z</atom:updated>
            <content:encoded><![CDATA[<p>The Next.js 16.4 Turbopack Bundle Analyzer showed me that next/dynamic doesn’t defer anything if one barrel file still imports the module statically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d9sLG8WmPL5RWdCy" /></figure><p>The dashboard felt heavier than it should.</p><p>It’s a page that lists documents. Titles, a few filters, a “New document” button. That’s it. But it had that slightly sticky feel on first load that you get when a page is carrying luggage it doesn’t need.</p><p>I knew where the luggage might come from. Our document workspace has a Tiptap/ProseMirror editor, Yjs for realtime collab, a comments sidebar, and markdown plus syntax highlighting for the Ask AI panel. None of that belongs on a page that only lists documents.</p><p>But I had wrapped the editor in next/dynamic months ago. I&#39;d ticked that box in my head. Lazy-loaded, done, moving on.</p><p>It wasn’t done. Here’s how I found out, what was actually wrong, how I fixed it, and how I proved the fix instead of just feeling good about it. Plus where an AI agent skill helped and where I kept my hands on the wheel.</p><h3>Why nobody noticed</h3><p>Part of the answer is boring: nothing told us.</p><p>Since Next.js 16.0, next build no longer prints JS bundle size metrics. That&#39;s in the CLI version history. So there&#39;s no red number in your build output telling you a route got fatter. Bundle growth is silent unless you go looking for it.</p><p>Nobody opens a bundle report on a feature PR “just to check.” The tests pass, the page loads, and a leak like this can sit there for months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5iCCv4x32Hcb9xD8" /></figure><h3>Step 1: Look at it</h3><p>Next.js 16.4 (the blog post is dated 28 October 2026) gave the Turbopack Bundle Analyzer some new tools. The analyzer itself first shipped in 16.1. It uses Turbopack’s module graph, so it needs Turbopack, which is the default bundler since Next.js 16.</p><pre>npx next analyze</pre><p>That analyzes the app and starts a local server (port 4000 by default, --port to change it). It doesn&#39;t produce an application build, which is nice for a quick look.</p><p>Here’s what I did, in order:</p><ol><li><strong>Started on the route summary home page.</strong> New in 16.4, it highlights the largest client routes. I wanted to see where the dashboard sat relative to the routes that legitimately need the editor.</li><li><strong>Opened the dashboard route</strong> and sorted the table by size. The per-route table is also new in 16.4.</li><li><strong>Turned on the critical render path view</strong> and filtered out async dependencies. That leaves only what loads synchronously for the first render, which is the part I cared about.</li><li><strong>Clicked a module</strong> to see its size and full import chain.</li></ol><p>That last step is where it got uncomfortable. The editor stack was there, on the dashboard’s critical path. Click into it and the import chain doesn’t lead through our next/dynamic loader. It leads through something else.</p><p>One caveat, straight from the Next.js team: depending on runtime state, RSC renders may include chunks created by next/dynamic in the initial load. So the critical-path view is a strong hint, not a verdict. Test the app to verify what really loads.</p><p>You can also filter by route, client vs server, and type (JavaScript, CSS, JSON). The analyzer traces imports across server-to-client boundaries and dynamic imports, which is what makes the chain readable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VWuAP2jbHLipsEwe" /></figure><h3>Step 2: The trap</h3><p>Here’s the rule the Next.js team spells out. If HeavyComponentLoader is the only module importing ./HeavyComponent, the code is deferred. But if any other module in the same bundle statically imports ./HeavyComponent, its code still loads upfront.</p><p>Read that twice. A dynamic() boundary protects you only if it&#39;s the <em>only</em> way in.</p><p>Our setup looked roughly like this.</p><p><strong>Before:</strong></p><pre>// components/editor/index.ts  (the barrel)<br>export { DocumentEditor } from &#39;./document-editor&#39;;<br>export { getDocTitle } from &#39;./get-doc-title&#39;;<br> <br>// app/(app)/dashboard/page.tsx<br>import { getDocTitle } from &#39;@/components/editor&#39;;<br> <br>export default function DashboardPage() {<br>  // ...uses getDocTitle(doc) to render the list<br>}</pre><p>getDocTitle is tiny. The dashboard only wants a string helper. But it imports from the barrel, and the barrel statically re-exports DocumentEditor. So the editor, and everything it pulls in, rides along into the dashboard&#39;s initial bundle. The next/dynamic wrapper elsewhere is still there, still correct, and doing nothing for this route.</p><p>Each import looked harmless on its own. That’s the trap.</p><p><strong>After:</strong></p><pre>// lib/doc-title.ts<br>export function getDocTitle(doc: { title?: string }) {<br>  return doc.title?.trim() || &#39;Untitled&#39;;<br>}<br> <br>// app/(app)/dashboard/page.tsx<br>import { getDocTitle } from &#39;@/lib/doc-title&#39;;</pre><p>Same helper, new home, direct import. The static path from the dashboard to the editor is gone.</p><p>Our second offender was the same pattern wearing a different hat: a shared utils file that imported a heavy dependency at the top level, used by a function the document list called. Same cure. Split the heavy part out so light routes can’t reach it by accident.</p><h3>Step 3: The fixes</h3><p>Four changes, each small.</p><h4>a. Import from the file, not the barrel</h4><p>Barrels are convenient, and they’re also the most common way a heavy module sneaks back into a light route. For anything near the editor I stopped importing from @/components/editor in non-editor routes. Direct file imports only, and I kept the static path to the heavy module out of any route that never opens a document.</p><p>(If you have a package with lots of exports, like an icon set, Next.js also has experimental.optimizePackageImports: [&#39;package-name&#39;] in next.config, which only loads the modules you use. Some libraries get this automatically. That&#39;s a different problem from our barrel, but it&#39;s the same family.)</p><h4>b. A real dynamic boundary, in a Client Component</h4><p>Now that nothing else statically imports the editor on light routes, the next/dynamic boundary can actually do its job.</p><pre>// components/editor/editor-loader.tsx<br>&#39;use client&#39;;<br> <br>import dynamic from &#39;next/dynamic&#39;;<br>import type { ComponentProps } from &#39;react&#39;;<br>import { EditorSkeleton } from &#39;./editor-skeleton&#39;;<br> <br>const DocumentEditor = dynamic(<br>  () =&gt; import(&#39;./document-editor&#39;).then((m) =&gt; m.DocumentEditor),<br>  {<br>    ssr: false,<br>    loading: () =&gt; &lt;EditorSkeleton /&gt;,<br>  }<br>);<br> <br>export function EditorLoader(props: ComponentProps&lt;typeof DocumentEditor&gt;) {<br>  return &lt;DocumentEditor {...props} /&gt;;<br>}</pre><p>Three things worth saying out loud:</p><ul><li>next/dynamic is a composite of React.lazy() and Suspense. The loading option is your fallback while the chunk arrives.</li><li>ssr: false only works in Client Components. Use it in a Server Component and you get an error. That&#39;s why this file starts with &#39;use client&#39;.</li><li>When a Server Component dynamically imports a Client Component, automatic code splitting is currently not supported. So the dynamic() call lives in a Client Component, always.</li></ul><p>I only used ssr: false because our editor genuinely can&#39;t prerender. If yours can, leave it off.</p><p>Since our editor is a named export, the .then((m) =&gt; m.DocumentEditor) is the docs&#39; pattern for that case.</p><h4>c. Load on-demand libraries when the user asks for them</h4><p>We have an “Export as PDF” button. It’s an occasional action, not something every visit needs, so there’s no reason its code should be in the initial bundle of the page it sits on.</p><pre>&#39;use client&#39;;<br> <br>export function ExportButton({ docId }: { docId: string }) {<br>  async function onClick() {<br>    const { exportDoc } = await import(&#39;@/lib/export-doc&#39;);<br>    await exportDoc(docId);<br>  }<br> <br>  return &lt;button onClick={onClick}&gt;Export as PDF&lt;/button&gt;;<br>}</pre><p>@/lib/export-doc is our own module. The point is the await import() inside the event handler: the code is fetched when someone clicks, not before. The same idea works for a diff library that only matters when someone opens a comparison.</p><h4>d. Move static rendering to a Server Component</h4><p>Markdown rendering and syntax highlighting were shipping to the client for our Ask AI panel. Some of that has to stay there: streaming AI output needs client rendering, because the content arrives token by token.</p><p>But not everything in that panel is streaming. A <em>saved</em> AI answer, or a read-only code preview in a rendered document, is static content. It doesn’t need browser APIs or interaction. The Next.js docs show this pattern with codeToHtml from shiki in an async Server Component, and that&#39;s what I followed.</p><pre>// components/ai/saved-code-preview.tsx  (Server Component)<br>import { codeToHtml } from &#39;shiki&#39;;<br> <br>export async function SavedCodePreview({ code }: { code: string }) {<br>  const html = await codeToHtml(code, { lang: &#39;tsx&#39;, theme: &#39;github-dark&#39; });<br>  return &lt;div dangerouslySetInnerHTML={{ __html: html }} /&gt;;<br>}</pre><p>The highlighting library runs on the server and never ships to the browser for these views. For the live streaming path, it stays client-side, and I put that behind a dynamic boundary so it only loads where the panel actually opens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qxWOt1CqLY3NRYHb" /></figure><h3>Step 4: Prove it</h3><p>This is the part I used to skip. This time I took snapshots.</p><pre>npx next analyze --output --snapshot before<br># ...make the changes...<br>npx next analyze --output --snapshot after</pre><p>--output (or -o) writes the analyzer data and UI files to .next/diagnostics/analyze without serving anything. --snapshot &lt;name&gt; saves a named snapshot, replacing any earlier one with the same name. Then I opened the analyzer and diffed the two snapshots.</p><p>I’m keeping my results qualitative on purpose. What I saw: the editor stack disappeared from the dashboard’s critical path. The document list and settings went the same way. The editor chunks still exist, and they load when you open a document, which is exactly the point.</p><p>If you want to script anything, or check this in CI, you can export a snapshot as JSON Lines without rebuilding or starting a server:</p><pre>npx next analyze export --snapshot after --route /dashboard &gt; dashboard.jsonl</pre><p>--snapshot defaults to the newest, --route restricts the export to one route (it still includes the full module graph), and --dist-dir is there if your build output lives somewhere unusual.</p><p>I didn’t build anything fancy on top of it. A generic script that reads the file line by line is enough to confirm the export isn’t empty:</p><pre>import { createReadStream } from &#39;node:fs&#39;;<br>import { createInterface } from &#39;node:readline&#39;;<br> <br>const rl = createInterface({ input: createReadStream(&#39;dashboard.jsonl&#39;) });<br>let lines = 0;<br>for await (const _ of rl) lines++;<br>console.log(`${lines} lines`);</pre><p>I’m deliberately not assuming anything about the schema of those lines. Look at the file yourself before you write checks against it.</p><p>One more honest check before declaring victory: I opened a real document and made sure the editor still loaded quickly. A smaller dashboard bundle is no use if the editor now feels sluggish the moment someone clicks into a document. The skeleton fallback helped, but you have to look.</p><h3>The agent part</h3><p>Next.js 16.4 also shipped an agent skill, next-bundle-optimizer. I was curious, and a bit skeptical. Install it:</p><pre>npx skills add vercel/next.js --skill next-bundle-optimizer</pre><p>Then invoke it with /next-bundle-optimizer.</p><p><strong>I started in audit mode.</strong> Audit is the default, and it only produces a report, with no source changes. The docs’ prompt is: “Use the next-bundle-optimizer skill to produce a report of the initial load performance of this site.” You can focus it on one route by naming that route in the prompt.</p><p>At a high level, per the Next.js blog, this is what the skill does. It exports saved next analyze snapshots as JSON and rebuilds Turbopack&#39;s module and chunk graphs. It finds large groups of connected modules, traces their import chains, and uses a minimum cut to suggest a small set of import boundaries that would defer them. Then it checks those changes against the source and how the components are used. It can also flag logic that could move to Server Components, duplicate versions of large dependencies, and cases where tree shaking couldn&#39;t be applied.</p><p>That “checks against the source and how components are used” part matters. A suggestion to defer a module is only good if deferring it won’t break the screen that needs it.</p><p><strong>Fix mode needs an explicit request.</strong> /next-bundle-optimizer fix applies proposed changes, reruns the analysis and compares snapshots, and the blog suggests asking the agent to open a pull request for each change. I&#39;d only use it on a branch. And I&#39;d review every change as if a teammate sent it, because that&#39;s effectively what it is.</p><p>For context, the Next.js blog describes how Vercel used it on their own products. Their agent opened a pull request per change, they verified each on a preview deployment, then shipped. The blog’s reported results, which are Vercel’s numbers and not mine: nearly two megabytes of compressed JavaScript cut across v0 and vercel.com. In v0, an experimental code editor loaded eagerly on nearly every page, even for users outside the experiment (about 150 KB saved on most pages), and a centralized dialog registry eagerly loaded heavy dialogs (40 to 650 KB depending on the page). On vercel.com, markdown rendering, syntax highlighting and chart drawing for an agent panel shipped even when the panel wasn’t open (255 KB on the dashboard), and URL parsing code imported through a shared utility file also pulled in an entire observability query engine (125 KB on the deployments page).</p><p>They’re the same shape as my problem: an editor loaded eagerly, a registry importing everything upfront, a panel’s rendering code shipping when the panel is closed, a shared utility file dragging in something huge. Oddly reassuring: we weren’t uniquely sloppy. This is just how these leaks happen.</p><p>Where I kept a human in the loop: choosing what a “light route” is, deciding which things really must stay eager, and checking that deferred code still feels fast when it’s needed. The tooling can find the shortest path to a cut. It can’t know that a particular dialog is the thing users open right after the page loads.</p><h3>Pitfalls I’d warn you about</h3><ul><li>Assuming lazy() or next/dynamic means deferred, when a barrel or shared utils file still statically imports the module.</li><li>Barrel files that re-export heavy components next to tiny helpers.</li><li>Putting dynamic() in a Server Component and expecting code splitting. It isn&#39;t supported there right now.</li><li>Using ssr: false in a Server Component. That&#39;s an error.</li><li>Dialog or modal registries that import every dialog upfront.</li><li>“Helper” files that import a heavy dependency at the top level.</li><li>Trusting the critical-path view without testing, given the footnote about next/dynamic chunks in RSC renders.</li><li>Comparing snapshots taken from different branches or configs. Your diff will lie to you.</li><li>Running the agent in fix mode on main without review.</li><li>Forgetting the analyzer needs Turbopack. If you’re on Webpack, you need @next/bundle-analyzer instead.</li><li>Declaring victory on bundle size without checking that the editor still loads fast once a document is opened.</li></ul><h3>A short aside: TanStack Redact</h3><p>TanStack Redact 0.2.0 was announced on 26 October 2026, the same week. It’s a smaller replacement for React and React DOM in the browser. It works with TanStack Start, Vite, Vinext and Next.js, and with Next.js, React still handles SSR and Server Components. It renders synchronously, without React’s time slicing, and their own post says a heavy render can still delay input.</p><p>That’s a different lever from the one in this post. I’d fix what we ship before swapping the runtime, especially for an editor, where a heavy synchronous render is exactly what you don’t want.</p><h3>What I’d do this week</h3><p><strong>This week:</strong></p><ul><li>Run npx next analyze.</li><li>Open your lightest routes (dashboard, list pages, settings) and check the critical render path with async dependencies filtered out.</li><li>Click any module that shouldn’t be there and read its import chain.</li><li>Kill barrel imports to heavy modules.</li></ul><p><strong>In your PR routine:</strong></p><ul><li>For any dependency or feature PR, save named snapshots before and after, and look at the diff. Two commands, one look.</li></ul><p><strong>Rollout order:</strong></p><ol><li>Audit first, report only. Know what you have.</li><li>Human fixes for the obvious leaks. The barrel import is usually one line.</li><li>Agent fix mode on a branch, reviewing each change and verifying on a preview deployment, then comparing snapshots.</li></ol><p>I had wrapped the editor in next/dynamic and called it done. The boundary was fine. It was the door next to it that was wide open.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2635fe71b073" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our Core Web Vitals Only Described the Landing Page.]]></title>
            <link>https://medium.com/@faisalmujtaba/our-core-web-vitals-only-described-the-landing-page-5384530b37ac?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/5384530b37ac</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[core-web-vitals]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 04:21:24 GMT</pubDate>
            <atom:updated>2026-10-28T04:21:24.242Z</atom:updated>
            <content:encoded><![CDATA[<h3>Our Core Web Vitals Only Described the Landing Page. Chrome’s Soft Navigation Metrics Finally Show the Rest.</h3><p>How I checked CrUX’s new experimental soft-navigation metrics, wired them into our own RUM in a Next.js App Router app, and what I’d watch out for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qO1NbbvlvPGtk-Di" /></figure><p>For a while, our Core Web Vitals report and the way our app felt were telling two different stories.</p><p>The report said things were fine, more or less. Then I’d open a document, click into another one, open the comments panel, and hit a pause I could feel. That pause never showed up anywhere I was looking.</p><p>I build a document workspace in React and Next.js, with a Tiptap editor, comments and realtime collaboration. Nobody lands on a page and stays there. They land on one document, then spend the rest of the session clicking between documents without ever triggering a full page load.</p><p>It took me longer than I’d like to admit to see why the report couldn’t describe that.</p><h3>Hard navigations, soft navigations, and what CrUX did with them</h3><p>A <strong>hard navigation</strong> is the browser loading a page: type a URL, click a normal link, hit refresh. A <strong>soft navigation</strong> is your JavaScript changing what’s on screen and the URL, without the browser doing a real load. Every client-side router in a Next.js App Router app produces these.</p><p>Before this month, CrUX (Chrome’s field dataset, the thing behind PageSpeed Insights and Search Console) measured the hard navigation and not much else. So an entire SPA session got attributed to whatever URL the user landed on.</p><p>For us that meant a session that started on one document and then involved a string of route changes, a pile of typing and a couple of layout shifts from comment lists loading in, all got pinned on that first URL. CLS and INP in particular kept accumulating long after the “page” the report thought they were measuring.</p><p>I had a second problem, and this one was my own fault. Our home-grown RUM tagged each metric with location.href at the moment we sent it. Web vitals can be reported late, and in an SPA the user has often moved on by then. A fair number of our rows were labeled with the wrong page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ran-Hr3bfFCDWIrg" /></figure><h3>What Chrome actually counts as a soft navigation</h3><p>Chrome’s Soft Navigations API is enabled by default from Chrome 151. Their definition has three parts:</p><ul><li>the navigation is initiated by a user action,</li><li>it results in a visible URL change,</li><li>and the interaction results in a visible paint.</li></ul><p>Chrome’s own docs admit this can produce false positives (things your users wouldn’t call a navigation) and false negatives. I’ll come back to that, because it matters for how you read your data.</p><p>Each detected soft navigation produces a soft-navigation performance entry, with a navigationId, the new URL in name, and the interactionId of the interaction that kicked it off. There are also interaction-contentful-paint entries, and soft-navigation entries have getLargestInteractionContentfulPaint().</p><p>One detail that bites people: all timings are relative to the original hard navigation, while a soft navigation’s start time is the start of the interaction. So soft LCP has to be measured relative to that interaction. The web-vitals library handles this for you, which is the main reason I&#39;d use it instead of rolling my own observer.</p><p>Two practical notes. Browsers other than Chromium, and Chrome before 151, won’t report any of this. And the DevTools Performance panel now supports soft navigations in Live Metrics and in the trace view, which is a good way to sanity-check what Chrome thinks your “pages” are.</p><h3>What changed in CrUX</h3><p>The October 2026 CrUX release, published on 13 October, added three experimental metrics:</p><ul><li>experimental_largest_contentful_paint_with_softnavs</li><li>experimental_interaction_to_next_paint_with_softnavs</li><li>experimental_cumulative_layout_shift_with_softnavs</li></ul><p>They’re available in CrUX BigQuery, the CrUX API and the CrUX History API, and they have the same shape as the stable metrics: a histogram and a p75. They blend hard and soft navigations, and soft-nav metrics are reported under the URL the user navigated to, subject to the usual eligibility rules. They also end the hard-navigation CLS and INP after the first soft navigation, instead of letting them run for the whole session.</p><p>The stable Core Web Vitals are unchanged for now. Chrome is aiming to graduate the experimental metrics in May 2027, subject to feedback, and Search Console would then switch to the new data. Soft-nav FCP and navigation types are expected in the November CrUX release.</p><p>So this is a preview. Nothing you’re ranked or judged on has moved yet. But it’s a very good preview.</p><h3>Step 1: Look before you write any code</h3><p>The cheapest check is CrUX Vis. It has an “Include soft navigations” toggle. Flip it for your origin and compare. If the numbers barely move, you may be in the group Chrome mentions: around 70% of origins have little to no soft-navigation traffic, according to Chrome’s blog. If they move a lot, you have an SPA that was being under-described.</p><p>I’m not going to quote our numbers here, but the comparison was enough to convince me it was worth building proper RUM.</p><p>Next, I wanted the stable and experimental p75s side by side. This is a small script against the CrUX API:</p><pre>// scripts/crux-softnavs.ts<br>const API_KEY = process.env.CRUX_API_KEY!;<br>const ENDPOINT = `https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${API_KEY}`;<br> <br>const metrics = [<br>  &quot;largest_contentful_paint&quot;,<br>  &quot;experimental_largest_contentful_paint_with_softnavs&quot;,<br>  &quot;interaction_to_next_paint&quot;,<br>  &quot;experimental_interaction_to_next_paint_with_softnavs&quot;,<br>  &quot;cumulative_layout_shift&quot;,<br>  &quot;experimental_cumulative_layout_shift_with_softnavs&quot;,<br>];<br> <br>async function main() {<br>  const res = await fetch(ENDPOINT, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({<br>      origin: &quot;https://example.com&quot;,<br>      formFactor: &quot;DESKTOP&quot;,<br>      metrics,<br>    }),<br>  });<br> <br>  if (!res.ok) {<br>    throw new Error(`CrUX API error: ${res.status} ${await res.text()}`);<br>  }<br> <br>  const { record } = await res.json();<br> <br>  for (const name of metrics) {<br>    const p75 = record.metrics?.[name]?.percentiles?.p75;<br>    console.log(name.padEnd(58), p75 ?? &quot;no data&quot;);<br>  }<br>}<br> <br>main();</pre><p>Swap the origin for a url if you want a single page, and change formFactor (PHONE, DESKTOP or TABLET) to match where your users are. I used desktop because a document workspace is mostly a desktop product.</p><p>Run it and read the output as pairs. If a stable metric and its experimental twin are close, soft navigations aren’t changing much for that metric. If they’re far apart, that’s the part of the session you couldn’t see before.</p><p>One caveat I’ll repeat later: the experimental metrics blend hard and soft navigations. They’re a different population from the stable ones, not a corrected version of the same one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QYfVWXdkCeRqOSGL" /></figure><h3>Step 2: Put it in our own RUM</h3><p>CrUX tells you what Chrome saw in aggregate. It doesn’t tell you which of your routes is the problem, so I wanted this in our own data too.</p><p>I used the web-vitals package directly (version 6.2.3 when I wrote this). The option that matters is reportSoftNavs: true, which reports metrics per soft navigation where the browser supports it.</p><p>There’s a catch that took me a minute to absorb. Turning on reportSoftNavs changes how the first page load is measured: the initial URL&#39;s CLS and INP are finalized at the first soft navigation. That&#39;s the right behavior for a per-page view, but it means the &quot;traditional&quot; number for that landing page is no longer the one you were collecting.</p><p>The fix is to register two sets of callbacks, one traditional and one soft-nav-aware, and tag each event with which mode it came from. Then you can keep both views and compare them deliberately.</p><p>Here’s the reporter. It’s a client component rendered from the root layout:</p><pre>// components/web-vitals-reporter.tsx<br>&quot;use client&quot;;<br> <br>import { useEffect } from &quot;react&quot;;<br>import { onCLS, onINP, onLCP, type Metric } from &quot;web-vitals&quot;;<br>import { normalizeRoute } from &quot;@/lib/normalize-route&quot;;<br> <br>type Mode = &quot;traditional&quot; | &quot;soft-nav-aware&quot;;<br> <br>function makeSender(mode: Mode) {<br>  return (metric: Metric) =&gt; {<br>    const body = JSON.stringify({<br>      name: metric.name,<br>      value: metric.value,<br>      delta: metric.delta,<br>      id: metric.id,<br>      rating: metric.rating,<br>      navigationType: metric.navigationType,<br>      // navigationURL, not location.href: the metric may be reported late<br>      route: normalizeRoute(metric.navigationURL ?? location.href),<br>      mode,<br>    });<br> <br>    navigator.sendBeacon(&quot;/analytics&quot;, body);<br>  };<br>}<br> <br>export function WebVitalsReporter() {<br>  useEffect(() =&gt; {<br>    const traditional = makeSender(&quot;traditional&quot;);<br>    const softNav = makeSender(&quot;soft-nav-aware&quot;);<br> <br>    onLCP(traditional);<br>    onLCP(softNav, { reportSoftNavs: true });<br> <br>    onINP(traditional);<br>    onINP(softNav, { reportSoftNavs: true });<br> <br>    onCLS(traditional);<br>    onCLS(softNav, { reportSoftNavs: true });<br>  }, []);<br> <br>  return null;<br>}</pre><p>And the layout:</p><pre>// app/layout.tsx<br>import { WebVitalsReporter } from &quot;@/components/web-vitals-reporter&quot;;<br> <br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;WebVitalsReporter /&gt;<br>        {children}<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Two things worth saying about this.</p><p>First, it lives in the root layout on purpose. A layout persists across client-side navigations in the App Router, so the effect runs once per session. Put this in a page-level component and you’ll re-register callbacks on every route change. In dev, React’s Strict Mode will also run the effect twice, so expect some duplicate events locally.</p><p>Second, I used web-vitals directly rather than a framework hook, simply because I needed to pass the reportSoftNavs option and wanted full control over both streams.</p><p>The payload uses metric.navigationType, which can be navigate, reload, back-forward, back-forward-cache, prerender, restore or soft-navigation. That field is what lets you separate the two worlds later. web-vitals also gives you navigationId, navigationStartTime and navigationInteractionId, which I&#39;d add if you want to stitch an INP event back to the interaction that caused it.</p><h3>Step 3: Make the data readable</h3><p>If you ship the reporter above and stop, you’ll open your dashboard and find a row for every document ID your users ever opened. That’s not a dashboard, it’s a log file.</p><p>So I normalize URLs to route patterns:</p><pre>// lib/normalize-route.ts<br>export function normalizeRoute(url: string): string {<br>  const { pathname } = new URL(url, window.location.origin);<br> <br>  return pathname<br>    .replace(/^\/docs\/[^/]+/, &quot;/docs/[id]&quot;)<br>    .replace(/^\/workspaces\/[^/]+/, &quot;/workspaces/[workspaceId]&quot;);<br>}</pre><p>It reads pathname only, so query strings like ?comment= and ?tab= fall away, and a document is a route pattern instead of a row. You&#39;ll want to adapt the replacements to your own route table. It&#39;s boring code and it earns its keep.</p><p>Then three rules for how I read the result:</p><ol><li><strong>Split by </strong><strong>navigationType.</strong> soft-navigation rows and everything else are different populations. Don&#39;t average them.</li><li><strong>Split by </strong><strong>mode.</strong> The traditional stream and the soft-nav-aware stream will disagree about landing-page CLS and INP, by design. That&#39;s the point of keeping both.</li><li><strong>Compare like with like.</strong> A soft LCP and a hard LCP are not the same measurement. For soft navigations, TTFB is reported as 0, and FCP and LCP are the first and largest paints after the navigation. Elements that stay on screen across the navigation don’t count. So a soft-nav load and a hard load of the same page can differ, even if the page looks identical to the user.</li></ol><p>For debugging, it helps to see what Chrome thinks a soft navigation is. This is the console snippet I used:</p><pre>if (PerformanceObserver.supportedEntryTypes.includes(&quot;soft-navigation&quot;)) {<br>  new PerformanceObserver((list) =&gt; {<br>    for (const entry of list.getEntries()) {<br>      console.log(&quot;soft navigation:&quot;, entry.name, entry);<br>    }<br>  }).observe({ type: &quot;soft-navigation&quot;, buffered: true });<br>}</pre><p>I use the observer with buffered: true rather than getEntriesByType, because getEntriesByType is limited to the first 50 buffered entries. That&#39;s plenty for a short test session and a trap for a long-lived app. Our users keep tabs open for days.</p><h3>What the soft-nav view changed about our priorities</h3><p>I want to be careful here, because it’s easy to read too much into early data.</p><p>Chrome’s blog says that for SPA-heavy sites, LCP and CLS tend to look better once soft navigations are counted, and INP improves because it’s measured per page view. It also says that SPA-heavy sites still trail multi-page sites in good INP, and that heavy main-thread JavaScript during route transitions can still cause INP problems.</p><p>That matched what I’d been feeling. If LCP and CLS tend to look kinder under soft navigations, then the thing worth my attention is interaction latency around the moment someone opens a document.</p><p>In our app, that moment is expensive. The editor initializes. A big comment list mounts. Several panels set themselves up. All of it is main-thread work, and it happens right after a click, which is exactly where INP gets measured.</p><p>So the soft-nav view didn’t give me a new villain. It moved the spotlight. Instead of asking whether the landing page was fast enough, I started asking what our document-open path does on the main thread, and which of that work could wait until after the first paint. Editor init and the comment list are where I’m looking first. I’ll write about what I find when I have something real to say.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TIjJ0Z0Ygcb_9voy" /></figure><h3>Pitfalls</h3><p>A list of things that bit me or nearly did:</p><ul><li><strong>Using </strong><strong>location.href instead of </strong><strong>navigationURL.</strong> Metrics get reported late. In an SPA, the user has often moved on by then, and you&#39;ve labeled the metric with the wrong page.</li><li><strong>Mixing the two streams in one chart.</strong> The traditional and soft-nav-aware streams measure the first page differently. Overlay them and you’ll get a number that means nothing.</li><li><strong>Comparing soft LCP to hard LCP as if they were the same.</strong> Different starting points, and elements that persist across the navigation don’t count.</li><li><strong>Forgetting the sample bias.</strong> Only Chromium 151 and later reports soft navigations. Your soft-nav data describes those users, not everyone.</li><li><strong>Letting URL-only UI changes count as pages.</strong> Under Chrome’s definition, a ?comment= or ?tab= parameter updated on click may well count as a soft navigation. Check what your app treats as a &quot;page&quot; before you trust the per-route numbers.</li><li><strong>One metric row per document ID.</strong> Normalize routes, or your dashboard becomes unusable.</li><li><strong>Registering callbacks in a component that re-mounts per route.</strong> Put the reporter in the root layout, once.</li><li><strong>Using </strong><strong>getEntriesByType past 50 entries.</strong> Use an observer.</li><li><strong>Panicking, or celebrating, when the experimental numbers move.</strong> The stable Core Web Vitals don’t change until at least May 2027, and that’s if feedback goes well. These numbers are a preview, not a verdict.</li></ul><h3>What I’d do, and in what order</h3><h4>This week</h4><ul><li>Open CrUX Vis for your origin and flip “Include soft navigations”. See whether anything moves.</li><li>Run the CrUX API script and read the stable and experimental p75s as pairs.</li><li>Open the DevTools Performance panel in Live Metrics and click around your own app. Check that Chrome’s idea of a soft navigation matches yours, especially for URL-only changes.</li></ul><h4>Before May 2027</h4><ul><li>Ship the reporter, with both callback sets and the mode and navigationType tags, so you have your own history before the experimental metrics graduate.</li><li>Normalize routes and build the dashboards split by navigationType and mode.</li><li>Watch the November CrUX release for soft-nav FCP and navigation types, and fold them in when they land.</li><li>Pick the one or two route transitions that matter most and look at the main-thread work around them.</li></ul><h4>Rollout order</h4><ol><li>Look at CrUX Vis and the API output. No code, no risk.</li><li>Ship the reporter (sampled, if your traffic is large), with route normalization from day one.</li><li>Build the split dashboards before you read any conclusions into the data.</li><li>Only then change your priorities, and keep them qualitative until you’ve seen a few weeks of your own numbers.</li></ol><p>The real shift for me wasn’t a number. It was that for the first time, the report was at least capable of describing the app people actually use.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5384530b37ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our AI Answers Looked Broken While They Streamed. The Model Was Fine.]]></title>
            <link>https://medium.com/@faisalmujtaba/our-ai-answers-looked-broken-while-they-streamed-the-model-was-fine-1e3a1919893e?source=rss-196f4d4e1b79------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e3a1919893e</guid>
            <category><![CDATA[frontend-engineering]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[ai-streaming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Faisal Mujtaba]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 04:35:12 GMT</pubDate>
            <atom:updated>2026-10-26T04:35:12.128Z</atom:updated>
            <content:encoded><![CDATA[<p>Throttling updates, switching to a streaming-aware Markdown renderer, and treating model output as untrusted content in a React/Next.js “Ask AI” panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xEtwz__9gi3ufxV5" /></figure><p>We shipped an “Ask AI” side panel in our document workspace. It sits right next to the Tiptap editor, streams answers token by token, and on the first day it looked terrible.</p><p>Not wrong. The answers were fine. They just looked <em>broken</em> while they were arriving.</p><p>Here’s what people saw. A stray ** would flash on screen, then vanish a moment later when the closing pair showed up. A backtick would appear, sit there like a typo, and eventually turn into inline code. Links showed up as [some text](https://exa and stayed that way for a few frames. The worst one was code. The model would open a code fence, and until the closing fence arrived, everything after it got swallowed. The rest of the message rendered as one giant code block, then snapped back to normal.</p><p>And on long answers, typing in the editor next to the panel started to feel sluggish. Nothing was frozen, but the keystrokes felt like they were wading through something.</p><p>I spent a while blaming the model, then the network, then the editor. It was none of those. It was how I was rendering Markdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bNTbtPXmhH9vus-V" /></figure><h3>Why it happens</h3><p>Here’s what I had:</p><pre>import ReactMarkdown from &#39;react-markdown&#39;;<br> <br>function AskAiMessage({ part }: { part: { text: string } }) {<br>  return &lt;ReactMarkdown&gt;{part.text}&lt;/ReactMarkdown&gt;;<br>}</pre><p>That’s a perfectly reasonable component. It’s also built on an assumption that doesn’t hold mid-stream: the string you hand it is a complete Markdown document.</p><p>During streaming it never is. Halfway through a word, **bol isn&#39;t bold text, it&#39;s broken Markdown, and a normal parser treats it that way. A code fence that opens but never closes is, by the rules, a code block that runs to the end of the document. So the parser did exactly what it was told. I was feeding it half-finished input and expecting it to guess my intent.</p><p>The second problem is separate. Every chunk that arrives makes the accumulated string longer, and my component re-parsed and re-rendered the entire message each time. For a short answer, nobody cares. For a long one, it’s a lot of repeated work on the main thread, and the editor next to it is competing for that same thread.</p><p>So there were two problems: the renderer didn’t understand partial input, and I was rendering far more often than a human can perceive. I fixed those separately, then added a third fix I should have thought about on day one.</p><h3>Fix 1: stop rendering on every chunk</h3><p>The AI SDK’s useChat has a throttle option. It&#39;s a number of milliseconds, it works in React and Vue, and it reduces how often the UI updates without delaying stream processing or callbacks. Status and error updates include the latest messages, so the final message still renders in full.</p><pre>&#39;use client&#39;;<br> <br>import { useChat } from &#39;@ai-sdk/react&#39;;<br>import { DefaultChatTransport } from &#39;ai&#39;;<br> <br>export function AskAiPanel() {<br>  const { messages, sendMessage } = useChat({<br>    transport: new DefaultChatTransport({ api: &#39;/api/chat&#39; }),<br>    throttle: 50,<br>  });<br> <br>  // render messages[].parts below<br>}</pre><p>That’s one line, and it’s the cheapest win in this whole post. If you’ve seen experimental_throttle in older code or blog posts, that&#39;s the previous, now-deprecated name for the same thing.</p><p>The editor felt better right away. It didn’t fully fix the jank, because the visual glitches were a renderer problem. But it took pressure off the main thread, and it’s the change I’d make first on any streaming UI.</p><p>One caveat I’ll repeat later: throttling smooths how often you <em>render</em>. It does nothing if your transport itself is slow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sC6vR_SI_otuUKAL" /></figure><h3>Fix 2: use a renderer that expects incomplete input</h3><p>I looked at two options. They solve the same problem with different philosophies, so I’ll walk through both.</p><h4>2a: Streamdown</h4><p>Streamdown (streamdown on npm, from Vercel) is billed as a drop-in replacement for react-markdown, designed for AI streaming. It handles incomplete syntax such as unclosed bold, partial code blocks, and unterminated links, using a library called remend. It also memoizes Markdown blocks, so blocks that haven&#39;t changed can skip re-rendering. Safe rendering is built on rehype-harden, and GFM (tables, task lists, strikethrough) comes through remark-gfm.</p><p>The swap was almost boring:</p><pre>import { Streamdown } from &#39;streamdown&#39;;<br>import { code } from &#39;@streamdown/code&#39;;<br>import &#39;streamdown/styles.css&#39;;<br> <br>type TextPart = { type: &#39;text&#39;; text: string; state?: &#39;streaming&#39; | &#39;done&#39; };<br> <br>export function AskAiMessage({ part }: { part: TextPart }) {<br>  return (<br>    &lt;Streamdown<br>      plugins={{ code }}<br>      isAnimating={part.state === &#39;streaming&#39;}<br>    &gt;<br>      {part.text}<br>    &lt;/Streamdown&gt;<br>  );<br>}</pre><p>Two details matter here.</p><p>First, isAnimating. Tie it to part.state === &#39;streaming&#39;. It lets Streamdown disable interactive controls, like copy buttons, until the text is complete. I&#39;ll admit I forgot this on my first pass and ended up with a copy button on a half-written code block. Clicking it copied half a function.</p><p>Second, the plugin. @streamdown/code gives you Shiki highlighting. There are also plugins for mermaid (@streamdown/mermaid), math (@streamdown/math, which needs import &#39;katex/dist/katex.min.css&#39;), and CJK text (@streamdown/cjk). You pass them in as plugins={{ code, mermaid }}.</p><p>If you’re on Tailwind v4, add this to your globals.css so the classes Streamdown uses don&#39;t get purged:</p><pre>@source &#39;../node_modules/streamdown/dist/*.js&#39;;</pre><p>There’s also mode=&quot;static&quot; for content that&#39;s already complete, like docs pages. Use that where nothing is streaming.</p><h4>2b: TanStack Markdown</h4><p>The other option is @tanstack/markdown, which hit 1.0.0 on 1 October 2026 alongside TanStack Highlight. It works differently on purpose.</p><p>There’s no incremental parser state. Every update parses the complete accumulated string synchronously. That sounds like the wasteful thing I just complained about, but the parser is small and the streaming extension handles the awkward parts.</p><pre>import { Markdown } from &#39;@tanstack/markdown/react&#39;;<br>import { streamingMarkdownExtension } from &#39;@tanstack/markdown/extensions/streaming&#39;;<br> <br>// Defined outside the component, on purpose<br>const streamingExtensions = [streamingMarkdownExtension()];<br> <br>export function AskAiMessage({ text }: { text: string }) {<br>  return (<br>    &lt;Markdown<br>      extensions={streamingExtensions}<br>      frontmatter={false}<br>      headingIds={false}<br>    &gt;<br>      {text}<br>    &lt;/Markdown&gt;<br>  );<br>}</pre><p>Here’s what the streaming extension does, as I understand it from the docs:</p><ul><li>Empty trailing headings, blockquotes, and list items are suppressed while they’re incomplete. You don’t see a lonely ## or - flash by.</li><li>An unclosed code fence renders all the code accumulated after the opening fence, as code. That’s the opposite of my original bug: the code so far shows up as code, not as a message-eating mystery.</li><li>Unclosed emphasis, code spans, and links stay as literal text until the closing delimiter arrives. So you may still briefly see **bol, but it&#39;s honest text, and it becomes bold when the pair closes.</li><li>Completed paragraphs, lists, tables, quotes, and fenced code are left alone.</li></ul><p>One thing to know: finishing a table delimiter row or an inline construct can legitimately restructure the latest block. That’s the nature of reparsing, not a bug.</p><p>For code, React keeps completed groups of plain code lines in stable text nodes, so appending code only updates the trailing group.</p><p>For syntax highlighting, you build a highlighter with createHighlighter from @tanstack/highlight/core, register only the languages you expect, wrap it with createTanStackMarkdownHighlighter from @tanstack/highlight/markdown, and pass the result as the highlighter prop:</p><pre>// markdown-highlighter.ts<br>import { createHighlighter } from &#39;@tanstack/highlight/core&#39;;<br>import { ts } from &#39;@tanstack/highlight/languages/ts&#39;;<br>import { tsx } from &#39;@tanstack/highlight/languages/tsx&#39;;<br>import { createTanStackMarkdownHighlighter } from &#39;@tanstack/highlight/markdown&#39;;<br> <br>const highlighter = createHighlighter({ languages: [ts, tsx] });<br> <br>export const highlightMarkdownCode = createTanStackMarkdownHighlighter(highlighter);<br> <br>// Then: &lt;Markdown highlighter={highlightMarkdownCode} extensions={streamingExtensions} ... /&gt;</pre><p>Unknown languages degrade to escaped plain text, which is the right failure mode.</p><p>The docs also advise batching very small transport tokens into normal UI updates when responses are long or tokens arrive very fast. That’s exactly what the throttle option from Fix 1 does, so the two pair naturally.</p><p>According to its npm page, the parser is about 5.2 KB gzipped, the React adapter about 7 KB gzipped, and there are zero runtime dependencies. I haven’t measured those myself, so treat them as vendor numbers.</p><p>It is also intentionally <em>not</em> full CommonMark, GFM, MDX, or HTML sanitization. If your model output leans on a feature outside its syntax profile, test with real answers before you commit.</p><h3>How I chose</h3><p>I don’t have a universal winner, and I’d be suspicious of anyone who claims one.</p><p>Streamdown fits if:</p><ul><li>you already have react-markdown and want the least disruptive migration</li><li>you need GFM tables, math, or mermaid diagrams</li><li>you don’t mind a heavier dependency tree for that coverage</li></ul><p>TanStack Markdown fits if:</p><ul><li>you want a tiny, dependency-free renderer</li><li>your answers are mostly prose, lists, inline code, and fenced code</li><li>you&#39;re comfortable with a narrower syntax profile, and you&#39;d rather know exactly what it parses</li></ul><p>For a document workspace, our answers are mostly prose and code, with the occasional table. Either would have worked. What I&#39;d actually recommend is rendering a few dozen real answers from your own logs through both before deciding, because the differences show up in <em>your</em> content, not in a README.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iQKXxgCaRLXdbMB1" /></figure><h3>Fix 3: the model&#39;s output is untrusted</h3><p>This is the one I&#39;d have skipped if I hadn&#39;t been in the Markdown code already.</p><p>Model output is not your content. It can be shaped by whatever the model read, including the user&#39;s prompt, a pasted document, or a retrieved page. If any of that contains instructions, the model may repeat them back as links, images, or raw HTML. If your renderer faithfully turns all of it into DOM, you&#39;ve handed an attacker a way to put elements on your page.</p><p>Both options have sensible defaults, but the details differ.</p><p>With Streamdown, rendering is built with rehype-harden, so you start from a safer baseline than a bare Markdown-to-HTML pipeline.</p><p>With TanStack Markdown:</p><ul><li>Leave allowHtml disabled. It&#39;s tempting to enable it &quot;to match the old renderer.&quot; Don&#39;t.</li><li>Executable URL protocols are removed and raw HTML is escaped by default.</li><li>Only use highlighters that escape source code.</li><li>Disable frontmatter for AI responses. A closing --- could make the renderer reinterpret the start of the message as metadata.</li><li>Disable heading IDs. IDs would change as a heading grows during streaming, which makes anchors unstable.</li></ul><p>Whichever one you choose, think about outbound links and remote images as a policy decision. A remote image is a request your user&#39;s browser makes on the model&#39;s behalf. TanStack Markdown leaves link and image policy to you via component overrides, so that&#39;s where I&#39;d decide things like whether external links open in a new tab, whether they go through a confirmation, and whether remote images are allowed at all. I won&#39;t pretend there&#39;s a one-size answer; for us, the default for anything the model produced is &quot;show the text, don&#39;t auto-load things.&quot;</p><h3>Pitfalls I hit, or almost hit</h3><ul><li><strong>Defining the extensions array inline.</strong> Create streamingExtensions once, outside the component. A new array every render defeats the point.</li><li><strong>Forgetting </strong><strong>isAnimating.</strong> With Streamdown, you get copy buttons on half-written code. Tie it to part.state === &#39;streaming&#39;.</li><li><strong>Turning on </strong><strong>allowHtml &quot;to match the old renderer.&quot;</strong> The old renderer&#39;s behavior isn&#39;t a reason to loosen the new one.</li><li><strong>Unstable keys.</strong> Wrap each part with a key built from message.id plus the part index. Otherwise React may remount content mid-stream.</li><li><strong>Expecting a streaming renderer to fix a slow transport.</strong> It makes partial text look good. It can&#39;t make tokens arrive faster.</li><li><strong>Assuming TanStack Markdown supports every GFM feature.</strong> It doesn&#39;t claim to.</li><li><strong>Leaving heading IDs on</strong> for streamed content.</li></ul><h3>What I&#39;d do, in order</h3><p>First, add throttle to useChat. It&#39;s one line, and it helps no matter what renderer you use.</p><p>Second, fix the key on each message part and tie loading state to part.state. That&#39;s cheap and removes a whole class of flicker.</p><p>Third, pick a renderer. If you&#39;re on react-markdown today and your answers include tables, math, or diagrams, Streamdown is the smoother path. If your answers are mostly prose and code and you like small dependencies, try TanStack Markdown, with frontmatter and heading IDs off. Run real answers through whichever one you pick before shipping.</p><p>Fourth, do the security pass: HTML off, a decision about links and remote images, and a highlighter that escapes its input.</p><p>Last, if it still feels sluggish, profile the transport and the rest of your page before blaming Markdown again. I did that in the wrong order, and I&#39;d rather you didn&#39;t.</p><p>The funny part is that nothing about the model changed. The answers were the same before and after. They just stopped <em>looking</em> broken, and that turned out to matter more than I expected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e3a1919893e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>