<?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">
    <channel>
        <title><![CDATA[Build with Matija]]></title>
        <description><![CDATA[Insights, tutorials, and expert guides to help you grow your business and master your craft.]]></description>
        <link>https://www.buildwithmatija.com</link>
        <generator>RSS for Node</generator>
        <lastBuildDate>Mon, 09 Nov 2026 15:01:25 GMT</lastBuildDate>
        <atom:link href="https://www.buildwithmatija.com/feed.xml" rel="self" type="application/rss+xml"/>
        <pubDate>Mon, 09 Nov 2026 15:01:25 GMT</pubDate>
        <copyright><![CDATA[© 2026 Build with Matija]]></copyright>
        <language><![CDATA[en]]></language>
        <item>
            <title><![CDATA[Payload CMS 4 for Business Owners: What It Means for Your Team and Budget]]></title>
            <description><![CDATA[<p>Product manager, designer, or the person who signs off on the website budget?</p>
<p>This is the guide for you. It explains what Payload 4 means for your team, your budget, and your risk, without a line of code. If you are the developer, the <a href="/blog/payload-4-0">technical breakdown of Payload 4</a> is the one you want.</p>
<h2>The short answer</h2>
<p>Payload 4 is the next major version of the CMS, and it is not finished. As of October 2026 it exists only as test builds. The most recent stable version is still Payload 3.</p>
<p>So here is what that means in practice:</p>
<ul>
<li><strong>Nothing needs to happen this quarter</strong> except planning. Your site is fine where it is.</li>
<li><strong>The benefits are real</strong>, and they are mostly about the editing experience and safer defaults.</li>
<li><strong>The cost is the upgrade itself</strong>, not the software. Payload is free to use, but moving a real site to a new major version is a project.</li>
<li><strong>Waiting is a legitimate decision</strong>, not a failure to keep up.</li>
</ul>
<p>The rest of this article explains each of those points so you can decide for yourself, and ask the right questions when your developer or agency brings it up.</p>
<blockquote>
<p>[!TOOL]
<strong>Payload 4 Upgrade Readiness &amp; Cost Estimator</strong></p>
<p>Unsure whether your site needs an early trial branch or can wait for GA? Answer 5 quick questions about your custom code, database state, and runtime constraints to get an instant readiness verdict, 5-pillar effort breakdown, and realistic budget range in under 90 seconds.</p>
<p><a href="/tools/payload-4-upgrade-quiz">Launch 90-Second Estimator →</a></p>
</blockquote>
<h2>What is changing, and what it means for you</h2>
<p>Most of the Payload 4 announcement is written for engineers. Translated into business terms, the changes fall into a handful of outcomes.</p>
<pre><code class="language-mermaid">flowchart LR
    subgraph C [&quot;What&#39;s changing&quot;]
        C1[&quot;Safer data access&lt;br/&gt;by default&quot;]
        C2[&quot;Content history&lt;br/&gt;on by default&quot;]
        C3[&quot;Folders, tags&lt;br/&gt;and a new admin&quot;]
        C4[&quot;Easier admin&lt;br/&gt;theming&quot;]
    end
    subgraph O [&quot;What it means for you&quot;]
        O1[&quot;Lower risk of&lt;br/&gt;accidental exposure&quot;]
        O2[&quot;Undo and&lt;br/&gt;audit trail&quot;]
        O3[&quot;Editors find&lt;br/&gt;content faster&quot;]
        O4[&quot;Admin that&lt;br/&gt;matches your brand&quot;]
    end
    C1 --&gt; O1
    C2 --&gt; O2
    C3 --&gt; O3
    C4 --&gt; O4
</code></pre>
<p><em>Each change on the left has a business reason behind it. The sections below explain the trade-off that comes with each one.</em></p>
<h3>Safer by default</h3>
<p>In Payload 3, code running inside your own site could read and change content while ignoring your permission rules, unless a developer remembered to switch the rules on. In Payload 4, the rules apply unless a developer deliberately says otherwise.</p>
<p>That is a real security improvement. It reduces the chance that a custom form, a scheduled task, or an internal tool quietly exposes data it should not.</p>
<p>The trade-off is that anything built on the old behavior needs to be reviewed. Imports, scheduled jobs, and internal tools that relied on the shortcut can stop working, or return empty results, until a developer fixes them.</p>
<h3>Content history on by default</h3>
<p>Payload 4 keeps a history of changes for your content automatically. In Payload 3 you had to switch this on collection by collection. That gives you an undo button and an audit trail: what changed, and what it looked like before.</p>
<p>Two things to know. First, it adds database tables, so it is a database change you should plan for. Teams with very large, high-turnover data can opt out for those areas. Second, content history follows the same viewing rules as the content itself. If a page is publicly readable, its old versions can be too, unless your developer restricts them. If you have content that was once public and later pulled back, ask about this.</p>
<p>Drafts and scheduled publishing are a separate setting and remain off by default.</p>
<h3>A better admin for editors and designers</h3>
<p>The admin panel gets its biggest redesign since Payload 3. Folders and tags are built in, so editors can organize pages and media into trees instead of paging through long flat lists. For large content libraries, that is the difference between finding something in seconds and giving up and asking a colleague.</p>
<p>Lists also load faster on big collections, because the admin now fetches only the columns an editor is actually looking at.</p>
<p>For designers, rebranding the admin gets simpler. Colors, radius, and borders are controlled by a shared set of design settings rather than hand-written stylesheets. If you want custom screens inside the admin built with modern styling tools, those no longer clash with the admin&#39;s own styles.</p>
<h3>AI assistants that work with your content</h3>
<p>Payload 4 has first-class support for connecting AI assistants to your CMS. The assistant acts as a specific user and is held to that user&#39;s permissions.</p>
<p>One caution. In Payload 4, the built-in content tools are switched on automatically unless someone turns them off. That is not a security hole, since permission checks still apply, but it is a decision. Ask your developer what is exposed to AI tools on your site, and whether that matches what you intend.</p>
<h3>More flexibility in the technology around it</h3>
<p>Payload 4 starts to separate the CMS from the framework it runs in. Next.js remains the main, proven path. Support for an alternative, TanStack Start, exists only as an early experiment.</p>
<p>If you are not already thinking about changing your website framework, ignore this one for now. It is a sign of direction, not a reason to move.</p>
<h2>A scenario: someone published the wrong price</h2>
<!-- bwm:slider payload-4-for-business-owners/price-incident-undo -->
<div data-slider="true" data-slider-id="payload-4-for-business-owners/price-incident-undo" data-slider-source="video/src/articles/payload-4-for-business-owners/price-incident-undo">
  <img src="https://img.buildwithmatija.com/api/images/f9qq9abe/file/original" alt="The Incident: Wrong Price Goes Live: An editor updates a pricing tier and publishes a typo: $19 instead of $190." title="The Incident: Wrong Price Goes Live" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/2gmganuf/file/original" alt="The Upgrade Difference: Payload 3 vs 4: In Payload 3, versioning was manual. In Payload 4, version history is active by default." title="The Upgrade Difference: Payload 3 vs 4" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/lnx9pwoj/file/original" alt="The Resolution: Reverted in 60 Seconds: The editor opens version history, picks yesterday's revision, and restores without code or panic." title="The Resolution: Reverted in 60 Seconds" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/rjtf5w1u/file/original" alt="Business Value: Peace of Mind by Default: 1-click undo, full audit trail, and zero emergency developer overhead." title="Business Value: Peace of Mind by Default" width="1080" height="1080" />
</div>
<!-- /bwm:slider --><p>This is where content history stops being abstract.</p>
<p>An editor updates a product page and accidentally publishes the wrong price. On a site without content history, the fix is a developer digging through a database backup, or an editor trying to remember what the old number was.</p>
<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    actor Editor as Editor
    participant CMS as Payload admin
    participant History as Version history
    participant Site as Live website
    Editor-&gt;&gt;CMS: Saves page with the wrong price
    CMS-&gt;&gt;History: Keeps the previous version
    CMS-&gt;&gt;Site: Wrong price goes live
    Editor-&gt;&gt;History: Opens history, picks yesterday&#39;s version
    History-&gt;&gt;CMS: Restores the earlier version
    CMS-&gt;&gt;Site: Correct price is back
</code></pre>
<p><em>With history switched on, the fix takes minutes and does not need a developer. This only works for content types where history is enabled, so choose them deliberately.</em></p>
<h2>What this means for your role</h2>
<h3>If you are a product manager</h3>
<p>You have nothing to schedule until a stable release exists. What you can do now is ask for a trial upgrade estimate, so that when stable lands you already know the size of the project. Also list the workarounds you maintain today, such as extra plugins for folders or page trees. Some of them may become unnecessary.</p>
<h3>If you are a designer</h3>
<p>Expect a refreshed admin interface that your editors will need a short time to get used to. If your brand lives inside custom admin screens, plan time to check them against the new styling system. The upside is that theming becomes easier, and custom views are less fragile.</p>
<h3>If you are a business owner</h3>
<p>Your decisions are timing and risk. The safe default is to stay on Payload 3 in production, plan the move, and schedule it for when a stable release exists and your business calendar has room for it. If your team handles sensitive data, the safer permission defaults are a good reason to want Payload 4 eventually.</p>
<p>For the wider question of how much control your marketing team should have, see <a href="/blog/marketing-cms-control-controlled-autonomy-model">how to give marketing control without losing consistency</a>.</p>
<h2>What the upgrade actually costs</h2>
<p>Payload is open source, so there is no licence fee. The cost is the time to move your site safely. A few things decide how large that is:</p>
<pre><code class="language-mermaid">flowchart TD
    P[&quot;Upgrade project&quot;] --&gt; A[&quot;Custom code review&lt;br/&gt;access rules, scripts, jobs&quot;]
    P --&gt; B[&quot;Database changes&lt;br/&gt;history tables, migrations&quot;]
    P --&gt; C[&quot;Hosting and software&lt;br/&gt;version upgrades&quot;]
    P --&gt; D[&quot;Content conversion&lt;br/&gt;if on the old editor&quot;]
    P --&gt; E[&quot;Testing on a&lt;br/&gt;staging copy&quot;]
</code></pre>
<p><em>A site with little custom code is a small project. A site with many integrations, scheduled jobs, and custom admin screens is a larger one. A trial upgrade on a copy of your site turns this into a real number.</em></p>
<p>An automatic tool handles many of the mechanical changes. It does not make the judgment calls: which jobs should bypass permissions, which content types should keep history, and whether a generated database change is safe to apply. Those still need an experienced developer.</p>
<p>Two further items catch people out. Payload 4 needs newer versions of the software your site runs on, so your hosting may need an upgrade. And if your content is still stored in Payload&#39;s older text editor, that content has to be converted before you can move.</p>
<p>I won&#39;t give you a price here. Anyone who quotes a number without looking at your site is guessing.</p>
<h2>The path to a safe rollout</h2>
<p>The sensible route is a gated one. Nothing touches production until a stable version exists and you have seen a trial on your own data.</p>
<pre><code class="language-mermaid">flowchart LR
    A[&quot;Today&lt;br/&gt;Production on 3.x&quot;] --&gt; B[&quot;Trial branch&lt;br/&gt;Audit and estimate&quot;]
    B --&gt; C[&quot;Budget and&lt;br/&gt;risk review&quot;]
    C --&gt; D{&quot;Stable Payload 4&lt;br/&gt;released?&quot;}
    D --&gt;|&quot;Not yet&quot;| W[&quot;Stay on 3.x&lt;br/&gt;and re-check&quot;]
    D --&gt;|&quot;Yes&quot;| E[&quot;Staged rollout&lt;br/&gt;test copy first&quot;]
    E --&gt; F[&quot;Production&quot;]
</code></pre>
<p><em>The gate is the stable release. Everything before it is planning and learning, which costs far less than a rushed migration.</em></p>
<h2>Should you upgrade? A decision guide</h2>
<pre><code class="language-mermaid">flowchart TD
    A{&quot;Is a stable&lt;br/&gt;Payload 4 released?&quot;} --&gt;|&quot;No&quot;| B[&quot;Keep production&lt;br/&gt;on Payload 3&quot;]
    B --&gt; C{&quot;Lots of custom code,&lt;br/&gt;jobs or admin screens?&quot;}
    C --&gt;|&quot;Yes&quot;| D[&quot;Plan a trial branch&lt;br/&gt;and audit now&quot;]
    C --&gt;|&quot;No&quot;| E[&quot;Wait for stable,&lt;br/&gt;then schedule the move&quot;]
    A --&gt;|&quot;Yes&quot;| F{&quot;Need folders, history&lt;br/&gt;or AI features soon?&quot;}
    F --&gt;|&quot;Yes&quot;| G[&quot;Budget an&lt;br/&gt;upgrade project&quot;]
    F --&gt;|&quot;No&quot;| H[&quot;Upgrade at your next&lt;br/&gt;planned maintenance&quot;]
</code></pre>
<p><em>Today you are on the &quot;No&quot; branch. The only question is whether your site is complicated enough to justify starting the trial early.</em></p>
<blockquote>
<p>[!TOOL]
<strong>Evaluate Your Migration Path</strong></p>
<p>The <a href="/tools/payload-4-upgrade-quiz">Payload 4 Upgrade Readiness &amp; Cost Estimator</a> runs through this decision tree in under 90 seconds. It evaluates your custom code, database state, and runtime constraints to give you an instant readiness verdict, estimated hours, and a realistic budget range.</p>
<p><a href="/tools/payload-4-upgrade-quiz">Launch 90-Second Estimator →</a></p>
</blockquote>
<h2>Questions to ask your developer or agency</h2>
<p>Bring these to your next conversation. Good answers are specific to your site, not general reassurance.</p>
<ol>
<li>Which parts of our site run custom code that talks to the CMS directly, and have they been checked against the new permission defaults?</li>
<li>Which content types should keep a history, and who should be allowed to see old versions?</li>
<li>Is any of our content still in the older rich-text editor, and what would converting it involve?</li>
<li>Are all the plugins we depend on ready for Payload 4?</li>
<li>What hosting and software upgrades would we need, and who owns them?</li>
<li>Can you run a trial upgrade on a copy of our site and give us an estimate before we commit?</li>
</ol>
<h2>Where to go from here</h2>
<p>Payload 4 is a good direction, and it is not yet a decision you have to make. Stay on Payload 3, keep your site healthy, and use the waiting time to find out how big your upgrade would be.</p>
<p>If you want a clear answer for your specific site, a <a href="/payload-cms-audit">Payload CMS audit</a> will tell you what an upgrade would involve before you commit to anything. For a bigger change of platform, see <a href="/payload-cms-migration">Payload CMS migration</a>, or work with an experienced <a href="/payload-cms-developer">Payload CMS developer</a>. If you are weighing up whether outside help is worth the cost, <a href="/blog/what-you-pay-for-senior-cms-consultant">what a senior CMS consultant is actually paid for</a> is a good place to start, and <a href="/blog/cms-migration-triage-7-outcomes">the seven outcomes of a CMS migration triage</a> shows how those decisions usually play out.</p>
<p>Your developers can find the full technical detail, with the official migration guide, in the <a href="/blog/payload-4-0">Payload 4 technical breakdown</a>. For the media-library side of the picture, see <a href="/blog/payload-dam-what-exists-today-coming-4-0">what Payload offers for digital asset management today</a>.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/payload-4-for-business-owners</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/payload-4-for-business-owners</guid>
            <category><![CDATA[Payload]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;Product manager, designer, or the person who signs off on the website budget?&lt;/p&gt;
&lt;p&gt;This is the guide for you. It explains what Payload 4 means for your team, your budget, and your risk, without a line of code. If you are the developer, the &lt;a href=&quot;/blog/payload-4-0&quot;&gt;technical breakdown of Payload 4&lt;/a&gt; is the one you want.&lt;/p&gt;
&lt;h2&gt;The short answer&lt;/h2&gt;
&lt;p&gt;Payload 4 is the next major version of the CMS, and it is not finished. As of October 2026 it exists only as test builds. The most recent stable version is still Payload 3.&lt;/p&gt;
&lt;p&gt;So here is what that means in practice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Nothing needs to happen this quarter&lt;/strong&gt; except planning. Your site is fine where it is.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The benefits are real&lt;/strong&gt;, and they are mostly about the editing experience and safer defaults.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The cost is the upgrade itself&lt;/strong&gt;, not the software. Payload is free to use, but moving a real site to a new major version is a project.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Waiting is a legitimate decision&lt;/strong&gt;, not a failure to keep up.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The rest of this article explains each of those points so you can decide for yourself, and ask the right questions when your developer or agency brings it up.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[!TOOL]
&lt;strong&gt;Payload 4 Upgrade Readiness &amp;amp; Cost Estimator&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Unsure whether your site needs an early trial branch or can wait for GA? Answer 5 quick questions about your custom code, database state, and runtime constraints to get an instant readiness verdict, 5-pillar effort breakdown, and realistic budget range in under 90 seconds.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;/tools/payload-4-upgrade-quiz&quot;&gt;Launch 90-Second Estimator →&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;What is changing, and what it means for you&lt;/h2&gt;
&lt;p&gt;Most of the Payload 4 announcement is written for engineers. Translated into business terms, the changes fall into a handful of outcomes.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
    subgraph C [&amp;quot;What&amp;#39;s changing&amp;quot;]
        C1[&amp;quot;Safer data access&amp;lt;br/&amp;gt;by default&amp;quot;]
        C2[&amp;quot;Content history&amp;lt;br/&amp;gt;on by default&amp;quot;]
        C3[&amp;quot;Folders, tags&amp;lt;br/&amp;gt;and a new admin&amp;quot;]
        C4[&amp;quot;Easier admin&amp;lt;br/&amp;gt;theming&amp;quot;]
    end
    subgraph O [&amp;quot;What it means for you&amp;quot;]
        O1[&amp;quot;Lower risk of&amp;lt;br/&amp;gt;accidental exposure&amp;quot;]
        O2[&amp;quot;Undo and&amp;lt;br/&amp;gt;audit trail&amp;quot;]
        O3[&amp;quot;Editors find&amp;lt;br/&amp;gt;content faster&amp;quot;]
        O4[&amp;quot;Admin that&amp;lt;br/&amp;gt;matches your brand&amp;quot;]
    end
    C1 --&amp;gt; O1
    C2 --&amp;gt; O2
    C3 --&amp;gt; O3
    C4 --&amp;gt; O4
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Each change on the left has a business reason behind it. The sections below explain the trade-off that comes with each one.&lt;/em&gt;&lt;/p&gt;
&lt;h3&gt;Safer by default&lt;/h3&gt;
&lt;p&gt;In Payload 3, code running inside your own site could read and change content while ignoring your permission rules, unless a developer remembered to switch the rules on. In Payload 4, the rules apply unless a developer deliberately says otherwise.&lt;/p&gt;
&lt;p&gt;That is a real security improvement. It reduces the chance that a custom form, a scheduled task, or an internal tool quietly exposes data it should not.&lt;/p&gt;
&lt;p&gt;The trade-off is that anything built on the old behavior needs to be reviewed. Imports, scheduled jobs, and internal tools that relied on the shortcut can stop working, or return empty results, until a developer fixes them.&lt;/p&gt;
&lt;h3&gt;Content history on by default&lt;/h3&gt;
&lt;p&gt;Payload 4 keeps a history of changes for your content automatically. In Payload 3 you had to switch this on collection by collection. That gives you an undo button and an audit trail: what changed, and what it looked like before.&lt;/p&gt;
&lt;p&gt;Two things to know. First, it adds database tables, so it is a database change you should plan for. Teams with very large, high-turnover data can opt out for those areas. Second, content history follows the same viewing rules as the content itself. If a page is publicly readable, its old versions can be too, unless your developer restricts them. If you have content that was once public and later pulled back, ask about this.&lt;/p&gt;
&lt;p&gt;Drafts and scheduled publishing are a separate setting and remain off by default.&lt;/p&gt;
&lt;h3&gt;A better admin for editors and designers&lt;/h3&gt;
&lt;p&gt;The admin panel gets its biggest redesign since Payload 3. Folders and tags are built in, so editors can organize pages and media into trees instead of paging through long flat lists. For large content libraries, that is the difference between finding something in seconds and giving up and asking a colleague.&lt;/p&gt;
&lt;p&gt;Lists also load faster on big collections, because the admin now fetches only the columns an editor is actually looking at.&lt;/p&gt;
&lt;p&gt;For designers, rebranding the admin gets simpler. Colors, radius, and borders are controlled by a shared set of design settings rather than hand-written stylesheets. If you want custom screens inside the admin built with modern styling tools, those no longer clash with the admin&amp;#39;s own styles.&lt;/p&gt;
&lt;h3&gt;AI assistants that work with your content&lt;/h3&gt;
&lt;p&gt;Payload 4 has first-class support for connecting AI assistants to your CMS. The assistant acts as a specific user and is held to that user&amp;#39;s permissions.&lt;/p&gt;
&lt;p&gt;One caution. In Payload 4, the built-in content tools are switched on automatically unless someone turns them off. That is not a security hole, since permission checks still apply, but it is a decision. Ask your developer what is exposed to AI tools on your site, and whether that matches what you intend.&lt;/p&gt;
&lt;h3&gt;More flexibility in the technology around it&lt;/h3&gt;
&lt;p&gt;Payload 4 starts to separate the CMS from the framework it runs in. Next.js remains the main, proven path. Support for an alternative, TanStack Start, exists only as an early experiment.&lt;/p&gt;
&lt;p&gt;If you are not already thinking about changing your website framework, ignore this one for now. It is a sign of direction, not a reason to move.&lt;/p&gt;
&lt;h2&gt;A scenario: someone published the wrong price&lt;/h2&gt;
&lt;!-- bwm:slider payload-4-for-business-owners/price-incident-undo --&gt;
&lt;div data-slider=&quot;true&quot; data-slider-id=&quot;payload-4-for-business-owners/price-incident-undo&quot; data-slider-source=&quot;video/src/articles/payload-4-for-business-owners/price-incident-undo&quot;&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/f9qq9abe/file/original&quot; alt=&quot;The Incident: Wrong Price Goes Live: An editor updates a pricing tier and publishes a typo: $19 instead of $190.&quot; title=&quot;The Incident: Wrong Price Goes Live&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/2gmganuf/file/original&quot; alt=&quot;The Upgrade Difference: Payload 3 vs 4: In Payload 3, versioning was manual. In Payload 4, version history is active by default.&quot; title=&quot;The Upgrade Difference: Payload 3 vs 4&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/lnx9pwoj/file/original&quot; alt=&quot;The Resolution: Reverted in 60 Seconds: The editor opens version history, picks yesterday&apos;s revision, and restores without code or panic.&quot; title=&quot;The Resolution: Reverted in 60 Seconds&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/rjtf5w1u/file/original&quot; alt=&quot;Business Value: Peace of Mind by Default: 1-click undo, full audit trail, and zero emergency developer overhead.&quot; title=&quot;Business Value: Peace of Mind by Default&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
&lt;/div&gt;
&lt;!-- /bwm:slider --&gt;&lt;p&gt;This is where content history stops being abstract.&lt;/p&gt;
&lt;p&gt;An editor updates a product page and accidentally publishes the wrong price. On a site without content history, the fix is a developer digging through a database backup, or an editor trying to remember what the old number was.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    autonumber
    actor Editor as Editor
    participant CMS as Payload admin
    participant History as Version history
    participant Site as Live website
    Editor-&amp;gt;&amp;gt;CMS: Saves page with the wrong price
    CMS-&amp;gt;&amp;gt;History: Keeps the previous version
    CMS-&amp;gt;&amp;gt;Site: Wrong price goes live
    Editor-&amp;gt;&amp;gt;History: Opens history, picks yesterday&amp;#39;s version
    History-&amp;gt;&amp;gt;CMS: Restores the earlier version
    CMS-&amp;gt;&amp;gt;Site: Correct price is back
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;With history switched on, the fix takes minutes and does not need a developer. This only works for content types where history is enabled, so choose them deliberately.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;What this means for your role&lt;/h2&gt;
&lt;h3&gt;If you are a product manager&lt;/h3&gt;
&lt;p&gt;You have nothing to schedule until a stable release exists. What you can do now is ask for a trial upgrade estimate, so that when stable lands you already know the size of the project. Also list the workarounds you maintain today, such as extra plugins for folders or page trees. Some of them may become unnecessary.&lt;/p&gt;
&lt;h3&gt;If you are a designer&lt;/h3&gt;
&lt;p&gt;Expect a refreshed admin interface that your editors will need a short time to get used to. If your brand lives inside custom admin screens, plan time to check them against the new styling system. The upside is that theming becomes easier, and custom views are less fragile.&lt;/p&gt;
&lt;h3&gt;If you are a business owner&lt;/h3&gt;
&lt;p&gt;Your decisions are timing and risk. The safe default is to stay on Payload 3 in production, plan the move, and schedule it for when a stable release exists and your business calendar has room for it. If your team handles sensitive data, the safer permission defaults are a good reason to want Payload 4 eventually.&lt;/p&gt;
&lt;p&gt;For the wider question of how much control your marketing team should have, see &lt;a href=&quot;/blog/marketing-cms-control-controlled-autonomy-model&quot;&gt;how to give marketing control without losing consistency&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;What the upgrade actually costs&lt;/h2&gt;
&lt;p&gt;Payload is open source, so there is no licence fee. The cost is the time to move your site safely. A few things decide how large that is:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart TD
    P[&amp;quot;Upgrade project&amp;quot;] --&amp;gt; A[&amp;quot;Custom code review&amp;lt;br/&amp;gt;access rules, scripts, jobs&amp;quot;]
    P --&amp;gt; B[&amp;quot;Database changes&amp;lt;br/&amp;gt;history tables, migrations&amp;quot;]
    P --&amp;gt; C[&amp;quot;Hosting and software&amp;lt;br/&amp;gt;version upgrades&amp;quot;]
    P --&amp;gt; D[&amp;quot;Content conversion&amp;lt;br/&amp;gt;if on the old editor&amp;quot;]
    P --&amp;gt; E[&amp;quot;Testing on a&amp;lt;br/&amp;gt;staging copy&amp;quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;A site with little custom code is a small project. A site with many integrations, scheduled jobs, and custom admin screens is a larger one. A trial upgrade on a copy of your site turns this into a real number.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;An automatic tool handles many of the mechanical changes. It does not make the judgment calls: which jobs should bypass permissions, which content types should keep history, and whether a generated database change is safe to apply. Those still need an experienced developer.&lt;/p&gt;
&lt;p&gt;Two further items catch people out. Payload 4 needs newer versions of the software your site runs on, so your hosting may need an upgrade. And if your content is still stored in Payload&amp;#39;s older text editor, that content has to be converted before you can move.&lt;/p&gt;
&lt;p&gt;I won&amp;#39;t give you a price here. Anyone who quotes a number without looking at your site is guessing.&lt;/p&gt;
&lt;h2&gt;The path to a safe rollout&lt;/h2&gt;
&lt;p&gt;The sensible route is a gated one. Nothing touches production until a stable version exists and you have seen a trial on your own data.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
    A[&amp;quot;Today&amp;lt;br/&amp;gt;Production on 3.x&amp;quot;] --&amp;gt; B[&amp;quot;Trial branch&amp;lt;br/&amp;gt;Audit and estimate&amp;quot;]
    B --&amp;gt; C[&amp;quot;Budget and&amp;lt;br/&amp;gt;risk review&amp;quot;]
    C --&amp;gt; D{&amp;quot;Stable Payload 4&amp;lt;br/&amp;gt;released?&amp;quot;}
    D --&amp;gt;|&amp;quot;Not yet&amp;quot;| W[&amp;quot;Stay on 3.x&amp;lt;br/&amp;gt;and re-check&amp;quot;]
    D --&amp;gt;|&amp;quot;Yes&amp;quot;| E[&amp;quot;Staged rollout&amp;lt;br/&amp;gt;test copy first&amp;quot;]
    E --&amp;gt; F[&amp;quot;Production&amp;quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;The gate is the stable release. Everything before it is planning and learning, which costs far less than a rushed migration.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;Should you upgrade? A decision guide&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart TD
    A{&amp;quot;Is a stable&amp;lt;br/&amp;gt;Payload 4 released?&amp;quot;} --&amp;gt;|&amp;quot;No&amp;quot;| B[&amp;quot;Keep production&amp;lt;br/&amp;gt;on Payload 3&amp;quot;]
    B --&amp;gt; C{&amp;quot;Lots of custom code,&amp;lt;br/&amp;gt;jobs or admin screens?&amp;quot;}
    C --&amp;gt;|&amp;quot;Yes&amp;quot;| D[&amp;quot;Plan a trial branch&amp;lt;br/&amp;gt;and audit now&amp;quot;]
    C --&amp;gt;|&amp;quot;No&amp;quot;| E[&amp;quot;Wait for stable,&amp;lt;br/&amp;gt;then schedule the move&amp;quot;]
    A --&amp;gt;|&amp;quot;Yes&amp;quot;| F{&amp;quot;Need folders, history&amp;lt;br/&amp;gt;or AI features soon?&amp;quot;}
    F --&amp;gt;|&amp;quot;Yes&amp;quot;| G[&amp;quot;Budget an&amp;lt;br/&amp;gt;upgrade project&amp;quot;]
    F --&amp;gt;|&amp;quot;No&amp;quot;| H[&amp;quot;Upgrade at your next&amp;lt;br/&amp;gt;planned maintenance&amp;quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Today you are on the &amp;quot;No&amp;quot; branch. The only question is whether your site is complicated enough to justify starting the trial early.&lt;/em&gt;&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;[!TOOL]
&lt;strong&gt;Evaluate Your Migration Path&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The &lt;a href=&quot;/tools/payload-4-upgrade-quiz&quot;&gt;Payload 4 Upgrade Readiness &amp;amp; Cost Estimator&lt;/a&gt; runs through this decision tree in under 90 seconds. It evaluates your custom code, database state, and runtime constraints to give you an instant readiness verdict, estimated hours, and a realistic budget range.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;/tools/payload-4-upgrade-quiz&quot;&gt;Launch 90-Second Estimator →&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Questions to ask your developer or agency&lt;/h2&gt;
&lt;p&gt;Bring these to your next conversation. Good answers are specific to your site, not general reassurance.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Which parts of our site run custom code that talks to the CMS directly, and have they been checked against the new permission defaults?&lt;/li&gt;
&lt;li&gt;Which content types should keep a history, and who should be allowed to see old versions?&lt;/li&gt;
&lt;li&gt;Is any of our content still in the older rich-text editor, and what would converting it involve?&lt;/li&gt;
&lt;li&gt;Are all the plugins we depend on ready for Payload 4?&lt;/li&gt;
&lt;li&gt;What hosting and software upgrades would we need, and who owns them?&lt;/li&gt;
&lt;li&gt;Can you run a trial upgrade on a copy of our site and give us an estimate before we commit?&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Where to go from here&lt;/h2&gt;
&lt;p&gt;Payload 4 is a good direction, and it is not yet a decision you have to make. Stay on Payload 3, keep your site healthy, and use the waiting time to find out how big your upgrade would be.&lt;/p&gt;
&lt;p&gt;If you want a clear answer for your specific site, a &lt;a href=&quot;/payload-cms-audit&quot;&gt;Payload CMS audit&lt;/a&gt; will tell you what an upgrade would involve before you commit to anything. For a bigger change of platform, see &lt;a href=&quot;/payload-cms-migration&quot;&gt;Payload CMS migration&lt;/a&gt;, or work with an experienced &lt;a href=&quot;/payload-cms-developer&quot;&gt;Payload CMS developer&lt;/a&gt;. If you are weighing up whether outside help is worth the cost, &lt;a href=&quot;/blog/what-you-pay-for-senior-cms-consultant&quot;&gt;what a senior CMS consultant is actually paid for&lt;/a&gt; is a good place to start, and &lt;a href=&quot;/blog/cms-migration-triage-7-outcomes&quot;&gt;the seven outcomes of a CMS migration triage&lt;/a&gt; shows how those decisions usually play out.&lt;/p&gt;
&lt;p&gt;Your developers can find the full technical detail, with the official migration guide, in the &lt;a href=&quot;/blog/payload-4-0&quot;&gt;Payload 4 technical breakdown&lt;/a&gt;. For the media-library side of the picture, see &lt;a href=&quot;/blog/payload-dam-what-exists-today-coming-4-0&quot;&gt;what Payload offers for digital asset management today&lt;/a&gt;.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/payload-4-for-business-owners"/>
        </item>
        <item>
            <title><![CDATA[The Code Is the Deliverable. Your Development System Might Not Be.]]></title>
            <description><![CDATA[<p>For a long time, I treated the repository as the natural home for almost everything related to a project.</p>
<p>Application code went there.</p>
<p>Tests went there.</p>
<p>Architecture notes went there.</p>
<p>Implementation decisions went there.</p>
<p>Then AI-assisted development added another category of files:</p>
<ul>
<li>agent instructions</li>
<li>project-specific skills</li>
<li>Claude and Codex configuration</li>
<li>implementation playbooks</li>
<li>research notes</li>
<li>internal audits</li>
<li>generated reports</li>
<li>prompts</li>
<li>orchestration instructions</li>
<li>development workflows</li>
<li>context that teaches an agent how I want a system to be built</li>
</ul>
<p>I put many of those things in the same repository too.</p>
<p>At first, that felt like good engineering.</p>
<p>Everything was close to the code. The context was available to the tools that needed it. I could open a project and immediately have a development environment that understood the architecture, conventions, important decisions, and patterns I wanted to follow.</p>
<p>It worked extremely well.</p>
<p>It also took me a while to realize that I had mixed two very different things together.</p>
<p>The first was the product I was building for the client.</p>
<p>The second was the system I use to build products.</p>
<p>Those are not necessarily the same deliverable.</p>
<h2>AI development creates a new kind of engineering asset</h2>
<p>A developer used to arrive at a project mostly carrying knowledge in their head.</p>
<p>They knew how they liked to structure applications, how they debugged problems, how they reviewed code, how they reasoned about architecture, and which shortcuts were dangerous.</p>
<p>Some of that knowledge might eventually appear in documentation.</p>
<p>Most of it disappeared when the developer left.</p>
<p>AI-assisted development changes this.</p>
<p>A surprising amount of that working knowledge can now be encoded directly into the development environment.</p>
<p>An agent skill might explain how a particular class of components should be implemented.</p>
<p>A project instruction file might tell an AI assistant how the architecture is structured, which abstractions are canonical, what should never be duplicated, and where important boundaries exist.</p>
<p>An internal audit might document hundreds of observations about a codebase.</p>
<p>A workflow might coordinate multiple agents to inspect, implement, verify, and document a change.</p>
<p>A prompt might contain the result of months of experimentation around how to reliably perform a particular engineering task.</p>
<p>Individually, these files can look insignificant.</p>
<p>Collectively, they become something much more valuable.</p>
<p>They become a development system.</p>
<p>And that development system can materially affect how quickly and reliably someone can work.</p>
<h2>The repository boundary suddenly matters more</h2>
<p>Suppose I am hired to build a complex application.</p>
<p>The client should obviously receive the application.</p>
<p>They should receive the code required to operate it.</p>
<p>They should receive the tests that verify it.</p>
<p>They should receive the infrastructure and configuration required to run it.</p>
<p>They should receive the documentation necessary to understand and maintain the system.</p>
<p>They should not be dependent on me having some secret knowledge that makes the application impossible to operate after I leave.</p>
<p>That part has not changed.</p>
<p>But imagine that next to the application I also maintain:</p>
<pre><code class="language-text">.agents/
.claude/
internal-reports/
research/
working-notes/
private-automation/
agent-skills/
</code></pre>
<p>Those directories might contain reusable methods that I use across many projects.</p>
<p>They may explain how I perform architecture reviews.</p>
<p>They may contain generic debugging workflows.</p>
<p>They may encode how I use agents to refactor repositories, inspect migrations, analyze schemas, or validate implementations.</p>
<p>They may contain working material that was never intended to be part of the final system.</p>
<p>Putting all of that into the client&#39;s repository creates an accidental ownership boundary.</p>
<p>The distinction between <em>documentation about the product</em> and <em>the machinery used to produce the product</em> disappears.</p>
<h2>Good documentation is still part of good engineering</h2>
<!-- bwm:slider code-is-the-deliverable-development-system-not/deliverable-vs-system -->
<div data-slider="true" data-slider-id="code-is-the-deliverable-development-system-not/deliverable-vs-system" data-slider-source="video/src/articles/code-is-the-deliverable-development-system-not/deliverable-vs-system">
  <img src="https://img.buildwithmatija.com/api/images/t9hxk8ft/file/original" alt="The Product Code Contract: The deliverable is the codebase, its architecture, tests, and operational documentation required to run it." title="The Product Code Contract" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/n6zfcoan/file/original" alt="Your Personal Operating System: Agent instructions, custom skills, prompt orchestration, and research notes are your private developer intelligence." title="Your Personal Operating System" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/pwz6lxvq/file/original" alt="Product Knowledge vs Delivery Knowledge: Product knowledge belongs to the client; delivery knowledge (how you produce fast, high-quality code) belongs to the engineer." title="Product Knowledge vs Delivery Knowledge" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/qo05rrn9/file/original" alt="Clear Boundaries Build Trust: Clean boundaries prevent IP disputes and keep projects professional when other teams or contractors arrive." title="Clear Boundaries Build Trust" width="1080" height="1080" />
</div>
<!-- /bwm:slider --><p>The wrong lesson would be:</p>
<blockquote>
<p>Never document anything because the client might learn too much.</p>
</blockquote>
<p>That would be terrible engineering.</p>
<p>The client should not be trapped.</p>
<p>If an application relies on a complicated content model, document it.</p>
<p>If there are important architectural decisions, record them.</p>
<p>If deployment has unusual requirements, explain them.</p>
<p>If another developer needs to understand how a subsystem works in order to safely change it, that knowledge belongs with the system.</p>
<p>But there is another category of material that deserves a different home.</p>
<p>I now think about the split roughly like this.</p>
<h3>Product knowledge</h3>
<p>This belongs with the project:</p>
<ul>
<li>application architecture</li>
<li>schema and data contracts</li>
<li>tests</li>
<li>runtime configuration</li>
<li>deployment instructions</li>
<li>migration documentation</li>
<li>operational guidance</li>
<li>meaningful architecture decision records</li>
<li>maintenance documentation</li>
<li>agreed handover material</li>
</ul>
<h3>Delivery knowledge</h3>
<p>This may belong with the developer or delivery organization:</p>
<ul>
<li>reusable agent skills</li>
<li>generic prompts</li>
<li>internal research workflows</li>
<li>personal orchestration systems</li>
<li>private code-review instructions</li>
<li>reusable auditing methodology</li>
<li>internal working notes</li>
<li>draft analysis</li>
<li>productivity automation</li>
<li>reusable AI context</li>
<li>methodology developed across multiple clients</li>
</ul>
<p>There will always be grey areas.</p>
<p>That is fine.</p>
<p>The important thing is making the distinction deliberately rather than discovering it accidentally six months into a project.</p>
<h2>The difference is easier to see when another team enters the project</h2>
<p>This became much more obvious to me when thinking about handover.</p>
<p>Imagine another development team takes over an application.</p>
<p>They should absolutely be able to understand the application.</p>
<p>But should they automatically inherit every tool, workflow, prompt, skill, internal report, and automation system I developed to make myself more effective?</p>
<p>That is a different question.</p>
<p>If those assets are part of the agreed engagement, of course.</p>
<p>If I was explicitly hired to build an internal engineering system for the organization, of course.</p>
<p>But if I developed them as part of my own working environment, their presence in the same Git repository does not automatically mean they were intended as part of the product.</p>
<p>This is very similar to other professional services.</p>
<p>A designer delivers the design.</p>
<p>They do not necessarily transfer every reusable template, research framework, reference library, or internal process they have developed over their career.</p>
<p>A consultancy delivers its analysis and recommendations.</p>
<p>It does not automatically transfer the complete internal methodology it uses to produce them.</p>
<p>Software development is beginning to look more like this because the development environment itself is becoming much richer.</p>
<h2>The codebase and the development system can live separately</h2>
<p>The practical solution is not particularly complicated.</p>
<p>I now prefer thinking in terms of two repositories.</p>
<p>The client repository contains the actual product:</p>
<pre><code class="language-text">client-project/
├── application/
├── tests/
├── infrastructure/
├── migrations/
└── project-documentation/
</code></pre>
<p>My private development workspace can contain things such as:</p>
<pre><code class="language-text">private-workspace/
├── agent-skills/
├── prompts/
├── internal-reports/
├── working-docs/
├── research/
└── automation/
</code></pre>
<p>Locally, those directories can still be exposed inside the normal development workspace.</p>
<p>Symlinks, local configuration, workspace tooling, or other development-environment mechanisms can make them available exactly where Claude, Codex, editors, or local scripts expect to find them.</p>
<p>The developer experience does not have to suffer.</p>
<p>What changes is the ownership boundary.</p>
<p>A commit to the application goes to the client repository.</p>
<p>A change to an internal agent skill goes to my private development repository.</p>
<p>That separation turns out to be useful even when there is no commercial tension whatsoever.</p>
<p>It keeps client repositories cleaner.</p>
<p>It makes handovers easier.</p>
<p>It makes reusable tooling genuinely reusable.</p>
<p>It prevents internal experiments from becoming accidental project dependencies.</p>
<p>And it forces me to decide what documentation another developer genuinely needs.</p>
<h2>Good faith is not a replacement for commercial boundaries</h2>
<p>There is another lesson underneath this.</p>
<p>When a client relationship is going well, it is very easy to operate informally.</p>
<p>You keep moving because you do not want paperwork to block progress.</p>
<p>You share context freely.</p>
<p>You put your tools close to the work.</p>
<p>You assume the next phase will happen because everyone says the next phase will happen.</p>
<p>Most of the time, that may be completely fine.</p>
<p>But commercial boundaries are most useful before there is a disagreement, not after one appears.</p>
<p>A clearly separated development system is not an expression of distrust.</p>
<p>Neither is waiting for a milestone to be authorized before starting a large amount of work.</p>
<p>Neither is deciding which assets belong to the client and which belong to your own operating system.</p>
<p>These are simply controls.</p>
<p>Good relationships and good controls are not opposites.</p>
<p>In fact, good controls often protect the relationship because fewer assumptions need to be renegotiated later.</p>
<h2>Your advantage should not depend on secrecy</h2>
<p>There is also an important counterpoint.</p>
<p>I do not think developers should build their advantage around hiding information.</p>
<p>If your entire value disappears because another developer can read your instructions, there is not much defensibility there.</p>
<p>The interesting advantage is that the development system keeps evolving.</p>
<p>An agent skill is not valuable simply because someone cannot see it.</p>
<p>It is valuable because it captures experience, improves over time, connects to other workflows, and helps produce better decisions faster.</p>
<p>Someone may have a snapshot.</p>
<p>You still have the system that continues to evolve.</p>
<p>That distinction matters.</p>
<p>The objective is not secrecy.</p>
<p>It is ownership.</p>
<h2>We may need a new definition of the software deliverable</h2>
<p>AI-assisted development is slowly changing what exists around a codebase.</p>
<p>There used to be an application and some documentation.</p>
<p>Now there can also be a substantial machine-readable layer explaining how the application should be reasoned about, extended, tested, reviewed, and changed.</p>
<p>That layer can contain real intellectual capital.</p>
<p>We are going to need better norms around it.</p>
<p>Some of it clearly belongs to the client.</p>
<p>Some of it clearly belongs to the developer.</p>
<p>Some of it will need to be explicitly negotiated.</p>
<p>But treating everything inside a working directory as automatically belonging to the same commercial category is becoming increasingly difficult to defend.</p>
<p>The lesson I am taking forward is simple:</p>
<p><strong>The client should receive a system they can genuinely operate without me.</strong></p>
<p>But that does not necessarily mean they need the entire system I use to make myself effective while building it.</p>
<p>The code is the deliverable.</p>
<p>The documentation required to understand and operate it is part of the deliverable.</p>
<p>The evolving development system behind it might not be.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/code-is-the-deliverable-development-system-not</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/code-is-the-deliverable-development-system-not</guid>
            <category><![CDATA[Tools]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;For a long time, I treated the repository as the natural home for almost everything related to a project.&lt;/p&gt;
&lt;p&gt;Application code went there.&lt;/p&gt;
&lt;p&gt;Tests went there.&lt;/p&gt;
&lt;p&gt;Architecture notes went there.&lt;/p&gt;
&lt;p&gt;Implementation decisions went there.&lt;/p&gt;
&lt;p&gt;Then AI-assisted development added another category of files:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;agent instructions&lt;/li&gt;
&lt;li&gt;project-specific skills&lt;/li&gt;
&lt;li&gt;Claude and Codex configuration&lt;/li&gt;
&lt;li&gt;implementation playbooks&lt;/li&gt;
&lt;li&gt;research notes&lt;/li&gt;
&lt;li&gt;internal audits&lt;/li&gt;
&lt;li&gt;generated reports&lt;/li&gt;
&lt;li&gt;prompts&lt;/li&gt;
&lt;li&gt;orchestration instructions&lt;/li&gt;
&lt;li&gt;development workflows&lt;/li&gt;
&lt;li&gt;context that teaches an agent how I want a system to be built&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I put many of those things in the same repository too.&lt;/p&gt;
&lt;p&gt;At first, that felt like good engineering.&lt;/p&gt;
&lt;p&gt;Everything was close to the code. The context was available to the tools that needed it. I could open a project and immediately have a development environment that understood the architecture, conventions, important decisions, and patterns I wanted to follow.&lt;/p&gt;
&lt;p&gt;It worked extremely well.&lt;/p&gt;
&lt;p&gt;It also took me a while to realize that I had mixed two very different things together.&lt;/p&gt;
&lt;p&gt;The first was the product I was building for the client.&lt;/p&gt;
&lt;p&gt;The second was the system I use to build products.&lt;/p&gt;
&lt;p&gt;Those are not necessarily the same deliverable.&lt;/p&gt;
&lt;h2&gt;AI development creates a new kind of engineering asset&lt;/h2&gt;
&lt;p&gt;A developer used to arrive at a project mostly carrying knowledge in their head.&lt;/p&gt;
&lt;p&gt;They knew how they liked to structure applications, how they debugged problems, how they reviewed code, how they reasoned about architecture, and which shortcuts were dangerous.&lt;/p&gt;
&lt;p&gt;Some of that knowledge might eventually appear in documentation.&lt;/p&gt;
&lt;p&gt;Most of it disappeared when the developer left.&lt;/p&gt;
&lt;p&gt;AI-assisted development changes this.&lt;/p&gt;
&lt;p&gt;A surprising amount of that working knowledge can now be encoded directly into the development environment.&lt;/p&gt;
&lt;p&gt;An agent skill might explain how a particular class of components should be implemented.&lt;/p&gt;
&lt;p&gt;A project instruction file might tell an AI assistant how the architecture is structured, which abstractions are canonical, what should never be duplicated, and where important boundaries exist.&lt;/p&gt;
&lt;p&gt;An internal audit might document hundreds of observations about a codebase.&lt;/p&gt;
&lt;p&gt;A workflow might coordinate multiple agents to inspect, implement, verify, and document a change.&lt;/p&gt;
&lt;p&gt;A prompt might contain the result of months of experimentation around how to reliably perform a particular engineering task.&lt;/p&gt;
&lt;p&gt;Individually, these files can look insignificant.&lt;/p&gt;
&lt;p&gt;Collectively, they become something much more valuable.&lt;/p&gt;
&lt;p&gt;They become a development system.&lt;/p&gt;
&lt;p&gt;And that development system can materially affect how quickly and reliably someone can work.&lt;/p&gt;
&lt;h2&gt;The repository boundary suddenly matters more&lt;/h2&gt;
&lt;p&gt;Suppose I am hired to build a complex application.&lt;/p&gt;
&lt;p&gt;The client should obviously receive the application.&lt;/p&gt;
&lt;p&gt;They should receive the code required to operate it.&lt;/p&gt;
&lt;p&gt;They should receive the tests that verify it.&lt;/p&gt;
&lt;p&gt;They should receive the infrastructure and configuration required to run it.&lt;/p&gt;
&lt;p&gt;They should receive the documentation necessary to understand and maintain the system.&lt;/p&gt;
&lt;p&gt;They should not be dependent on me having some secret knowledge that makes the application impossible to operate after I leave.&lt;/p&gt;
&lt;p&gt;That part has not changed.&lt;/p&gt;
&lt;p&gt;But imagine that next to the application I also maintain:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;.agents/
.claude/
internal-reports/
research/
working-notes/
private-automation/
agent-skills/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Those directories might contain reusable methods that I use across many projects.&lt;/p&gt;
&lt;p&gt;They may explain how I perform architecture reviews.&lt;/p&gt;
&lt;p&gt;They may contain generic debugging workflows.&lt;/p&gt;
&lt;p&gt;They may encode how I use agents to refactor repositories, inspect migrations, analyze schemas, or validate implementations.&lt;/p&gt;
&lt;p&gt;They may contain working material that was never intended to be part of the final system.&lt;/p&gt;
&lt;p&gt;Putting all of that into the client&amp;#39;s repository creates an accidental ownership boundary.&lt;/p&gt;
&lt;p&gt;The distinction between &lt;em&gt;documentation about the product&lt;/em&gt; and &lt;em&gt;the machinery used to produce the product&lt;/em&gt; disappears.&lt;/p&gt;
&lt;h2&gt;Good documentation is still part of good engineering&lt;/h2&gt;
&lt;!-- bwm:slider code-is-the-deliverable-development-system-not/deliverable-vs-system --&gt;
&lt;div data-slider=&quot;true&quot; data-slider-id=&quot;code-is-the-deliverable-development-system-not/deliverable-vs-system&quot; data-slider-source=&quot;video/src/articles/code-is-the-deliverable-development-system-not/deliverable-vs-system&quot;&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/t9hxk8ft/file/original&quot; alt=&quot;The Product Code Contract: The deliverable is the codebase, its architecture, tests, and operational documentation required to run it.&quot; title=&quot;The Product Code Contract&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/n6zfcoan/file/original&quot; alt=&quot;Your Personal Operating System: Agent instructions, custom skills, prompt orchestration, and research notes are your private developer intelligence.&quot; title=&quot;Your Personal Operating System&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/pwz6lxvq/file/original&quot; alt=&quot;Product Knowledge vs Delivery Knowledge: Product knowledge belongs to the client; delivery knowledge (how you produce fast, high-quality code) belongs to the engineer.&quot; title=&quot;Product Knowledge vs Delivery Knowledge&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/qo05rrn9/file/original&quot; alt=&quot;Clear Boundaries Build Trust: Clean boundaries prevent IP disputes and keep projects professional when other teams or contractors arrive.&quot; title=&quot;Clear Boundaries Build Trust&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
&lt;/div&gt;
&lt;!-- /bwm:slider --&gt;&lt;p&gt;The wrong lesson would be:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Never document anything because the client might learn too much.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;That would be terrible engineering.&lt;/p&gt;
&lt;p&gt;The client should not be trapped.&lt;/p&gt;
&lt;p&gt;If an application relies on a complicated content model, document it.&lt;/p&gt;
&lt;p&gt;If there are important architectural decisions, record them.&lt;/p&gt;
&lt;p&gt;If deployment has unusual requirements, explain them.&lt;/p&gt;
&lt;p&gt;If another developer needs to understand how a subsystem works in order to safely change it, that knowledge belongs with the system.&lt;/p&gt;
&lt;p&gt;But there is another category of material that deserves a different home.&lt;/p&gt;
&lt;p&gt;I now think about the split roughly like this.&lt;/p&gt;
&lt;h3&gt;Product knowledge&lt;/h3&gt;
&lt;p&gt;This belongs with the project:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;application architecture&lt;/li&gt;
&lt;li&gt;schema and data contracts&lt;/li&gt;
&lt;li&gt;tests&lt;/li&gt;
&lt;li&gt;runtime configuration&lt;/li&gt;
&lt;li&gt;deployment instructions&lt;/li&gt;
&lt;li&gt;migration documentation&lt;/li&gt;
&lt;li&gt;operational guidance&lt;/li&gt;
&lt;li&gt;meaningful architecture decision records&lt;/li&gt;
&lt;li&gt;maintenance documentation&lt;/li&gt;
&lt;li&gt;agreed handover material&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Delivery knowledge&lt;/h3&gt;
&lt;p&gt;This may belong with the developer or delivery organization:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;reusable agent skills&lt;/li&gt;
&lt;li&gt;generic prompts&lt;/li&gt;
&lt;li&gt;internal research workflows&lt;/li&gt;
&lt;li&gt;personal orchestration systems&lt;/li&gt;
&lt;li&gt;private code-review instructions&lt;/li&gt;
&lt;li&gt;reusable auditing methodology&lt;/li&gt;
&lt;li&gt;internal working notes&lt;/li&gt;
&lt;li&gt;draft analysis&lt;/li&gt;
&lt;li&gt;productivity automation&lt;/li&gt;
&lt;li&gt;reusable AI context&lt;/li&gt;
&lt;li&gt;methodology developed across multiple clients&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;There will always be grey areas.&lt;/p&gt;
&lt;p&gt;That is fine.&lt;/p&gt;
&lt;p&gt;The important thing is making the distinction deliberately rather than discovering it accidentally six months into a project.&lt;/p&gt;
&lt;h2&gt;The difference is easier to see when another team enters the project&lt;/h2&gt;
&lt;p&gt;This became much more obvious to me when thinking about handover.&lt;/p&gt;
&lt;p&gt;Imagine another development team takes over an application.&lt;/p&gt;
&lt;p&gt;They should absolutely be able to understand the application.&lt;/p&gt;
&lt;p&gt;But should they automatically inherit every tool, workflow, prompt, skill, internal report, and automation system I developed to make myself more effective?&lt;/p&gt;
&lt;p&gt;That is a different question.&lt;/p&gt;
&lt;p&gt;If those assets are part of the agreed engagement, of course.&lt;/p&gt;
&lt;p&gt;If I was explicitly hired to build an internal engineering system for the organization, of course.&lt;/p&gt;
&lt;p&gt;But if I developed them as part of my own working environment, their presence in the same Git repository does not automatically mean they were intended as part of the product.&lt;/p&gt;
&lt;p&gt;This is very similar to other professional services.&lt;/p&gt;
&lt;p&gt;A designer delivers the design.&lt;/p&gt;
&lt;p&gt;They do not necessarily transfer every reusable template, research framework, reference library, or internal process they have developed over their career.&lt;/p&gt;
&lt;p&gt;A consultancy delivers its analysis and recommendations.&lt;/p&gt;
&lt;p&gt;It does not automatically transfer the complete internal methodology it uses to produce them.&lt;/p&gt;
&lt;p&gt;Software development is beginning to look more like this because the development environment itself is becoming much richer.&lt;/p&gt;
&lt;h2&gt;The codebase and the development system can live separately&lt;/h2&gt;
&lt;p&gt;The practical solution is not particularly complicated.&lt;/p&gt;
&lt;p&gt;I now prefer thinking in terms of two repositories.&lt;/p&gt;
&lt;p&gt;The client repository contains the actual product:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;client-project/
├── application/
├── tests/
├── infrastructure/
├── migrations/
└── project-documentation/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;My private development workspace can contain things such as:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;private-workspace/
├── agent-skills/
├── prompts/
├── internal-reports/
├── working-docs/
├── research/
└── automation/
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Locally, those directories can still be exposed inside the normal development workspace.&lt;/p&gt;
&lt;p&gt;Symlinks, local configuration, workspace tooling, or other development-environment mechanisms can make them available exactly where Claude, Codex, editors, or local scripts expect to find them.&lt;/p&gt;
&lt;p&gt;The developer experience does not have to suffer.&lt;/p&gt;
&lt;p&gt;What changes is the ownership boundary.&lt;/p&gt;
&lt;p&gt;A commit to the application goes to the client repository.&lt;/p&gt;
&lt;p&gt;A change to an internal agent skill goes to my private development repository.&lt;/p&gt;
&lt;p&gt;That separation turns out to be useful even when there is no commercial tension whatsoever.&lt;/p&gt;
&lt;p&gt;It keeps client repositories cleaner.&lt;/p&gt;
&lt;p&gt;It makes handovers easier.&lt;/p&gt;
&lt;p&gt;It makes reusable tooling genuinely reusable.&lt;/p&gt;
&lt;p&gt;It prevents internal experiments from becoming accidental project dependencies.&lt;/p&gt;
&lt;p&gt;And it forces me to decide what documentation another developer genuinely needs.&lt;/p&gt;
&lt;h2&gt;Good faith is not a replacement for commercial boundaries&lt;/h2&gt;
&lt;p&gt;There is another lesson underneath this.&lt;/p&gt;
&lt;p&gt;When a client relationship is going well, it is very easy to operate informally.&lt;/p&gt;
&lt;p&gt;You keep moving because you do not want paperwork to block progress.&lt;/p&gt;
&lt;p&gt;You share context freely.&lt;/p&gt;
&lt;p&gt;You put your tools close to the work.&lt;/p&gt;
&lt;p&gt;You assume the next phase will happen because everyone says the next phase will happen.&lt;/p&gt;
&lt;p&gt;Most of the time, that may be completely fine.&lt;/p&gt;
&lt;p&gt;But commercial boundaries are most useful before there is a disagreement, not after one appears.&lt;/p&gt;
&lt;p&gt;A clearly separated development system is not an expression of distrust.&lt;/p&gt;
&lt;p&gt;Neither is waiting for a milestone to be authorized before starting a large amount of work.&lt;/p&gt;
&lt;p&gt;Neither is deciding which assets belong to the client and which belong to your own operating system.&lt;/p&gt;
&lt;p&gt;These are simply controls.&lt;/p&gt;
&lt;p&gt;Good relationships and good controls are not opposites.&lt;/p&gt;
&lt;p&gt;In fact, good controls often protect the relationship because fewer assumptions need to be renegotiated later.&lt;/p&gt;
&lt;h2&gt;Your advantage should not depend on secrecy&lt;/h2&gt;
&lt;p&gt;There is also an important counterpoint.&lt;/p&gt;
&lt;p&gt;I do not think developers should build their advantage around hiding information.&lt;/p&gt;
&lt;p&gt;If your entire value disappears because another developer can read your instructions, there is not much defensibility there.&lt;/p&gt;
&lt;p&gt;The interesting advantage is that the development system keeps evolving.&lt;/p&gt;
&lt;p&gt;An agent skill is not valuable simply because someone cannot see it.&lt;/p&gt;
&lt;p&gt;It is valuable because it captures experience, improves over time, connects to other workflows, and helps produce better decisions faster.&lt;/p&gt;
&lt;p&gt;Someone may have a snapshot.&lt;/p&gt;
&lt;p&gt;You still have the system that continues to evolve.&lt;/p&gt;
&lt;p&gt;That distinction matters.&lt;/p&gt;
&lt;p&gt;The objective is not secrecy.&lt;/p&gt;
&lt;p&gt;It is ownership.&lt;/p&gt;
&lt;h2&gt;We may need a new definition of the software deliverable&lt;/h2&gt;
&lt;p&gt;AI-assisted development is slowly changing what exists around a codebase.&lt;/p&gt;
&lt;p&gt;There used to be an application and some documentation.&lt;/p&gt;
&lt;p&gt;Now there can also be a substantial machine-readable layer explaining how the application should be reasoned about, extended, tested, reviewed, and changed.&lt;/p&gt;
&lt;p&gt;That layer can contain real intellectual capital.&lt;/p&gt;
&lt;p&gt;We are going to need better norms around it.&lt;/p&gt;
&lt;p&gt;Some of it clearly belongs to the client.&lt;/p&gt;
&lt;p&gt;Some of it clearly belongs to the developer.&lt;/p&gt;
&lt;p&gt;Some of it will need to be explicitly negotiated.&lt;/p&gt;
&lt;p&gt;But treating everything inside a working directory as automatically belonging to the same commercial category is becoming increasingly difficult to defend.&lt;/p&gt;
&lt;p&gt;The lesson I am taking forward is simple:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The client should receive a system they can genuinely operate without me.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;But that does not necessarily mean they need the entire system I use to make myself effective while building it.&lt;/p&gt;
&lt;p&gt;The code is the deliverable.&lt;/p&gt;
&lt;p&gt;The documentation required to understand and operate it is part of the deliverable.&lt;/p&gt;
&lt;p&gt;The evolving development system behind it might not be.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/code-is-the-deliverable-development-system-not"/>
        </item>
        <item>
            <title><![CDATA[Keeping Files Local While Moving Their Git History to a Private Repository]]></title>
            <description><![CDATA[<p>While reorganizing a development workspace, I wanted internal documents and tests to remain at their familiar project paths. I also wanted their future changes tracked in a private repository. Symlinks made that possible, but the useful insight is broader: <strong>the path you use to open a file and the Git repository that tracks it are separate decisions.</strong></p>
<h2>What happens when you split them</h2>
<!-- bwm:slider keep-files-local-move-git-history-private-repository/workspace-history-split -->
<div data-slider="true" data-slider-id="keep-files-local-move-git-history-private-repository/workspace-history-split" data-slider-source="video/src/articles/keep-files-local-move-git-history-private-repository/workspace-history-split">
  <img src="https://img.buildwithmatija.com/api/images/i3dol7kv/file/original" alt="The Workspace Collision: Internal notes, agent configs, and tests shouldn't pollute the client repository, but moving them breaks editor habits." title="The Workspace Collision" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/3gpgyaaf/file/original" alt="The Path is a Doorway, Not an Index: The path you use to open a file in your editor and the Git repository that tracks it are independent decisions." title="The Path is a Doorway, Not an Index" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/e9f0ys01/file/original" alt="Extracting History Without Leakage: git-filter-repo rewrites commit history in seconds, moving commits into the private repo while erasing them from the upstream log." title="Extracting History Without Leakage" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/ffec2kij/file/original" alt="Clean Application, Private Memory: The app repo stays clean for CI and collaborators; your private repo tracks notes, prompts, and playbooks." title="Clean Application, Private Memory" width="1080" height="1080" />
</div>
<!-- /bwm:slider --><p>Imagine an application at <code>~/work/app</code> and a private workspace at <code>~/work/private/app-workspace</code>. The documents physically live in the private workspace. <code>~/work/app/docs</code> is a symlink pointing to them.</p>
<p>An editor can still open <code>~/work/app/docs/architecture.md</code>. Saving it changes the private file, so <code>git status</code> in the private repository reports the edit. The application repository ignores the local symlink.</p>
<p>Think of the application path as a doorway. It gets you to the document; it does not decide which Git index records changes to it.</p>
<h2>When this is useful</h2>
<p>This fits internal documentation, reports, agent configuration, and other working files that you want beside an application during development but under a separate repository boundary.</p>
<p>It needs more thought for files used by automated builds or CI. A clean clone of the application repository will not contain your local symlinks. If that clone needs the files, its environment must also receive the private workspace.</p>
<h2>A guide to making the move</h2>
<p>The example below moves <code>docs/</code>. Repeat the same checks for each additional directory. Run it only after reviewing the paths in your own repository.</p>
<h3>1. Back up the current files</h3>
<p>A filtered Git history contains committed files; it will not capture your current uncommitted edits. Back up the working directory first.</p>
<pre><code class="language-bash">APP_DIR=&quot;$HOME/work/app&quot;
PRIVATE_DIR=&quot;$HOME/work/private/app-workspace&quot;
BACKUP_DIR=&quot;$HOME/backups/app-workspace-$(date +%Y%m%d-%H%M%S)&quot;

mkdir -p &quot;$BACKUP_DIR&quot;
tar -czf &quot;$BACKUP_DIR/source.tar.gz&quot; -C &quot;$APP_DIR&quot; docs
tar -tzf &quot;$BACKUP_DIR/source.tar.gz&quot; &gt;/dev/null
</code></pre>
<p>Check <code>git status</code> in the application repository and note any edits or renames under <code>docs/</code>.</p>
<h3>2. Extract the committed history</h3>
<p>Use a temporary clone. This leaves the application repository’s history untouched.</p>
<pre><code class="language-bash">git clone --no-local &quot;$APP_DIR&quot; &quot;$BACKUP_DIR/history&quot;

git -C &quot;$BACKUP_DIR/history&quot; filter-repo \
  --path docs/ \
  --force
</code></pre>
<p>Inspect the result before publishing it. Its current tree should contain the intended private paths and no application code. <code>git-filter-repo</code> may remove the temporary clone’s original remote; that is expected.</p>
<h3>3. Create and populate the private repository</h3>
<p>Create an empty <strong>private</strong> GitHub repository, then push the filtered <code>main</code> history. The example assumes GitHub CLI authentication is already set up.</p>
<pre><code class="language-bash">GH_USER=$(gh api user --jq .login)

gh repo create &quot;$GH_USER/app-workspace&quot; --private

git -C &quot;$BACKUP_DIR/history&quot; remote add origin \
  &quot;git@github.com:$GH_USER/app-workspace.git&quot;

git -C &quot;$BACKUP_DIR/history&quot; push -u origin main

mkdir -p &quot;$(dirname &quot;$PRIVATE_DIR&quot;)&quot;
git clone &quot;git@github.com:$GH_USER/app-workspace.git&quot; &quot;$PRIVATE_DIR&quot;

gh repo view &quot;$GH_USER/app-workspace&quot; \
  --json visibility --jq .visibility
</code></pre>
<p>Confirm the final command prints <code>PRIVATE</code>. Then copy the <strong>current</strong> local files into that checkout. The <code>--delete</code> option makes renames and deletions match the source directory, which is why the backup comes first.</p>
<pre><code class="language-bash">rsync -a --delete --exclude=&#39;.git&#39; \
  &quot;$APP_DIR/docs/&quot; &quot;$PRIVATE_DIR/docs/&quot;
</code></pre>
<p>Review <code>git -C &quot;$PRIVATE_DIR&quot; status --short</code> before staging. Add private ignore rules for generated files and keep credentials out of the commit. Once the current contents look right, commit and push them in the private repository.</p>
<h3>4. Replace the application directory with a local symlink</h3>
<p>Only do this after confirming the private checkout has the current files. Remove the tracked paths from the application repository’s <strong>index</strong>, keep the original directory in the backup, and create the link.</p>
<pre><code class="language-bash">printf &#39;docs\n&#39; &gt;&gt; &quot;$APP_DIR/.git/info/exclude&quot;

git -C &quot;$APP_DIR&quot; rm -r --cached -- docs

mv &quot;$APP_DIR/docs&quot; &quot;$BACKUP_DIR/docs&quot;
ln -s &quot;$PRIVATE_DIR/docs&quot; &quot;$APP_DIR/docs&quot;
</code></pre>
<p>The <code>--cached</code> flag matters: it stages Git’s removal of <code>docs/</code> without deleting the working files. The entry in <code>.git/info/exclude</code> ignores the new symlink on this machine without putting the private workspace path in a committed <code>.gitignore</code>.</p>
<h3>5. Check both sides before committing the application change</h3>
<p>Confirm the familiar path still works and the symlink is locally ignored.</p>
<pre><code class="language-bash">test -d &quot;$APP_DIR/docs&quot;
git -C &quot;$APP_DIR&quot; check-ignore -v --no-index docs

git -C &quot;$PRIVATE_DIR&quot; status --short
git -C &quot;$APP_DIR&quot; status --short
</code></pre>
<p>Make one temporary edit under the private <code>docs/</code> directory. It should appear in the private repository’s status and remain accessible through <code>&quot;$APP_DIR/docs&quot;</code>. It should not appear as an untracked file in the application repository. Remove the probe, review the application’s staged diff, and only then commit its tracked-file removals.</p>
<h2>The gotchas I ran into</h2>
<p><strong>An ignore rule does not untrack a file.</strong> Git continues tracking a path already in its index. That is why the move requires <code>git rm --cached</code> before the ignored symlink behaves as intended.</p>
<p><strong>Test files are sensitive to physical paths.</strong> When tests live behind a symlink, Node may resolve them at their location in the private checkout. Relative imports, package resolution, and fixtures can then point somewhere new. In my workspace, local links back to application code and dependencies were needed, and a test that inferred the repository root from its own file path had to use the application working directory instead. Verify the actual test runner before moving <code>tests/</code>.</p>
<p><strong>Older application commits still contain the old files.</strong> This process changes current tracking and preserves the selected history in the private repository. It does not erase historical copies from the application repository.</p>
<h2>Conclusion</h2>
<p>A symlink preserves a useful local path while Git tracks the underlying files in a separate repository. Use this when the local workflow benefits from those familiar paths and each repository’s contents are clear. Keep a directory in the application repository when an application-only clone must have it.</p>
<p>If you would rather keep a separate repository checked out inside the main one, <a href="/blog/git-submodules-nested-repositories-guide">Git submodules</a> are the alternative to symlinks.</p>
<p>If you have questions or ran into a different gotcha, drop a comment below. And if you found this useful, subscribe for more.</p>
<p>Thanks,<br>Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/keep-files-local-move-git-history-private-repository</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/keep-files-local-move-git-history-private-repository</guid>
            <category><![CDATA[Tools]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;While reorganizing a development workspace, I wanted internal documents and tests to remain at their familiar project paths. I also wanted their future changes tracked in a private repository. Symlinks made that possible, but the useful insight is broader: &lt;strong&gt;the path you use to open a file and the Git repository that tracks it are separate decisions.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;What happens when you split them&lt;/h2&gt;
&lt;!-- bwm:slider keep-files-local-move-git-history-private-repository/workspace-history-split --&gt;
&lt;div data-slider=&quot;true&quot; data-slider-id=&quot;keep-files-local-move-git-history-private-repository/workspace-history-split&quot; data-slider-source=&quot;video/src/articles/keep-files-local-move-git-history-private-repository/workspace-history-split&quot;&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/i3dol7kv/file/original&quot; alt=&quot;The Workspace Collision: Internal notes, agent configs, and tests shouldn&apos;t pollute the client repository, but moving them breaks editor habits.&quot; title=&quot;The Workspace Collision&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/3gpgyaaf/file/original&quot; alt=&quot;The Path is a Doorway, Not an Index: The path you use to open a file in your editor and the Git repository that tracks it are independent decisions.&quot; title=&quot;The Path is a Doorway, Not an Index&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/e9f0ys01/file/original&quot; alt=&quot;Extracting History Without Leakage: git-filter-repo rewrites commit history in seconds, moving commits into the private repo while erasing them from the upstream log.&quot; title=&quot;Extracting History Without Leakage&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/ffec2kij/file/original&quot; alt=&quot;Clean Application, Private Memory: The app repo stays clean for CI and collaborators; your private repo tracks notes, prompts, and playbooks.&quot; title=&quot;Clean Application, Private Memory&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
&lt;/div&gt;
&lt;!-- /bwm:slider --&gt;&lt;p&gt;Imagine an application at &lt;code&gt;~/work/app&lt;/code&gt; and a private workspace at &lt;code&gt;~/work/private/app-workspace&lt;/code&gt;. The documents physically live in the private workspace. &lt;code&gt;~/work/app/docs&lt;/code&gt; is a symlink pointing to them.&lt;/p&gt;
&lt;p&gt;An editor can still open &lt;code&gt;~/work/app/docs/architecture.md&lt;/code&gt;. Saving it changes the private file, so &lt;code&gt;git status&lt;/code&gt; in the private repository reports the edit. The application repository ignores the local symlink.&lt;/p&gt;
&lt;p&gt;Think of the application path as a doorway. It gets you to the document; it does not decide which Git index records changes to it.&lt;/p&gt;
&lt;h2&gt;When this is useful&lt;/h2&gt;
&lt;p&gt;This fits internal documentation, reports, agent configuration, and other working files that you want beside an application during development but under a separate repository boundary.&lt;/p&gt;
&lt;p&gt;It needs more thought for files used by automated builds or CI. A clean clone of the application repository will not contain your local symlinks. If that clone needs the files, its environment must also receive the private workspace.&lt;/p&gt;
&lt;h2&gt;A guide to making the move&lt;/h2&gt;
&lt;p&gt;The example below moves &lt;code&gt;docs/&lt;/code&gt;. Repeat the same checks for each additional directory. Run it only after reviewing the paths in your own repository.&lt;/p&gt;
&lt;h3&gt;1. Back up the current files&lt;/h3&gt;
&lt;p&gt;A filtered Git history contains committed files; it will not capture your current uncommitted edits. Back up the working directory first.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;APP_DIR=&amp;quot;$HOME/work/app&amp;quot;
PRIVATE_DIR=&amp;quot;$HOME/work/private/app-workspace&amp;quot;
BACKUP_DIR=&amp;quot;$HOME/backups/app-workspace-$(date +%Y%m%d-%H%M%S)&amp;quot;

mkdir -p &amp;quot;$BACKUP_DIR&amp;quot;
tar -czf &amp;quot;$BACKUP_DIR/source.tar.gz&amp;quot; -C &amp;quot;$APP_DIR&amp;quot; docs
tar -tzf &amp;quot;$BACKUP_DIR/source.tar.gz&amp;quot; &amp;gt;/dev/null
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Check &lt;code&gt;git status&lt;/code&gt; in the application repository and note any edits or renames under &lt;code&gt;docs/&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;2. Extract the committed history&lt;/h3&gt;
&lt;p&gt;Use a temporary clone. This leaves the application repository’s history untouched.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;git clone --no-local &amp;quot;$APP_DIR&amp;quot; &amp;quot;$BACKUP_DIR/history&amp;quot;

git -C &amp;quot;$BACKUP_DIR/history&amp;quot; filter-repo \
  --path docs/ \
  --force
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Inspect the result before publishing it. Its current tree should contain the intended private paths and no application code. &lt;code&gt;git-filter-repo&lt;/code&gt; may remove the temporary clone’s original remote; that is expected.&lt;/p&gt;
&lt;h3&gt;3. Create and populate the private repository&lt;/h3&gt;
&lt;p&gt;Create an empty &lt;strong&gt;private&lt;/strong&gt; GitHub repository, then push the filtered &lt;code&gt;main&lt;/code&gt; history. The example assumes GitHub CLI authentication is already set up.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;GH_USER=$(gh api user --jq .login)

gh repo create &amp;quot;$GH_USER/app-workspace&amp;quot; --private

git -C &amp;quot;$BACKUP_DIR/history&amp;quot; remote add origin \
  &amp;quot;git@github.com:$GH_USER/app-workspace.git&amp;quot;

git -C &amp;quot;$BACKUP_DIR/history&amp;quot; push -u origin main

mkdir -p &amp;quot;$(dirname &amp;quot;$PRIVATE_DIR&amp;quot;)&amp;quot;
git clone &amp;quot;git@github.com:$GH_USER/app-workspace.git&amp;quot; &amp;quot;$PRIVATE_DIR&amp;quot;

gh repo view &amp;quot;$GH_USER/app-workspace&amp;quot; \
  --json visibility --jq .visibility
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Confirm the final command prints &lt;code&gt;PRIVATE&lt;/code&gt;. Then copy the &lt;strong&gt;current&lt;/strong&gt; local files into that checkout. The &lt;code&gt;--delete&lt;/code&gt; option makes renames and deletions match the source directory, which is why the backup comes first.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;rsync -a --delete --exclude=&amp;#39;.git&amp;#39; \
  &amp;quot;$APP_DIR/docs/&amp;quot; &amp;quot;$PRIVATE_DIR/docs/&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Review &lt;code&gt;git -C &amp;quot;$PRIVATE_DIR&amp;quot; status --short&lt;/code&gt; before staging. Add private ignore rules for generated files and keep credentials out of the commit. Once the current contents look right, commit and push them in the private repository.&lt;/p&gt;
&lt;h3&gt;4. Replace the application directory with a local symlink&lt;/h3&gt;
&lt;p&gt;Only do this after confirming the private checkout has the current files. Remove the tracked paths from the application repository’s &lt;strong&gt;index&lt;/strong&gt;, keep the original directory in the backup, and create the link.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;printf &amp;#39;docs\n&amp;#39; &amp;gt;&amp;gt; &amp;quot;$APP_DIR/.git/info/exclude&amp;quot;

git -C &amp;quot;$APP_DIR&amp;quot; rm -r --cached -- docs

mv &amp;quot;$APP_DIR/docs&amp;quot; &amp;quot;$BACKUP_DIR/docs&amp;quot;
ln -s &amp;quot;$PRIVATE_DIR/docs&amp;quot; &amp;quot;$APP_DIR/docs&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;code&gt;--cached&lt;/code&gt; flag matters: it stages Git’s removal of &lt;code&gt;docs/&lt;/code&gt; without deleting the working files. The entry in &lt;code&gt;.git/info/exclude&lt;/code&gt; ignores the new symlink on this machine without putting the private workspace path in a committed &lt;code&gt;.gitignore&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;5. Check both sides before committing the application change&lt;/h3&gt;
&lt;p&gt;Confirm the familiar path still works and the symlink is locally ignored.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;test -d &amp;quot;$APP_DIR/docs&amp;quot;
git -C &amp;quot;$APP_DIR&amp;quot; check-ignore -v --no-index docs

git -C &amp;quot;$PRIVATE_DIR&amp;quot; status --short
git -C &amp;quot;$APP_DIR&amp;quot; status --short
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Make one temporary edit under the private &lt;code&gt;docs/&lt;/code&gt; directory. It should appear in the private repository’s status and remain accessible through &lt;code&gt;&amp;quot;$APP_DIR/docs&amp;quot;&lt;/code&gt;. It should not appear as an untracked file in the application repository. Remove the probe, review the application’s staged diff, and only then commit its tracked-file removals.&lt;/p&gt;
&lt;h2&gt;The gotchas I ran into&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;An ignore rule does not untrack a file.&lt;/strong&gt; Git continues tracking a path already in its index. That is why the move requires &lt;code&gt;git rm --cached&lt;/code&gt; before the ignored symlink behaves as intended.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Test files are sensitive to physical paths.&lt;/strong&gt; When tests live behind a symlink, Node may resolve them at their location in the private checkout. Relative imports, package resolution, and fixtures can then point somewhere new. In my workspace, local links back to application code and dependencies were needed, and a test that inferred the repository root from its own file path had to use the application working directory instead. Verify the actual test runner before moving &lt;code&gt;tests/&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Older application commits still contain the old files.&lt;/strong&gt; This process changes current tracking and preserves the selected history in the private repository. It does not erase historical copies from the application repository.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;A symlink preserves a useful local path while Git tracks the underlying files in a separate repository. Use this when the local workflow benefits from those familiar paths and each repository’s contents are clear. Keep a directory in the application repository when an application-only clone must have it.&lt;/p&gt;
&lt;p&gt;If you would rather keep a separate repository checked out inside the main one, &lt;a href=&quot;/blog/git-submodules-nested-repositories-guide&quot;&gt;Git submodules&lt;/a&gt; are the alternative to symlinks.&lt;/p&gt;
&lt;p&gt;If you have questions or ran into a different gotcha, drop a comment below. And if you found this useful, subscribe for more.&lt;/p&gt;
&lt;p&gt;Thanks,&lt;br&gt;Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/keep-files-local-move-git-history-private-repository"/>
        </item>
        <item>
            <title><![CDATA[Remotion vs Motion Canvas: The Two Mental Models of Code-Driven Video]]></title>
            <description><![CDATA[<p>When developers first hear about &quot;code-to-video,&quot; most assume all tools operate on the same mental model: write some TypeScript, define an animation, and let a headless compiler spit out an MP4. </p>
<p>That assumption works until you actually try to build something. The moment you need to render an existing React component or choreograph a complex multi-node vector path, the ecosystem splits into two fundamentally opposed camps. On one side is Remotion, which approaches video as a declarative series of React DOM snapshots. On the other side is Motion Canvas, which treats video as an imperative, procedural timeline executed against an HTML5 canvas.</p>
<p>They both produce MP4 files, but they are built for entirely different problems. Picking between them is not a matter of feature checklists. It is a decision about whether you are animating web user interfaces or authoring motion graphics from scratch.</p>
<hr>
<h2>What It Is</h2>
<p>Remotion is a framework that brings video rendering to standard React. You write ordinary TSX components with HTML elements, Tailwind CSS classes, inline SVG paths, and custom React hooks. Instead of keyframes on a timeline, Remotion gives you a frame counter via <code>useCurrentFrame()</code>. When you export a video, Remotion opens a headless instance of Chromium, renders your React tree at every single frame mark (frame 0, frame 1, frame 2), takes screenshots, and pipes those rasterized frames into an <code>ffmpeg</code> process to encode a video file.</p>
<p>Motion Canvas is an imperative vector animation engine written in TypeScript and powered by Vite. It does not use the DOM, CSS, or standard web layout engines. Instead, it renders entirely to an HTML5 <code>&lt;canvas&gt;</code> context using procedural generator functions (<code>function*</code>). Animations are expressed sequentially through <code>yield*</code> expressions that pause and resume execution as virtual time elapses.</p>
<hr>
<h2>The Mental Model: <code>UI = f(frame)</code> vs The Coroutine Timeline</h2>
<!-- bwm:slider remotion-vs-motion-canvas-code-driven-video/two-mental-models -->
<div data-slider="true" data-slider-id="remotion-vs-motion-canvas-code-driven-video/two-mental-models" data-slider-source="video/src/articles/remotion-vs-motion-canvas-code-driven-video/two-mental-models">
  <img src="https://img.buildwithmatija.com/api/images/htrrvi0v/file/original" alt="The Fundamental Divide: Both produce MP4s, but Remotion animates React DOM snapshots while Motion Canvas animates canvas vectors imperatively." title="The Fundamental Divide" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/86alydia/file/original" alt="Remotion: Declarative f(frame): Any frame can be rendered in parallel out-of-order because components are stateless functions of the frame index." title="Remotion: Declarative f(frame)" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/24k2tuuu/file/original" alt="Motion Canvas: Coroutine Timeline: Procedural generator functions pause and resume as virtual time elapses through yield* expressions." title="Motion Canvas: Coroutine Timeline" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/jhby9sk0/file/original" alt="The Decision Matrix: Reach for Remotion when animating Web UI &amp; components; reach for Motion Canvas for standalone motion graphics." title="The Decision Matrix" width="1080" height="1080" />
</div>
<!-- /bwm:slider --><p>To understand why these tools feel so different to write, consider how they represent time.</p>
<p>Remotion operates on the classic React paradigm where UI is a pure function of state, except here the primary state variable is the current frame number: <code>UI = f(frame)</code>. There is no concept of &quot;waiting two seconds and then moving.&quot; Instead, every component must be able to calculate its exact visual appearance at any arbitrary point in time independently:</p>
<pre><code class="language-tsx">// File: src/scenes/CardPreview.tsx
import { useCurrentFrame, interpolate } from &#39;remotion&#39;;

export function CardPreview() {
  const frame = useCurrentFrame();
  const opacity = interpolate(frame, [0, 30], [0, 1], { extrapolateRight: &#39;clamp&#39; });
  const translateY = interpolate(frame, [0, 30], [20, 0], { extrapolateRight: &#39;clamp&#39; });

  return (
    &lt;div style={{ opacity, transform: `translateY(${translateY}px)` }} className=&quot;bg-slate-900 p-6 rounded-xl&quot;&gt;
      &lt;h2 className=&quot;text-white font-semibold&quot;&gt;Architecture Overview&lt;/h2&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>If you scrub the playhead directly to frame 15, Remotion does not need to execute frames 0 through 14. It simply evaluates the equation for <code>frame = 15</code>.</p>
<p>Motion Canvas inverts this completely. It uses TypeScript generator functions as coroutines, modeling time as an unfolding story. You write imperative instructions that block the execution thread until the animation step completes:</p>
<pre><code class="language-ts">// File: src/scenes/architecture.ts
import { makeScene2D, Circle, createRef, all } from &#39;@motion-canvas/2d&#39;;

export default makeScene2D(function* (view) {
  const circle = createRef&lt;Circle&gt;();
  view.add(&lt;Circle ref={circle} size={80} fill=&quot;#38bdf8&quot; /&gt;);

  // Execution pauses here for 1.0 second while the circle animates
  yield* circle().size(160, 1.0);
  
  // Only runs after the previous line completes
  yield* circle().position.x(300, 0.8);
});
</code></pre>
<p>Because of this generator architecture, Motion Canvas thinks like an animator. You tell an object to move, wait for it to arrive, and then trigger the next reaction.</p>
<hr>
<h2>When To Use It</h2>
<h3>Reach for Remotion when your video content is based on Web UI</h3>
<p>If your goal is to showcase product interfaces, automate social preview cards from database records, turn blog architecture diagrams into teaser videos, or animate real application dashboards, Remotion is almost always the right tool. You can copy-paste your production Tailwind classes, import your existing design system components, use real typography stacks, and render SVG icons directly from libraries like Lucide. You do not have to recreate your web app inside a bespoke animation dialect because Remotion literally runs your web app.</p>
<h3>Reach for Motion Canvas when you are building explanatory motion graphics</h3>
<p>If you are producing educational videos, explaining complex algorithms, animating interconnected graph nodes, or demonstrating mathematical concepts (similar to 3Blue1Brown-style visualizations), Motion Canvas is vastly superior. Its vector math engine understands path tweening, signal routing, arrow attachments, and camera coordinates out of the box. Choreographing five interacting vector nodes in Motion Canvas takes twenty lines of clean, readable generator code; attempting the same choreography in Remotion requires complex coordinate math mapped across multiple frame interpolators.</p>
<hr>
<h2>When NOT To Use It</h2>
<p>Do not reach for Remotion if you need character animation, physics-heavy vector simulations, or complex morphing paths. Because Remotion relies on the browser DOM, pushing thousands of simultaneous SVG nodes or running intensive canvas computations frame-by-frame will degrade render speeds to a crawl. The DOM is an excellent document layout engine, but it is an inefficient canvas for raw geometric motion.</p>
<p>Conversely, do not use Motion Canvas if you expect to drop in your company&#39;s React components, CSS stylesheets, or markdown renderers. Motion Canvas has no DOM. You cannot use Flexbox, CSS Grid, or Tailwind utilities. Every layout box, text node, and border radius must be explicitly constructed using Motion Canvas&#39;s proprietary 2D node primitives. If your design relies on complex responsive text reflow or styled HTML markup, recreating that inside a canvas engine will waste hours of developer time.</p>
<hr>
<h2>Gotchas &amp; Common Mistakes</h2>
<h3>1. Asynchronous Layout Desynchronization in Remotion</h3>
<p>The most common mistake when starting with Remotion is fetching data, loading web fonts, or executing asynchronous layout work inside a standard <code>useEffect</code> without notifying the rendering engine. When Remotion exports a video via headless Chromium, it captures frames as fast as the CPU allows. If your custom font or API payload takes 200 milliseconds to resolve, Chromium may capture frames 0 through 15 before your layout finishes painting, leading to visual flickering or layout shifts in the final MP4. You must explicitly gate frame progression using Remotion&#39;s <code>delayRender</code> and <code>continueRender</code> handles until all external typography and network assets are verified in memory.</p>
<h3>2. Assuming Motion Canvas JSX is React</h3>
<p>Developers frequently see TSX angle brackets in Motion Canvas examples and assume they can import standard React packages or npm UI libraries. It is a visual trick of TypeScript tooling. Motion Canvas implements its own custom JSX runtime that constructs canvas scene-graph nodes, not React Virtual DOM elements. Attempting to use React hooks like <code>useState</code> or importing third-party React components will trigger immediate runtime errors.</p>
<h3>3. Overlooking Commercial Licensing Boundaries</h3>
<p>Motion Canvas is published under the standard MIT license, giving you unrestricted freedom for personal, open-source, and commercial projects without financial caps. Remotion, while source-available and free for individuals and companies with up to three people, uses a custom commercial license. If you are building automated video infrastructure inside a larger enterprise, you will need an active paid commercial license. Discovering this after wiring your entire publishing pipeline into Remotion can create unexpected procurement friction.</p>
<hr>
<h2>Conclusion</h2>
<p>Remotion and Motion Canvas represent two distinct answers to the code-driven video challenge. Remotion treats video as a progression of React states, making it the natural extension for web engineering teams who want to leverage their existing HTML, CSS, and component systems. Motion Canvas treats video as a timeline of coordinated procedural events, making it the premier choice for standalone technical explainers and mathematical vector graphics.</p>
<p>Reach for Remotion when your video content lives in the DOM. Reach for Motion Canvas when your video content lives in geometry.</p>
<p>If you have questions or ran into a different gotcha when setting up code-to-video pipelines, drop a comment below. And if you found this useful, subscribe for more practical frontend architecture breakdowns.</p>
<p>Thanks,<br>Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/remotion-vs-motion-canvas-code-driven-video</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/remotion-vs-motion-canvas-code-driven-video</guid>
            <category><![CDATA[Tools]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;When developers first hear about &amp;quot;code-to-video,&amp;quot; most assume all tools operate on the same mental model: write some TypeScript, define an animation, and let a headless compiler spit out an MP4. &lt;/p&gt;
&lt;p&gt;That assumption works until you actually try to build something. The moment you need to render an existing React component or choreograph a complex multi-node vector path, the ecosystem splits into two fundamentally opposed camps. On one side is Remotion, which approaches video as a declarative series of React DOM snapshots. On the other side is Motion Canvas, which treats video as an imperative, procedural timeline executed against an HTML5 canvas.&lt;/p&gt;
&lt;p&gt;They both produce MP4 files, but they are built for entirely different problems. Picking between them is not a matter of feature checklists. It is a decision about whether you are animating web user interfaces or authoring motion graphics from scratch.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;What It Is&lt;/h2&gt;
&lt;p&gt;Remotion is a framework that brings video rendering to standard React. You write ordinary TSX components with HTML elements, Tailwind CSS classes, inline SVG paths, and custom React hooks. Instead of keyframes on a timeline, Remotion gives you a frame counter via &lt;code&gt;useCurrentFrame()&lt;/code&gt;. When you export a video, Remotion opens a headless instance of Chromium, renders your React tree at every single frame mark (frame 0, frame 1, frame 2), takes screenshots, and pipes those rasterized frames into an &lt;code&gt;ffmpeg&lt;/code&gt; process to encode a video file.&lt;/p&gt;
&lt;p&gt;Motion Canvas is an imperative vector animation engine written in TypeScript and powered by Vite. It does not use the DOM, CSS, or standard web layout engines. Instead, it renders entirely to an HTML5 &lt;code&gt;&amp;lt;canvas&amp;gt;&lt;/code&gt; context using procedural generator functions (&lt;code&gt;function*&lt;/code&gt;). Animations are expressed sequentially through &lt;code&gt;yield*&lt;/code&gt; expressions that pause and resume execution as virtual time elapses.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;The Mental Model: &lt;code&gt;UI = f(frame)&lt;/code&gt; vs The Coroutine Timeline&lt;/h2&gt;
&lt;!-- bwm:slider remotion-vs-motion-canvas-code-driven-video/two-mental-models --&gt;
&lt;div data-slider=&quot;true&quot; data-slider-id=&quot;remotion-vs-motion-canvas-code-driven-video/two-mental-models&quot; data-slider-source=&quot;video/src/articles/remotion-vs-motion-canvas-code-driven-video/two-mental-models&quot;&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/htrrvi0v/file/original&quot; alt=&quot;The Fundamental Divide: Both produce MP4s, but Remotion animates React DOM snapshots while Motion Canvas animates canvas vectors imperatively.&quot; title=&quot;The Fundamental Divide&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/86alydia/file/original&quot; alt=&quot;Remotion: Declarative f(frame): Any frame can be rendered in parallel out-of-order because components are stateless functions of the frame index.&quot; title=&quot;Remotion: Declarative f(frame)&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/24k2tuuu/file/original&quot; alt=&quot;Motion Canvas: Coroutine Timeline: Procedural generator functions pause and resume as virtual time elapses through yield* expressions.&quot; title=&quot;Motion Canvas: Coroutine Timeline&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/jhby9sk0/file/original&quot; alt=&quot;The Decision Matrix: Reach for Remotion when animating Web UI &amp;amp; components; reach for Motion Canvas for standalone motion graphics.&quot; title=&quot;The Decision Matrix&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
&lt;/div&gt;
&lt;!-- /bwm:slider --&gt;&lt;p&gt;To understand why these tools feel so different to write, consider how they represent time.&lt;/p&gt;
&lt;p&gt;Remotion operates on the classic React paradigm where UI is a pure function of state, except here the primary state variable is the current frame number: &lt;code&gt;UI = f(frame)&lt;/code&gt;. There is no concept of &amp;quot;waiting two seconds and then moving.&amp;quot; Instead, every component must be able to calculate its exact visual appearance at any arbitrary point in time independently:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;// File: src/scenes/CardPreview.tsx
import { useCurrentFrame, interpolate } from &amp;#39;remotion&amp;#39;;

export function CardPreview() {
  const frame = useCurrentFrame();
  const opacity = interpolate(frame, [0, 30], [0, 1], { extrapolateRight: &amp;#39;clamp&amp;#39; });
  const translateY = interpolate(frame, [0, 30], [20, 0], { extrapolateRight: &amp;#39;clamp&amp;#39; });

  return (
    &amp;lt;div style={{ opacity, transform: `translateY(${translateY}px)` }} className=&amp;quot;bg-slate-900 p-6 rounded-xl&amp;quot;&amp;gt;
      &amp;lt;h2 className=&amp;quot;text-white font-semibold&amp;quot;&amp;gt;Architecture Overview&amp;lt;/h2&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you scrub the playhead directly to frame 15, Remotion does not need to execute frames 0 through 14. It simply evaluates the equation for &lt;code&gt;frame = 15&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Motion Canvas inverts this completely. It uses TypeScript generator functions as coroutines, modeling time as an unfolding story. You write imperative instructions that block the execution thread until the animation step completes:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/scenes/architecture.ts
import { makeScene2D, Circle, createRef, all } from &amp;#39;@motion-canvas/2d&amp;#39;;

export default makeScene2D(function* (view) {
  const circle = createRef&amp;lt;Circle&amp;gt;();
  view.add(&amp;lt;Circle ref={circle} size={80} fill=&amp;quot;#38bdf8&amp;quot; /&amp;gt;);

  // Execution pauses here for 1.0 second while the circle animates
  yield* circle().size(160, 1.0);
  
  // Only runs after the previous line completes
  yield* circle().position.x(300, 0.8);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because of this generator architecture, Motion Canvas thinks like an animator. You tell an object to move, wait for it to arrive, and then trigger the next reaction.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;When To Use It&lt;/h2&gt;
&lt;h3&gt;Reach for Remotion when your video content is based on Web UI&lt;/h3&gt;
&lt;p&gt;If your goal is to showcase product interfaces, automate social preview cards from database records, turn blog architecture diagrams into teaser videos, or animate real application dashboards, Remotion is almost always the right tool. You can copy-paste your production Tailwind classes, import your existing design system components, use real typography stacks, and render SVG icons directly from libraries like Lucide. You do not have to recreate your web app inside a bespoke animation dialect because Remotion literally runs your web app.&lt;/p&gt;
&lt;h3&gt;Reach for Motion Canvas when you are building explanatory motion graphics&lt;/h3&gt;
&lt;p&gt;If you are producing educational videos, explaining complex algorithms, animating interconnected graph nodes, or demonstrating mathematical concepts (similar to 3Blue1Brown-style visualizations), Motion Canvas is vastly superior. Its vector math engine understands path tweening, signal routing, arrow attachments, and camera coordinates out of the box. Choreographing five interacting vector nodes in Motion Canvas takes twenty lines of clean, readable generator code; attempting the same choreography in Remotion requires complex coordinate math mapped across multiple frame interpolators.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;When NOT To Use It&lt;/h2&gt;
&lt;p&gt;Do not reach for Remotion if you need character animation, physics-heavy vector simulations, or complex morphing paths. Because Remotion relies on the browser DOM, pushing thousands of simultaneous SVG nodes or running intensive canvas computations frame-by-frame will degrade render speeds to a crawl. The DOM is an excellent document layout engine, but it is an inefficient canvas for raw geometric motion.&lt;/p&gt;
&lt;p&gt;Conversely, do not use Motion Canvas if you expect to drop in your company&amp;#39;s React components, CSS stylesheets, or markdown renderers. Motion Canvas has no DOM. You cannot use Flexbox, CSS Grid, or Tailwind utilities. Every layout box, text node, and border radius must be explicitly constructed using Motion Canvas&amp;#39;s proprietary 2D node primitives. If your design relies on complex responsive text reflow or styled HTML markup, recreating that inside a canvas engine will waste hours of developer time.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Gotchas &amp;amp; Common Mistakes&lt;/h2&gt;
&lt;h3&gt;1. Asynchronous Layout Desynchronization in Remotion&lt;/h3&gt;
&lt;p&gt;The most common mistake when starting with Remotion is fetching data, loading web fonts, or executing asynchronous layout work inside a standard &lt;code&gt;useEffect&lt;/code&gt; without notifying the rendering engine. When Remotion exports a video via headless Chromium, it captures frames as fast as the CPU allows. If your custom font or API payload takes 200 milliseconds to resolve, Chromium may capture frames 0 through 15 before your layout finishes painting, leading to visual flickering or layout shifts in the final MP4. You must explicitly gate frame progression using Remotion&amp;#39;s &lt;code&gt;delayRender&lt;/code&gt; and &lt;code&gt;continueRender&lt;/code&gt; handles until all external typography and network assets are verified in memory.&lt;/p&gt;
&lt;h3&gt;2. Assuming Motion Canvas JSX is React&lt;/h3&gt;
&lt;p&gt;Developers frequently see TSX angle brackets in Motion Canvas examples and assume they can import standard React packages or npm UI libraries. It is a visual trick of TypeScript tooling. Motion Canvas implements its own custom JSX runtime that constructs canvas scene-graph nodes, not React Virtual DOM elements. Attempting to use React hooks like &lt;code&gt;useState&lt;/code&gt; or importing third-party React components will trigger immediate runtime errors.&lt;/p&gt;
&lt;h3&gt;3. Overlooking Commercial Licensing Boundaries&lt;/h3&gt;
&lt;p&gt;Motion Canvas is published under the standard MIT license, giving you unrestricted freedom for personal, open-source, and commercial projects without financial caps. Remotion, while source-available and free for individuals and companies with up to three people, uses a custom commercial license. If you are building automated video infrastructure inside a larger enterprise, you will need an active paid commercial license. Discovering this after wiring your entire publishing pipeline into Remotion can create unexpected procurement friction.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Remotion and Motion Canvas represent two distinct answers to the code-driven video challenge. Remotion treats video as a progression of React states, making it the natural extension for web engineering teams who want to leverage their existing HTML, CSS, and component systems. Motion Canvas treats video as a timeline of coordinated procedural events, making it the premier choice for standalone technical explainers and mathematical vector graphics.&lt;/p&gt;
&lt;p&gt;Reach for Remotion when your video content lives in the DOM. Reach for Motion Canvas when your video content lives in geometry.&lt;/p&gt;
&lt;p&gt;If you have questions or ran into a different gotcha when setting up code-to-video pipelines, drop a comment below. And if you found this useful, subscribe for more practical frontend architecture breakdowns.&lt;/p&gt;
&lt;p&gt;Thanks,&lt;br&gt;Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/remotion-vs-motion-canvas-code-driven-video"/>
        </item>
        <item>
            <title><![CDATA[Remotion Tutorial: Build an Animated Video with React and TypeScript]]></title>
            <description><![CDATA[<p>I wanted to turn an article about Payload CMS 4.0 into a short animated teaser. The content already had useful visual ideas: an access-control comparison, a relationship-depth diagram, and two framework adapters sharing one core. Remotion let me turn those ideas into video using React components, TypeScript, CSS, and SVG.</p>
<p>Here is the finished 15-second video we will recreate:</p>
<video controls preload="metadata" poster="/remotion-guide/payload-4-0-poster.png" width="1920" height="1080">
  <source src="/remotion-guide/payload-4-0-teaser.mp4" type="video/mp4" />
  <source src="/remotion-guide/payload-4-0-teaser.webm" type="video/webm" />
  Your browser cannot play this video. <a href="/remotion-guide/payload-4-0-teaser.mp4">Download the MP4.</a>
</video><p>By the end, you will have the same five-scene video in two formats: 1920×1080 landscape and 1080×1080 square. You will also understand how Remotion connects a frame number to what appears on screen, how scenes get their own timelines, and how to make fonts and images ready before a frame is captured.</p>
<p>You should be comfortable with React components, hooks, TypeScript, and basic CSS. You do not need a Payload installation: all the Payload content in this example is text and graphics. The canary labels describe the example&#39;s subject; this tutorial is about creating its animation.</p>
<p>This is a complete implementation walkthrough. Each application source file appears below. The large component is split into consecutive blocks so we can discuss each part. Copy those blocks into the same file in the order shown.</p>
<h2>1. Understand what Remotion renders</h2>
<!-- bwm:slider remotion-react-video-tutorial/remotion-pipeline-scenes -->
<div data-slider="true" data-slider-id="remotion-react-video-tutorial/remotion-pipeline-scenes" data-slider-source="video/src/articles/remotion-react-video-tutorial/remotion-pipeline-scenes">
  <img src="https://img.buildwithmatija.com/api/images/b0062x4y/file/original" alt="UI = f(frame): The Mental Model: Remotion doesn't use timelines or keyframe tracks; every frame is a deterministic React render at frame N." title="UI = f(frame): The Mental Model" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/o3bbeuvz/file/original" alt="Isolated Timelines with &lt;Sequence&gt;: Break complex animations into modular scene components with localized frame counters." title="Isolated Timelines with &lt;Sequence&gt;" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/lf9r63si/file/original" alt="Natural Motion with spring(): Replace rigid linear easing with mass, damping, and stiffness for fluid UI physics." title="Natural Motion with spring()" width="1080" height="1080" />
  <img src="https://img.buildwithmatija.com/api/images/oorsixjy/file/original" alt="Responsive Video: 16:9 &amp; 1:1: Use responsive layout hooks to render widescreen YouTube video and square social feeds from one component." title="Responsive Video: 16:9 &amp; 1:1" width="1080" height="1080" />
</div>
<!-- /bwm:slider --><p>Think of a composition as a React component with a video-sized canvas and a timeline. Remotion supplies the current frame. Your component calculates positions, opacity, scale, and visible content for that frame.</p>
<p>At 60 frames per second, frame 60 represents one second into the video. Our composition lasts 900 frames, so its duration is <code>900 / 60 = 15</code> seconds. Frames are zero-based: the first is 0 and the last is 899.</p>
<p>In Studio, you can scrub directly to a frame and see the component at that point. During a local render, Remotion uses a browser to capture frames and encodes them into a video. The component must therefore produce the right visual even when you jump directly to a later frame.</p>
<p>This changes how you animate. A web page often starts a CSS transition after a click and lets time pass. In a Remotion composition, the current frame determines the animation state. There is no need to play the previous 100 frames to know how frame 101 should look. Remotion explicitly recommends frame-driven animation instead of CSS transitions and keyframes. <a href="https://www.remotion.dev/docs/troubleshooting/css-animations">Read the animation guidance</a>.</p>
<p>Our implementation uses two main tools: <code>interpolate()</code> for mapping progress to visual values, and <code>spring()</code> for entrances with a natural settling motion. Ordinary CSS still handles layout, typography, borders, gradients, and colors.</p>
<h2>2. Create an isolated video project</h2>
<p>Use Node.js 24 and pnpm 10.33.0 for this walkthrough. Create a fresh directory outside any existing pnpm workspace, so its dependencies and configuration belong to this example:</p>
<pre><code class="language-bash">mkdir remotion-payload-teaser
cd remotion-payload-teaser
mkdir -p src public/fonts out
</code></pre>
<p>All following shell commands run from this directory. Create the package file before installing anything. These are the versions used by the reference implementation; keep the Remotion packages on the same exact version.</p>
<p><strong>Create <code>package.json</code>:</strong></p>
<pre><code class="language-json">{
  &quot;name&quot;: &quot;bwm-payload-video&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;private&quot;: true,
  &quot;type&quot;: &quot;module&quot;,
  &quot;packageManager&quot;: &quot;pnpm@10.33.0&quot;,
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;remotion studio src/index.ts --port=3100&quot;,
    &quot;render:landscape&quot;: &quot;remotion render src/index.ts Payload4Teaser out/payload-4-0-teaser.mp4 --codec=h264 --pixel-format=yuv420p --crf=18 --concurrency=4 --color-space=bt709 --image-format=png&quot;,
    &quot;render:square&quot;: &quot;remotion render src/index.ts Payload4Square out/payload-4-0-square.mp4 --codec=h264 --pixel-format=yuv420p --crf=18 --concurrency=4 --color-space=bt709 --image-format=png&quot;,
    &quot;render:webm&quot;: &quot;remotion render src/index.ts Payload4Teaser out/payload-4-0-teaser.webm --codec=vp9 --video-bitrate=6M --concurrency=4 --color-space=bt709 --image-format=png&quot;,
    &quot;poster:landscape&quot;: &quot;remotion still src/index.ts Payload4Teaser out/payload-4-0-poster.png --frame=150&quot;,
    &quot;poster:square&quot;: &quot;remotion still src/index.ts Payload4Square out/payload-4-0-square-poster.png --frame=150&quot;
  },
  &quot;dependencies&quot;: {
    &quot;remotion&quot;: &quot;4.0.532&quot;,
    &quot;react&quot;: &quot;19.2.4&quot;,
    &quot;react-dom&quot;: &quot;19.2.4&quot;,
    &quot;lucide-react&quot;: &quot;0.475.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@remotion/cli&quot;: &quot;4.0.532&quot;,
    &quot;@remotion/tailwind-v4&quot;: &quot;4.0.532&quot;,
    &quot;@fontsource/inter&quot;: &quot;5.3.0&quot;,
    &quot;@fontsource/ibm-plex-mono&quot;: &quot;5.3.0&quot;,
    &quot;@types/react&quot;: &quot;19.2.2&quot;,
    &quot;@types/react-dom&quot;: &quot;19.2.2&quot;,
    &quot;typescript&quot;: &quot;5.9.3&quot;,
    &quot;tailwindcss&quot;: &quot;4.2.2&quot;,
    &quot;zod&quot;: &quot;4.5.4&quot;
  }
}
</code></pre>
<p>Install the dependencies:</p>
<pre><code class="language-bash">pnpm install
pnpm exec remotion versions
</code></pre>
<p>The first install generates <code>pnpm-lock.yaml</code>. Keep that lockfile with your project. Once it exists, use <code>pnpm install --frozen-lockfile</code> for repeat installations. You do not need to hand-write or copy hundreds of lockfile entries from an article.</p>
<p>React and React DOM render our components. Remotion supplies the timeline primitives. The CLI opens Studio and exports media. Lucide provides SVG icons, the Fontsource packages supply local font files, and the Tailwind integration processes the utility classes used by the layout. Zod is pinned in the reference package; this composition does not define a custom props schema.</p>
<p>The finished project will have this structure:</p>
<pre><code class="language-text">remotion-payload-teaser/
  package.json
  pnpm-lock.yaml                 # generated by pnpm install
  remotion.config.ts
  tsconfig.json
  src/
    index.ts
    Root.tsx
    Payload4Teaser.tsx
    style.css
  public/
    bwm-logo.svg
    author.jpeg
    fonts/
      inter-400.woff2
      inter-500.woff2
      inter-600.woff2
      inter-700.woff2
      plex-mono-400.woff2
      inter-LICENSE.txt
      ibm-plex-mono-LICENSE.txt
  out/                           # generated videos and stills
</code></pre>
<h3>Configure TypeScript and Tailwind</h3>
<p>The TypeScript configuration includes browser types because the font loader uses <code>FontFace</code> and <code>document.fonts</code>. This package is independent of any website&#39;s TypeScript configuration.</p>
<p><strong>Create <code>tsconfig.json</code>:</strong></p>
<pre><code class="language-json">{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;ES2022&quot;,
    &quot;lib&quot;: [&quot;DOM&quot;, &quot;ES2022&quot;, &quot;DOM.Iterable&quot;],
    &quot;jsx&quot;: &quot;react-jsx&quot;,
    &quot;module&quot;: &quot;ESNext&quot;,
    &quot;moduleResolution&quot;: &quot;Bundler&quot;,
    &quot;strict&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;noEmit&quot;: true
  },
  &quot;include&quot;: [&quot;src&quot;, &quot;remotion.config.ts&quot;]
}
</code></pre>
<p>Tailwind v4 needs a bundler integration in this project. Installing Tailwind alone does not make the classes in our components work. Use Remotion&#39;s <code>enableTailwind()</code> override. The overwrite setting allows subsequent exports to replace the same output filename. <a href="https://www.remotion.dev/docs/tailwind-v4/enable-tailwind">See the official integration</a>.</p>
<p><strong>Create <code>remotion.config.ts</code>:</strong></p>
<pre><code class="language-ts">import { Config } from &quot;@remotion/cli/config&quot;;
import { enableTailwind } from &quot;@remotion/tailwind-v4&quot;;

Config.overrideWebpackConfig((config) =&gt; enableTailwind(config));
Config.setOverwriteOutput(true);
</code></pre>
<p>The stylesheet imports Tailwind, points source scanning at this directory, and uses border-box sizing. It contains no time-based CSS animation.</p>
<p><strong>Create <code>src/style.css</code>:</strong></p>
<pre><code class="language-css">@import &quot;tailwindcss&quot;;
@source &#39;./&#39;;

* {
  box-sizing: border-box;
}
</code></pre>
<h3>Prepare the images and fonts</h3>
<p>Download the <a href="/remotion-guide/assets/bwm-logo.svg">example logo</a> and <a href="/remotion-guide/assets/author.jpeg">author portrait</a> into <code>public/</code>, keeping their filenames. These are the assets shown in the video. For your own video, replace them with your branding.</p>
<p>On macOS or Linux, you can download them from the site with:</p>
<pre><code class="language-bash">curl --fail --location https://buildwithmatija.com/remotion-guide/assets/bwm-logo.svg --output public/bwm-logo.svg
curl --fail --location https://buildwithmatija.com/remotion-guide/assets/author.jpeg --output public/author.jpeg
</code></pre>
<p>Copy the font files from the packages you just installed, and rename them to match the paths our component will request:</p>
<pre><code class="language-bash">for weight in 400 500 600 700; do
  cp &quot;node_modules/@fontsource/inter/files/inter-latin-${weight}-normal.woff2&quot; &quot;public/fonts/inter-${weight}.woff2&quot;
done
cp node_modules/@fontsource/ibm-plex-mono/files/ibm-plex-mono-latin-400-normal.woff2 public/fonts/plex-mono-400.woff2
cp node_modules/@fontsource/inter/LICENSE public/fonts/inter-LICENSE.txt
cp node_modules/@fontsource/ibm-plex-mono/LICENSE public/fonts/ibm-plex-mono-LICENSE.txt
</code></pre>
<p>The Latin subset covers the example&#39;s text. If you adapt it to another writing system, select a font subset that includes those characters.</p>
<p>Remotion&#39;s <code>staticFile()</code> resolves assets from the project&#39;s <code>public/</code> directory. We will use it for both the images and fonts, rather than relying on a website-relative URL. <a href="https://www.remotion.dev/docs/staticfile">See <code>staticFile()</code></a>.</p>
<h2>3. Register the entrypoint and compositions</h2>
<p>The CLI needs an entrypoint that registers our root component.</p>
<p><strong>Create <code>src/index.ts</code>:</strong></p>
<pre><code class="language-ts">import { registerRoot } from &quot;remotion&quot;;
import { RemotionRoot } from &quot;./Root&quot;;

registerRoot(RemotionRoot);
</code></pre>
<p>The root registers two compositions. Each points to the same React component, but supplies different canvas dimensions. The IDs are what the render scripts select. <a href="https://www.remotion.dev/docs/composition">See the composition API</a>.</p>
<p><strong>Create <code>src/Root.tsx</code>:</strong></p>
<pre><code class="language-tsx">import { Composition } from &quot;remotion&quot;;
import { Payload4Teaser } from &quot;./Payload4Teaser&quot;;

export const RemotionRoot = () =&gt; {
  return (
    &lt;&gt;
      &lt;Composition
        id=&quot;Payload4Teaser&quot;
        component={Payload4Teaser}
        durationInFrames={900}
        fps={60}
        width={1920}
        height={1080}
        defaultProps={{
          title: &quot;Payload CMS 4.0: Breaking Changes &amp; Canary Deep Dive&quot;,
          slug: &quot;payload-4-0&quot;,
        }}
      /&gt;
      &lt;Composition
        id=&quot;Payload4Square&quot;
        component={Payload4Teaser}
        durationInFrames={900}
        fps={60}
        width={1080}
        height={1080}
        defaultProps={{
          title: &quot;Payload CMS 4.0: Breaking Changes &amp; Canary Deep Dive&quot;,
          slug: &quot;payload-4-0&quot;,
        }}
      /&gt;
    &lt;/&gt;
  );
};
</code></pre>
<p>Both compositions run at 60 fps for 900 frames. The square video is a different layout of the same content, rather than a center crop of the landscape export.</p>
<p><code>defaultProps</code> supplies the title for the opening scene and the article slug for the closing URL. These props do not make every scene generic: the access-control diagrams and other Payload-specific text remain in the component.</p>
<p><code>Root.tsx</code> imports <code>Payload4Teaser</code>, which we create next. Wait until the final component is assembled before opening Studio.</p>
<h2>4. Create the shared animation and layout components</h2>
<p>Create <code>src/Payload4Teaser.tsx</code>. <strong>Copy every TSX block from this section through section 6 into this one file, in order.</strong> Each block adds new declarations; it does not replace the previous block. Together they are the complete source.</p>
<h3>Imports, colors, and layout detection</h3>
<p>Start the file with all imports and the shared constants:</p>
<pre><code class="language-tsx">import { useEffect, useState, type CSSProperties, type ReactNode } from &quot;react&quot;;
import {
  AbsoluteFill,
  Img,
  Sequence,
  continueRender,
  delayRender,
  cancelRender,
  interpolate,
  spring,
  staticFile,
  useCurrentFrame,
  useVideoConfig,
} from &quot;remotion&quot;;
import {
  ArrowRight,
  ArrowUpRight,
  Code2,
  Database,
  GitBranch,
  LockKeyhole,
  ShieldCheck,
  Sparkles,
  Terminal,
  Users,
  Workflow,
} from &quot;lucide-react&quot;;
import &quot;./style.css&quot;;

export type TeaserProps = { title: string; slug: string };
const C = {
  bg: &quot;#0b1120&quot;,
  card: &quot;#1e293b&quot;,
  sky: &quot;#38bdf8&quot;,
  text: &quot;#f1f5f9&quot;,
  muted: &quot;#94a3b8&quot;,
  red: &quot;#fb7185&quot;,
  green: &quot;#6ee7b7&quot;,
  border: &quot;#334155&quot;,
};
const mono: CSSProperties = { fontFamily: &quot;IBM Plex Mono, monospace&quot; };
const clamp = { extrapolateLeft: &quot;clamp&quot;, extrapolateRight: &quot;clamp&quot; } as const;
const useSquare = () =&gt; {
  const { width, height } = useVideoConfig();
  return width === height;
};
</code></pre>
<p><code>C</code> centralizes the palette. <code>mono</code> gives code and labels a consistent font. <code>clamp</code> prevents interpolation from continuing beyond its intended endpoints. The <code>useSquare()</code> hook reads the composition dimensions; it does not use the browser window&#39;s size.</p>
<p>That distinction matters when the same composition is previewed at different zoom levels. A 1080×1080 canvas stays square even if Studio shows it inside a wide browser window.</p>
<h3>Wait for bundled fonts</h3>
<p>Append the font gate:</p>
<pre><code class="language-tsx">const FontGate = () =&gt; {
  const [handle] = useState(() =&gt; delayRender(&quot;Loading bundled typography&quot;));
  useEffect(() =&gt; {
    let active = true;
    Promise.all(
      [
        ...[400, 500, 600, 700].map(
          (weight) =&gt;
            new FontFace(
              &quot;Inter&quot;,
              `url(&quot;${staticFile(`fonts/inter-${weight}.woff2`)}&quot;)`,
              { weight: String(weight) },
            ),
        ),
        new FontFace(
          &quot;IBM Plex Mono&quot;,
          `url(&quot;${staticFile(&quot;fonts/plex-mono-400.woff2&quot;)}&quot;)`,
          { weight: &quot;400&quot; },
        ),
      ].map(async (font) =&gt; {
        const loaded = await font.load();
        document.fonts.add(loaded);
      }),
    )
      .then(() =&gt; {
        if (active) continueRender(handle);
      })
      .catch(cancelRender);
    return () =&gt; {
      active = false;
    };
  }, [handle]);
  return null;
};
</code></pre>
<p>The gate creates a render-delay handle once for the mounted component. It loads the required weights, registers them with the browser, and clears the handle when all fonts are ready. A load failure calls <code>cancelRender</code>, so an export fails rather than silently capturing fallback typography. <a href="https://www.remotion.dev/docs/delay-render">See the render-delay lifecycle</a>.</p>
<p>The component renders nothing visible. Its purpose is to coordinate readiness. Loading the typefaces matters because fallback fonts can change text widths, line breaks, and diagram spacing.</p>
<p>The cleanup flag prevents a completed request from continuing a render after this instance has unmounted. For a larger application, Remotion also provides font-loading utilities; here we retain the small <code>FontFace</code> implementation used by the reference video. <a href="https://www.remotion.dev/docs/fonts">Read the font guide</a>.</p>
<h3>Badges and staggered entrances</h3>
<p>Append the badge component:</p>
<pre><code class="language-tsx">const Badge = ({
  children,
  color = C.sky,
  style,
}: {
  children: ReactNode;
  color?: string;
  style?: CSSProperties;
}) =&gt; (
  &lt;div
    style={{
      ...mono,
      display: &quot;inline-flex&quot;,
      alignItems: &quot;center&quot;,
      gap: 12,
      padding: &quot;12px 18px&quot;,
      fontSize: 22,
      color,
      background: `${color}10`,
      border: `1px solid ${color}40`,
      borderRadius: 12,
      whiteSpace: &quot;nowrap&quot;,
      ...style,
    }}
  &gt;
    {children}
  &lt;/div&gt;
);
</code></pre>
<p>A badge is ordinary JSX and CSS. Its children can be text, an icon, or both. The same primitive styles the opening tags and the canary indicator.</p>
<p>Now append the entrance animation:</p>
<pre><code class="language-tsx">const Pop = ({
  children,
  delay = 0,
  style,
}: {
  children: ReactNode;
  delay?: number;
  style?: CSSProperties;
}) =&gt; {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const progress = spring({
    frame: frame - delay,
    fps,
    config: { damping: 22, stiffness: 120, mass: 0.8 },
  });
  return (
    &lt;div
      style={{
        opacity: interpolate(frame - delay, [-8, 16], [0, 1], clamp),
        transform: `translateY(${(1 - progress) * 28}px) scale(${0.97 + progress * 0.03})`,
        ...style,
      }}
    &gt;
      {children}
    &lt;/div&gt;
  );
};
</code></pre>
<p><code>Pop</code> combines two drivers. A spring moves the element from 28 pixels below its resting position and scales it from roughly 0.97 toward 1. Interpolation controls opacity. <code>delay</code> shifts both calculations, allowing a heading, subtitle, and badges to enter in succession.</p>
<p>The spring receives the composition&#39;s <code>fps</code>; the damping, stiffness, and mass values tune how it settles. The frame passed to it is <code>frame - delay</code>, so each element uses the same entrance with a different start. <a href="https://www.remotion.dev/docs/spring">See the spring API</a>.</p>
<p>There is a subtle detail in the opacity curve: it maps <code>[-8, 16]</code> to <code>[0, 1]</code>. That starts fading eight frames before the spring&#39;s nominal start and reaches full opacity sixteen frames after it. <code>delay</code> therefore does not mean completely invisible until that exact frame.</p>
<p>Clamping keeps opacity within the chosen range before and after the animation interval. Without clamping, interpolation continues along the line beyond its endpoints. <a href="https://www.remotion.dev/docs/interpolate">See interpolation and extrapolation</a>.</p>
<h3>Scene framing and headings</h3>
<p>Append the shared scene wrapper:</p>
<pre><code class="language-tsx">const Scene = ({
  children,
  duration = 180,
  hold = false,
}: {
  children: ReactNode;
  duration?: number;
  hold?: boolean;
}) =&gt; {
  const frame = useCurrentFrame();
  const sq = useSquare();
  return (
    &lt;AbsoluteFill
      style={{
        padding: sq ? &quot;208px 68px 140px&quot; : &quot;220px 112px 140px&quot;,
        opacity: interpolate(
          frame,
          [0, 16, duration - 13, duration - 1],
          [0.35, 1, 1, hold ? 1 : 0.35],
          clamp,
        ),
        transform: `translateY(${interpolate(frame, [0, 24, duration - 13, duration - 1], [14, 0, 0, hold ? 0 : -8], clamp)}px)`,
      }}
    &gt;
      {children}
    &lt;/AbsoluteFill&gt;
  );
};
</code></pre>
<p><code>AbsoluteFill</code> covers the composition. The wrapper supplies padding, a short entrance, and a short exit based on the scene&#39;s local frame. Its default duration is 180 frames; the longer access scene and shorter depth scene pass explicit durations.</p>
<p>This example fades between opacity 0.35 and 1, rather than fading completely to black. The final scene uses <code>hold</code> to keep its end state visible. These are design choices you can change by adjusting the output ranges.</p>
<p>Append the shared heading:</p>
<pre><code class="language-tsx">const Heading = ({
  index,
  eyebrow,
  children,
  subtitle,
}: {
  index: string;
  eyebrow: string;
  children: ReactNode;
  subtitle?: ReactNode;
}) =&gt; {
  const sq = useSquare();
  return (
    &lt;div style={{ marginBottom: sq ? 30 : 42 }}&gt;
      &lt;div
        style={{
          ...mono,
          color: C.sky,
          fontSize: 23,
          letterSpacing: 3,
          textTransform: &quot;uppercase&quot;,
          marginBottom: 16,
        }}
      &gt;
        {index} / {eyebrow}
      &lt;/div&gt;
      &lt;h1
        style={{
          fontSize: sq ? 56 : 76,
          fontWeight: 600,
          letterSpacing: -3,
          lineHeight: 1.1,
          margin: 0,
        }}
      &gt;
        {children}
      &lt;/h1&gt;
      {subtitle &amp;&amp; (
        &lt;div
          style={{
            fontSize: sq ? 25 : 28,
            color: C.muted,
            lineHeight: 1.5,
            marginTop: 18,
          }}
        &gt;
          {subtitle}
        &lt;/div&gt;
      )}
    &lt;/div&gt;
  );
};
</code></pre>
<p>The heading changes font sizes and spacing for the square composition. <code>ReactNode</code> lets subtitles contain either plain text or JSX, such as a highlighted value.</p>
<h3>Persistent background and branding</h3>
<p>Append the background:</p>
<pre><code class="language-tsx">const Background = () =&gt; {
  const frame = useCurrentFrame();
  const { width } = useVideoConfig();
  return (
    &lt;AbsoluteFill style={{ background: C.bg, overflow: &quot;hidden&quot; }}&gt;
      &lt;AbsoluteFill
        style={{
          background:
            &quot;radial-gradient(ellipse at 82% 18%, #38bdf817 0%, transparent 52%), radial-gradient(ellipse at 12% 90%, #2563eb10 0%, transparent 45%)&quot;,
        }}
      /&gt;
      &lt;AbsoluteFill
        style={{
          opacity: 0.15,
          backgroundImage:
            &quot;linear-gradient(#334155 1px, transparent 1px), linear-gradient(90deg, #334155 1px, transparent 1px)&quot;,
          backgroundSize: &quot;80px 80px&quot;,
          transform: `translateY(${(frame / 30) % 80}px)`,
          top: -80,
          bottom: -80,
        }}
      /&gt;
      &lt;div
        style={{
          position: &quot;absolute&quot;,
          width: 630,
          height: 630,
          border: &quot;1px solid #38bdf814&quot;,
          borderRadius: &quot;50%&quot;,
          right: -170,
          top: -180,
          transform: `scale(${1 + frame / 18000})`,
        }}
      /&gt;
      &lt;div
        style={{
          position: &quot;absolute&quot;,
          width: 840,
          height: 840,
          border: &quot;1px solid #38bdf80b&quot;,
          borderRadius: &quot;50%&quot;,
          right: -275,
          top: -285,
        }}
      /&gt;
      &lt;div
        style={{
          position: &quot;absolute&quot;,
          bottom: 0,
          left: 0,
          height: 5,
          width: (width * (frame + 1)) / 900,
          background: C.sky,
          boxShadow: &quot;0 0 24px #38bdf880&quot;,
        }}
      /&gt;
    &lt;/AbsoluteFill&gt;
  );
};
</code></pre>
<p>The gradient, grid, rings, and progress bar remain behind every scene. Their movement comes from the current frame. The grid translates using a repeating calculation, and the large ring slowly scales.</p>
<p>The progress bar uses <code>(frame + 1) / 900</code>, so it reaches full width on the last frame, 899. The denominator is deliberately tied to this video&#39;s fixed duration. If you change the composition length, update it too, or derive it from <code>useVideoConfig()</code>.</p>
<p>Append the brand overlay:</p>
<pre><code class="language-tsx">const Brand = () =&gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const chapter =
    frame &lt; 180
      ? &quot;THE V4 BREAKDOWN&quot;
      : frame &lt; 420
        ? &quot;SECURITY DEFAULTS&quot;
        : frame &lt; 540
          ? &quot;QUERY DEPTH&quot;
          : frame &lt; 720
            ? &quot;FRAMEWORK ADAPTERS&quot;
            : &quot;THE FULL GUIDE&quot;;
  return (
    &lt;&gt;
      &lt;div
        className=&quot;flex items-center justify-between&quot;
        style={{
          position: &quot;absolute&quot;,
          top: sq ? 66 : 64,
          left: sq ? 68 : 112,
          right: sq ? 68 : 112,
          height: 64,
        }}
      &gt;
        &lt;div className=&quot;flex items-center&quot; style={{ gap: 18 }}&gt;
          &lt;Img
            src={staticFile(&quot;bwm-logo.svg&quot;)}
            style={{ width: 54, height: 54, borderRadius: 9 }}
          /&gt;
          &lt;div
            style={{
              fontSize: sq ? 24 : 26,
              letterSpacing: -0.7,
              fontWeight: 600,
            }}
          &gt;
            Build with Matija&lt;span style={{ color: C.sky }}&gt;.&lt;/span&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;Badge style={{ fontSize: sq ? 17 : 19, padding: &quot;10px 14px&quot; }}&gt;
          &lt;span
            style={{
              width: 7,
              height: 7,
              borderRadius: &quot;50%&quot;,
              background: C.sky,
            }}
          /&gt;
          V4 CANARY
        &lt;/Badge&gt;
      &lt;/div&gt;
      &lt;div
        style={{
          position: &quot;absolute&quot;,
          bottom: 56,
          left: sq ? 68 : 112,
          right: sq ? 68 : 112,
          display: &quot;flex&quot;,
          justifyContent: &quot;space-between&quot;,
          color: C.muted,
          ...mono,
          fontSize: sq ? 17 : 20,
          letterSpacing: 1.2,
        }}
      &gt;
        &lt;span&gt;{chapter}&lt;/span&gt;
        &lt;span&gt;buildwithmatija.com&lt;/span&gt;
      &lt;/div&gt;
    &lt;/&gt;
  );
};
</code></pre>
<p>The chapter labels switch at the same frame boundaries we will use for the scenes. The logo, canary badge, chapter label, and website address stay visible across the whole timeline.</p>
<p>We will place <code>Background</code> and <code>Brand</code> outside the sequences. They therefore receive the composition&#39;s frame, while the scene components inside a sequence receive a local frame. That lets the background stay continuous while each scene starts its own entrance at zero.</p>
<h2>5. Build the five scenes</h2>
<p>Continue appending these blocks to <code>src/Payload4Teaser.tsx</code>. We are now composing the shared primitives into the exact content shown in the video.</p>
<h3>Scene 1: title and hook</h3>
<p>Append the opening scene:</p>
<pre><code class="language-tsx">const Hook = ({ title }: { title: string }) =&gt; {
  const sq = useSquare();
  const separator = title.indexOf(&quot;:&quot;);
  const headline = separator &lt; 0 ? title : title.slice(0, separator);
  const subtitle =
    separator &lt; 0
      ? &quot;Breaking Changes &amp; Canary Deep Dive&quot;
      : title.slice(separator + 1).trim();
  return (
    &lt;Scene&gt;
      &lt;Pop&gt;
        &lt;div
          style={{
            ...mono,
            fontSize: 23,
            color: C.sky,
            letterSpacing: 3,
            marginBottom: sq ? 36 : 34,
          }}
        &gt;
          ARCHITECTURE / MIGRATION / WHAT’S NEXT
        &lt;/div&gt;
      &lt;/Pop&gt;
      &lt;Pop delay={8}&gt;
        &lt;h1
          style={{
            fontSize: sq ? 104 : 146,
            lineHeight: 1.06,
            fontWeight: 600,
            letterSpacing: sq ? -6 : -8,
            margin: 0,
            maxWidth: sq ? 900 : 1600,
          }}
        &gt;
          {headline.replace(&quot; 4.0&quot;, &quot;&quot;)}
          &lt;br /&gt;
          &lt;span style={{ color: C.sky }}&gt;4.0&lt;/span&gt;
          &lt;span
            style={{
              fontSize: sq ? 27 : 32,
              letterSpacing: 0,
              color: C.muted,
              marginLeft: 28,
              verticalAlign: &quot;middle&quot;,
              ...mono,
            }}
          &gt;
            THE NEXT CHAPTER
          &lt;/span&gt;
        &lt;/h1&gt;
      &lt;/Pop&gt;
      &lt;Pop delay={20}&gt;
        &lt;div
          style={{
            fontSize: sq ? 40 : 49,
            lineHeight: 1.25,
            fontWeight: 500,
            letterSpacing: -1.3,
            maxWidth: sq ? 820 : 1400,
            marginTop: sq ? 28 : 32,
          }}
        &gt;
          {subtitle}
        &lt;/div&gt;
      &lt;/Pop&gt;
      &lt;div
        className=&quot;flex flex-wrap&quot;
        style={{ gap: 14, maxWidth: sq ? 810 : 1550, marginTop: sq ? 40 : 50 }}
      &gt;
        {[
          &quot;Node 24&quot;,
          &quot;Next.js 16&quot;,
          &quot;TanStack Start&quot;,
          &quot;overrideAccess: false&quot;,
        ].map((tag, i) =&gt; (
          &lt;Pop key={tag} delay={32 + i * 8}&gt;
            &lt;Badge style={{ fontSize: sq ? 23 : 25 }}&gt;{tag}&lt;/Badge&gt;
          &lt;/Pop&gt;
        ))}
      &lt;/div&gt;
      &lt;Pop delay={70}&gt;
        &lt;div style={{ color: C.muted, fontSize: sq ? 24 : 26, marginTop: 30 }}&gt;
          A closer look at the defaults that change your code.
        &lt;/div&gt;
      &lt;/Pop&gt;
    &lt;/Scene&gt;
  );
};
</code></pre>
<p>The title is split at its first colon. The first part becomes the headline, and the rest becomes the subtitle. The highlighted <code>4.0</code> and the supporting labels are specific to this example.</p>
<p>The tags use delays of <code>32 + i * 8</code> frames, so each starts eight frames after the previous tag. At 60 fps that spacing is about 0.13 seconds. The animation stays deterministic because the delay comes from the array index.</p>
<h3>Scene 2: compare access defaults</h3>
<p>Append the comparison card and its scene:</p>
<pre><code class="language-tsx">const AccessCard = ({ v4 }: { v4: boolean }) =&gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const color = v4 ? C.green : C.red;
  const draw = interpolate(frame, [v4 ? 58 : 25, v4 ? 100 : 67], [0, 1], clamp);
  return (
    &lt;div
      style={{
        background: &quot;linear-gradient(135deg, #1e293b, #152033)&quot;,
        border: `1px solid ${color}45`,
        borderRadius: 24,
        padding: sq ? &quot;20px 28px&quot; : &quot;32px 36px&quot;,
        flex: 1,
        position: &quot;relative&quot;,
        lineHeight: 1.2,
        boxShadow: &quot;0 18px 60px #00000020&quot;,
      }}
    &gt;
      &lt;div className=&quot;flex items-center justify-between&quot;&gt;
        &lt;div style={{ ...mono, fontSize: sq ? 20 : 24, color: C.muted }}&gt;
          PAYLOAD {v4 ? &quot;4&quot; : &quot;3&quot;}
        &lt;/div&gt;
        &lt;div style={{ color }}&gt;
          {sq ? (
            &lt;span style={{ ...mono, fontSize: 21 }}&gt;
              overrideAccess: {v4 ? &quot;false&quot; : &quot;true&quot;}
            &lt;/span&gt;
          ) : (
            &lt;ShieldCheck size={32} /&gt;
          )}
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div
        style={{
          display: &quot;flex&quot;,
          alignItems: &quot;center&quot;,
          gap: 20,
          marginTop: sq ? 12 : 28,
        }}
      &gt;
        &lt;Terminal color={C.muted} size={sq ? 28 : 36} /&gt;
        &lt;svg width={sq ? 140 : 180} height=&quot;28&quot; viewBox=&quot;0 0 180 28&quot;&gt;
          &lt;path
            d=&quot;M0 14 H164&quot;
            pathLength={1}
            stroke={color}
            strokeWidth={2}
            fill=&quot;none&quot;
            strokeDasharray=&quot;1&quot;
            strokeDashoffset={1 - draw}
          /&gt;
          &lt;path
            d=&quot;M156 6 L164 14 L156 22&quot;
            stroke={color}
            strokeWidth={2}
            fill=&quot;none&quot;
            opacity={draw}
          /&gt;
        &lt;/svg&gt;
        &lt;div style={{ color }}&gt;
          {v4 ? (
            &lt;LockKeyhole size={sq ? 28 : 36} /&gt;
          ) : (
            &lt;Database size={sq ? 28 : 36} /&gt;
          )}
        &lt;/div&gt;
        &lt;span style={{ ...mono, color, fontSize: sq ? 21 : 23 }}&gt;
          {v4 ? &quot;RULES EVALUATED&quot; : &quot;RULES BYPASSED&quot;}
        &lt;/span&gt;
      &lt;/div&gt;
      &lt;div
        style={{
          fontSize: sq ? 30 : 42,
          fontWeight: 600,
          letterSpacing: -1.2,
          marginTop: sq ? 12 : 28,
        }}
      &gt;
        {v4 ? &quot;Access enforced by default&quot; : &quot;Implicit superadmin&quot;}
      &lt;/div&gt;
      {!sq &amp;&amp; (
        &lt;div style={{ ...mono, fontSize: 26, color, marginTop: 16 }}&gt;
          overrideAccess: {v4 ? &quot;false&quot; : &quot;true&quot;}
        &lt;/div&gt;
      )}
      &lt;div
        style={{
          fontSize: sq ? 21 : 25,
          color: C.muted,
          marginTop: sq ? 12 : 24,
        }}
      &gt;
        {v4 ? &quot;Allow · Filter · Deny&quot; : &quot;Collection access checks skipped&quot;}
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

const Access = () =&gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  return (
    &lt;Scene duration={240}&gt;
      &lt;Heading
        index=&quot;01&quot;
        eyebrow=&quot;Secure by default&quot;
        subtitle={&lt;&gt;Same Local API query. Different default.&lt;/&gt;}
      &gt;
        The rules now apply.
      &lt;/Heading&gt;
      &lt;Pop delay={4}&gt;
        &lt;div
          style={{
            ...mono,
            fontSize: sq ? 25 : 29,
            background: &quot;#02061780&quot;,
            border: `1px solid ${C.border}`,
            borderRadius: 14,
            padding: &quot;18px 24px&quot;,
            marginBottom: sq ? 22 : 30,
            color: C.text,
          }}
        &gt;
          payload.find({&quot;{&quot;} collection:{&quot; &quot;}
          &lt;span style={{ color: C.sky }}&gt;&#39;orders&#39;&lt;/span&gt; {&quot;}&quot;})
          &lt;span
            style={{
              color: C.muted,
              fontSize: sq ? 18 : 22,
              display: sq ? &quot;block&quot; : &quot;inline&quot;,
              marginLeft: sq ? 0 : 22,
              marginTop: sq ? 8 : 0,
            }}
          &gt;
            // overrideAccess omitted
          &lt;/span&gt;
        &lt;/div&gt;
      &lt;/Pop&gt;
      &lt;div
        style={{
          display: &quot;flex&quot;,
          flexDirection: sq ? &quot;column&quot; : &quot;row&quot;,
          gap: sq ? 18 : 28,
          transform: `scale(${interpolate(frame, [50, 190], [1, 1.012], clamp)})`,
          transformOrigin: &quot;center&quot;,
        }}
      &gt;
        &lt;Pop delay={12} style={{ flex: 1, display: &quot;flex&quot; }}&gt;
          &lt;AccessCard v4={false} /&gt;
        &lt;/Pop&gt;
        &lt;Pop delay={42} style={{ flex: 1, display: &quot;flex&quot; }}&gt;
          &lt;AccessCard v4 /&gt;
        &lt;/Pop&gt;
      &lt;/div&gt;
      &lt;Pop delay={90}&gt;
        &lt;div
          style={{
            color: C.muted,
            fontSize: sq ? 21 : 25,
            marginTop: sq ? 20 : 28,
          }}
        &gt;
          No user? Public access rules apply.
        &lt;/div&gt;
      &lt;/Pop&gt;
    &lt;/Scene&gt;
  );
};
</code></pre>
<p>The two cards share one component. The <code>v4</code> flag changes the labels, colors, icons, and connector timing. For the animated SVG line, <code>pathLength={1}</code> normalizes the path length and <code>strokeDashoffset={1 - draw}</code> reveals it as <code>draw</code> moves toward 1.</p>
<p>The square layout stacks the cards and moves the access-default text into each header. That removes repeated detail from the taller layout and keeps room for the query, heading, and footer. Simply changing the canvas size would not make the landscape scene fit.</p>
<p>The scene lasts 240 frames, which is four seconds. Its card entrances use local frame values, so their delays are measured from the start of this scene, not from frame zero of the full video.</p>
<p>The example&#39;s message distinguishes access checks being evaluated from a request being granted. The green card still lists Allow, Filter, and Deny; the diagram should not imply that evaluating rules always allows access.</p>
<h3>Scene 3: relationship depth</h3>
<p>Append the relationship row and the depth scene:</p>
<pre><code class="language-tsx">const RelationshipRow = ({ v4 }: { v4: boolean }) =&gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const draw = interpolate(frame, [v4 ? 25 : 8, v4 ? 65 : 42], [0, 1], clamp);
  const labels = [&quot;Post&quot;, &quot;Author&quot;, v4 ? &quot;Avatar ID&quot; : &quot;Avatar document&quot;];
  const icons = [
    &lt;Code2 key=&quot;post&quot; size={32} /&gt;,
    &lt;Users key=&quot;author&quot; size={32} /&gt;,
    &lt;Database key=&quot;avatar&quot; size={32} /&gt;,
  ];
  return (
    &lt;div
      style={{
        padding: sq ? &quot;26px 24px&quot; : &quot;30px 36px&quot;,
        border: `1px solid ${v4 ? C.sky + &quot;60&quot; : C.border}`,
        borderRadius: 24,
        background: v4 ? &quot;#12253b&quot; : &quot;#1e293b90&quot;,
        lineHeight: 1.2,
      }}
    &gt;
      &lt;div
        style={{
          ...mono,
          color: v4 ? C.sky : C.muted,
          fontSize: 23,
          marginBottom: 24,
        }}
      &gt;
        PAYLOAD {v4 ? &quot;4&quot; : &quot;3&quot;}{&quot; &quot;}
        &lt;span style={{ color: C.muted }}&gt;
          {&quot; &quot;}
          / DEFAULT DEPTH: {v4 ? &quot;1&quot; : &quot;2&quot;}
        &lt;/span&gt;
      &lt;/div&gt;
      &lt;div className=&quot;flex items-center&quot; style={{ gap: sq ? 10 : 24 }}&gt;
        {labels.map((label, i) =&gt; (
          &lt;div key={label} style={{ display: &quot;contents&quot; }}&gt;
            {i &gt; 0 &amp;&amp; (
              &lt;svg
                width={sq ? 60 : 140}
                height=&quot;30&quot;
                viewBox=&quot;0 0 140 30&quot;
                style={{ flexShrink: 0 }}
              &gt;
                &lt;path
                  d=&quot;M0 15 H126&quot;
                  stroke={v4 &amp;&amp; i === 2 ? C.muted : C.sky}
                  strokeWidth={2}
                  strokeDasharray={v4 &amp;&amp; i === 2 ? &quot;8 7&quot; : undefined}
                  opacity={draw}
                /&gt;
                &lt;path
                  d=&quot;M118 7 L126 15 L118 23&quot;
                  stroke={v4 &amp;&amp; i === 2 ? C.muted : C.sky}
                  strokeWidth={2}
                  fill=&quot;none&quot;
                  opacity={draw}
                /&gt;
              &lt;/svg&gt;
            )}
            &lt;div
              style={{
                flex: 1,
                padding: sq ? &quot;22px 12px&quot; : &quot;26px 30px&quot;,
                border: `1px ${v4 &amp;&amp; i === 2 ? &quot;dashed&quot; : &quot;solid&quot;} ${C.border}`,
                background: &quot;#0b1120a0&quot;,
                borderRadius: 14,
                display: &quot;flex&quot;,
                flexDirection: sq ? &quot;column&quot; : &quot;row&quot;,
                alignItems: &quot;center&quot;,
                gap: 16,
                color: v4 &amp;&amp; i === 2 ? C.muted : C.text,
              }}
            &gt;
              &lt;span style={{ color: i === 2 &amp;&amp; v4 ? C.muted : C.sky }}&gt;
                {icons[i]}
              &lt;/span&gt;
              &lt;span
                style={{
                  fontSize: sq ? 25 : 32,
                  fontWeight: 500,
                  textAlign: &quot;center&quot;,
                  whiteSpace: &quot;nowrap&quot;,
                }}
              &gt;
                {label}
              &lt;/span&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        ))}
      &lt;/div&gt;
    &lt;/div&gt;
  );
};

const Depth = () =&gt; (
  &lt;Scene duration={120}&gt;
    &lt;Heading
      index=&quot;02&quot;
      eyebrow=&quot;Leaner queries&quot;
      subtitle=&quot;One fewer populated relationship level.&quot;
    &gt;
      Default depth: &lt;span style={{ color: C.muted }}&gt;2&lt;/span&gt;{&quot; &quot;}
      &lt;span style={{ color: C.sky }}&gt;→ 1&lt;/span&gt;
    &lt;/Heading&gt;
    &lt;div style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot;, gap: 24 }}&gt;
      &lt;Pop&gt;
        &lt;RelationshipRow v4={false} /&gt;
      &lt;/Pop&gt;
      &lt;Pop delay={18}&gt;
        &lt;RelationshipRow v4 /&gt;
      &lt;/Pop&gt;
    &lt;/div&gt;
    &lt;Pop delay={45}&gt;
      &lt;div style={{ marginTop: 28, fontSize: 25, color: C.muted }}&gt;
        Need the avatar document? Set{&quot; &quot;}
        &lt;span style={{ ...mono, color: C.sky }}&gt;depth: 2&lt;/span&gt;.
      &lt;/div&gt;
    &lt;/Pop&gt;
  &lt;/Scene&gt;
);
</code></pre>
<p>This scene uses two rows to compare the diagrams. The last node is a populated document in one row and an ID in the other. Dashed styling carries that distinction even without relying on color.</p>
<p>The node contents are React components, including Lucide SVG icons. The connectors are SVG paths. Remotion can animate them because their visible properties are calculated from frames, just like the earlier HTML cards.</p>
<p><code>Scene duration={120}</code> keeps this scene&#39;s entrance and exit aligned with its two-second sequence. The second row and explanatory note arrive later through <code>Pop</code> delays.</p>
<h3>Scene 4: framework adapters and the shared core</h3>
<p>Append the framework scene:</p>
<pre><code class="language-tsx">const Frameworks = () =&gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const progress = interpolate(frame, [25, 72], [0, 1], clamp);
  return (
    &lt;Scene&gt;
      &lt;Heading index=&quot;03&quot; eyebrow=&quot;Framework boundary&quot;&gt;
        Two paths. One core.
      &lt;/Heading&gt;
      &lt;div style={{ position: &quot;relative&quot; }}&gt;
        &lt;div className=&quot;flex&quot; style={{ gap: 24 }}&gt;
          {[false, true].map((tanstack) =&gt; (
            &lt;Pop
              key={String(tanstack)}
              delay={tanstack ? 12 : 0}
              style={{ flex: 1 }}
            &gt;
              &lt;div
                style={{
                  padding: sq ? &quot;26px 24px&quot; : &quot;24px 36px&quot;,
                  lineHeight: 1.2,
                  background: &quot;#1e293bcc&quot;,
                  border: `1px ${tanstack ? &quot;dashed&quot; : &quot;solid&quot;} ${tanstack ? &quot;#38bdf870&quot; : C.border}`,
                  borderRadius: 24,
                }}
              &gt;
                &lt;div
                  style={{
                    display: &quot;flex&quot;,
                    gap: 16,
                    alignItems: &quot;center&quot;,
                    color: C.sky,
                  }}
                &gt;
                  {tanstack ? &lt;GitBranch size={32} /&gt; : &lt;Workflow size={32} /&gt;}
                  &lt;span
                    style={{
                      fontSize: sq ? 30 : 38,
                      fontWeight: 600,
                      letterSpacing: -1,
                    }}
                  &gt;
                    {tanstack ? &quot;TanStack Start&quot; : &quot;Next.js&quot;}
                  &lt;/span&gt;
                &lt;/div&gt;
                &lt;div
                  style={{
                    ...mono,
                    color: C.muted,
                    fontSize: sq ? 22 : 25,
                    marginTop: 18,
                  }}
                &gt;
                  {tanstack ? &quot;Vite / Router&quot; : &quot;App Router / RSC&quot;}
                &lt;/div&gt;
                &lt;div
                  style={{
                    color: tanstack ? C.sky : C.muted,
                    fontSize: sq ? 21 : 23,
                    marginTop: 16,
                  }}
                &gt;
                  {tanstack ? &quot;Experimental canary&quot; : &quot;Established adapter&quot;}
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/Pop&gt;
          ))}
        &lt;/div&gt;
        &lt;svg
          width=&quot;100%&quot;
          height={sq ? 96 : 116}
          viewBox=&quot;0 0 1000 116&quot;
          preserveAspectRatio=&quot;none&quot;
          style={{ display: &quot;block&quot; }}
        &gt;
          &lt;path
            d=&quot;M245 0 V48 Q245 58 255 58 H490 Q500 58 500 68 V106&quot;
            fill=&quot;none&quot;
            stroke={C.sky}
            strokeWidth={2}
            pathLength={1}
            strokeDasharray=&quot;1&quot;
            strokeDashoffset={1 - progress}
          /&gt;
          &lt;path
            d=&quot;M755 0 V48 Q755 58 745 58 H500 V106&quot;
            fill=&quot;none&quot;
            stroke={C.sky}
            strokeWidth={2}
            strokeDasharray=&quot;8 7&quot;
            opacity={progress}
          /&gt;
          &lt;path
            d=&quot;M490 96 L500 106 L510 96&quot;
            fill=&quot;none&quot;
            stroke={C.sky}
            strokeWidth={2}
            opacity={progress}
          /&gt;
        &lt;/svg&gt;
        &lt;Pop delay={30}&gt;
          &lt;div
            style={{
              border: &quot;1px solid #38bdf870&quot;,
              borderRadius: 24,
              padding: sq ? &quot;28px&quot; : &quot;26px 42px&quot;,
              lineHeight: 1.2,
              background: &quot;linear-gradient(120deg, #0c2840, #122036)&quot;,
              display: &quot;flex&quot;,
              alignItems: &quot;center&quot;,
              gap: 24,
            }}
          &gt;
            &lt;Database size={sq ? 48 : 62} color={C.sky} /&gt;
            &lt;div&gt;
              &lt;div
                style={{
                  fontSize: sq ? 39 : 49,
                  fontWeight: 600,
                  letterSpacing: -1.5,
                }}
              &gt;
                Payload 4 Core
              &lt;/div&gt;
              &lt;div
                style={{
                  fontSize: sq ? 22 : 26,
                  marginTop: 12,
                  color: C.muted,
                }}
              &gt;
                Local API · Collections · Auth · Database adapters
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/Pop&gt;
      &lt;/div&gt;
      &lt;Pop delay={58}&gt;
        &lt;div
          style={{
            display: &quot;flex&quot;,
            alignItems: &quot;center&quot;,
            gap: 18,
            marginTop: sq ? 30 : 28,
          }}
        &gt;
          &lt;Sparkles color={C.sky} size={30} /&gt;
          &lt;div&gt;
            &lt;div style={{ fontSize: sq ? 29 : 34, fontWeight: 500 }}&gt;
              Zero Sass. Pure CSS variables.
            &lt;/div&gt;
            &lt;div style={{ fontSize: 22, color: C.muted, marginTop: 8 }}&gt;
              Semantic tokens for the refreshed admin.
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/Pop&gt;
    &lt;/Scene&gt;
  );
};
</code></pre>
<p>Both framework cards point toward one Payload core. The Next.js path is solid, while the TanStack Start card and path retain the example&#39;s experimental-canary styling.</p>
<p>The solid connector uses the same normalized path-length technique as the access cards. The dashed connector fades in through <code>opacity={progress}</code>. The SVG view box provides a shared coordinate system while its rendered width follows the composition.</p>
<p>The scene is ordinary React composition: two cards, a connector diagram, a core card, and an admin-style note. The motion is concentrated in entrances and connector reveals, making the content easier to read during its three seconds on screen.</p>
<h3>Scene 5: hold the call to action</h3>
<p>Append the closing scene:</p>
<pre><code class="language-tsx">const CTA = ({ slug }: { slug: string }) =&gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  return (
    &lt;Scene hold&gt;
      &lt;div
        style={{
          transform: `scale(${interpolate(frame, [0, 48], [1.025, 1], clamp)})`,
          transformOrigin: &quot;center&quot;,
        }}
      &gt;
        &lt;Pop&gt;
          &lt;div
            style={{
              ...mono,
              color: C.sky,
              fontSize: 23,
              letterSpacing: 3,
              marginBottom: 34,
            }}
          &gt;
            YOUR NEXT MIGRATION STARTS HERE
          &lt;/div&gt;
        &lt;/Pop&gt;
        &lt;Pop delay={6}&gt;
          &lt;h1
            style={{
              fontSize: sq ? 83 : 112,
              letterSpacing: -5,
              fontWeight: 600,
              lineHeight: 1.09,
              margin: 0,
            }}
          &gt;
            Read the full guide
            &lt;br /&gt;
            &lt;span style={{ color: C.sky }}&gt;
              &amp; migration
              &lt;br className={sq ? &quot;&quot; : &quot;hidden&quot;} /&gt; breakdown.
            &lt;/span&gt;
          &lt;/h1&gt;
        &lt;/Pop&gt;
        &lt;Pop delay={18}&gt;
          &lt;div
            style={{
              display: &quot;flex&quot;,
              alignItems: &quot;center&quot;,
              gap: 20,
              marginTop: sq ? 34 : 42,
              padding: sq ? &quot;22px 24px&quot; : &quot;24px 30px&quot;,
              border: &quot;1px solid #38bdf860&quot;,
              borderRadius: 18,
              background: &quot;#38bdf80d&quot;,
              maxWidth: sq ? 940 : 1410,
            }}
          &gt;
            &lt;ArrowUpRight color={C.sky} size={36} /&gt;
            &lt;div style={{ ...mono, fontSize: sq ? 28 : 33, lineHeight: 1.5 }}&gt;
              &lt;span&gt;buildwithmatija.com&lt;/span&gt;
              &lt;span style={{ color: C.sky, display: sq ? &quot;block&quot; : &quot;inline&quot; }}&gt;
                /blog/{slug}
              &lt;/span&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/Pop&gt;
        &lt;Pop delay={30}&gt;
          &lt;div
            style={{
              display: &quot;flex&quot;,
              alignItems: &quot;center&quot;,
              gap: 22,
              marginTop: sq ? 34 : 44,
            }}
          &gt;
            &lt;Img
              src={staticFile(&quot;author.jpeg&quot;)}
              style={{
                width: 74,
                height: 74,
                borderRadius: &quot;50%&quot;,
                objectFit: &quot;cover&quot;,
                border: &quot;2px solid #334155&quot;,
              }}
            /&gt;
            &lt;div&gt;
              &lt;div style={{ fontSize: 29, fontWeight: 500 }}&gt;
                Matija Žiberna
              &lt;/div&gt;
              &lt;div style={{ fontSize: 22, color: C.muted, marginTop: 7 }}&gt;
                Build with Matija
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;div style={{ marginLeft: &quot;auto&quot;, color: C.sky }}&gt;
              &lt;ArrowRight size={sq ? 46 : 62} strokeWidth={1.5} /&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/Pop&gt;
      &lt;/div&gt;
    &lt;/Scene&gt;
  );
};
</code></pre>
<p>The closing URL uses the <code>slug</code> prop. Its square variant puts the path on a second line and wraps the heading deliberately. The portrait uses Remotion&#39;s <code>Img</code> component with <code>staticFile()</code>, and the fixed display dimensions keep the surrounding layout stable.</p>
<p><code>Scene hold</code> keeps the completed CTA at full opacity. Its small scale change settles during the first 48 frames, leaving time to read the URL before the video ends.</p>
<h2>6. Assemble the timeline</h2>
<p>Append the final exported component. This completes <code>src/Payload4Teaser.tsx</code>:</p>
<pre><code class="language-tsx">export const Payload4Teaser = ({ title, slug }: TeaserProps) =&gt; (
  &lt;AbsoluteFill
    style={{ fontFamily: &quot;Inter, sans-serif&quot;, color: C.text, background: C.bg }}
  &gt;
    &lt;FontGate /&gt;
    &lt;Background /&gt;
    &lt;Sequence from={0} durationInFrames={180} name=&quot;Hook &amp; title&quot;&gt;
      &lt;Hook title={title} /&gt;
    &lt;/Sequence&gt;
    &lt;Sequence from={180} durationInFrames={240} name=&quot;Access defaults&quot;&gt;
      &lt;Access /&gt;
    &lt;/Sequence&gt;
    &lt;Sequence from={420} durationInFrames={120} name=&quot;Relationship depth&quot;&gt;
      &lt;Depth /&gt;
    &lt;/Sequence&gt;
    &lt;Sequence from={540} durationInFrames={180} name=&quot;Frameworks &amp; admin&quot;&gt;
      &lt;Frameworks /&gt;
    &lt;/Sequence&gt;
    &lt;Sequence from={720} durationInFrames={180} name=&quot;Read the guide&quot;&gt;
      &lt;CTA slug={slug} /&gt;
    &lt;/Sequence&gt;
    &lt;Brand /&gt;
  &lt;/AbsoluteFill&gt;
);
</code></pre>
<p>The order of the layers matters: font coordination first, then the background, then the timed scenes, then branding above them.</p>
<p>Here is the full frame budget:</p>
<table>
<thead>
<tr>
<th>Scene</th>
<th align="right">Start frame</th>
<th align="right">Duration</th>
<th align="right">Last frame</th>
<th>Time interval</th>
</tr>
</thead>
<tbody><tr>
<td>Hook and title</td>
<td align="right">0</td>
<td align="right">180</td>
<td align="right">179</td>
<td>0–3 seconds</td>
</tr>
<tr>
<td>Access defaults</td>
<td align="right">180</td>
<td align="right">240</td>
<td align="right">419</td>
<td>3–7 seconds</td>
</tr>
<tr>
<td>Relationship depth</td>
<td align="right">420</td>
<td align="right">120</td>
<td align="right">539</td>
<td>7–9 seconds</td>
</tr>
<tr>
<td>Frameworks and admin</td>
<td align="right">540</td>
<td align="right">180</td>
<td align="right">719</td>
<td>9–12 seconds</td>
</tr>
<tr>
<td>Call to action</td>
<td align="right">720</td>
<td align="right">180</td>
<td align="right">899</td>
<td>12–15 seconds</td>
</tr>
</tbody></table>
<p>A sequence&#39;s <code>durationInFrames</code> is a count. The first scene includes frames 0 through 179; frame 180 belongs to the next scene. These five intervals cover all 900 frames without a gap or overlap.</p>
<p>Inside <code>&lt;Sequence from={180}&gt;</code>, <code>useCurrentFrame()</code> returns 0 at composition frame 180, 1 at frame 181, and so on. That is why the access cards can use small delays such as 12 and 42: they are relative to that scene. <a href="https://www.remotion.dev/docs/sequence">See sequence timing</a>.</p>
<p>The background and brand are outside those sequences and keep the global frame number. Moving them inside a scene would reset their timing when the scene starts.</p>
<p>A sequence also controls when its children appear. You do not need to hide every scene manually with conditions; the sequence supplies the visibility window and shifted timeline.</p>
<h2>7. Preview the result in Studio</h2>
<p>Check TypeScript and start Studio:</p>
<pre><code class="language-bash">npx tsc --noEmit
pnpm start
</code></pre>
<p>Open <code>http://localhost:3100</code> and select <code>Payload4Teaser</code>. Play the composition, then switch to <code>Payload4Square</code>. If the port is busy, use:</p>
<pre><code class="language-bash">pnpm exec remotion studio src/index.ts --port=3103
</code></pre>
<p>Use representative frames to inspect each scene: 150, 340, 490, 660, and 850. Also inspect both sides of every boundary: 179/180, 419/420, 539/540, and 719/720. Check the opening frame 0 and the final frame 899.</p>
<p>At each stop, check whether headings fit, connectors point to the intended nodes, and the persistent footer stays clear. Preview the square composition around social-feed display sizes as well as at full resolution. Large export dimensions do not guarantee readable text on a phone.</p>
<p>You can save an individual frame for a closer look:</p>
<pre><code class="language-bash">pnpm exec remotion still src/index.ts Payload4Square out/check-square-access.png --frame=340
</code></pre>
<p>Do not judge a composition only by one attractive poster. The frame before a scene change and the first frame after it reveal timing mistakes that a settled frame can hide.</p>
<h2>8. Render MP4, WebM, and posters</h2>
<p>The scripts in <code>package.json</code> already specify the entrypoint, composition ID, and output filename. Run them from the example project:</p>
<pre><code class="language-bash">pnpm render:landscape
pnpm render:square
pnpm render:webm
pnpm poster:landscape
pnpm poster:square
</code></pre>
<p>The first render may download Chrome Headless Shell. Let that finish before diagnosing a slow first export as an animation problem. <a href="https://www.remotion.dev/docs/render">See the rendering walkthrough</a>.</p>
<p>The MP4 scripts use H.264, <code>yuv420p</code>, CRF 18, and BT.709 color space. PNG frame capture avoids introducing JPEG artifacts before encoding around text and thin diagram strokes. <code>--concurrency=4</code> is the reference setting; reduce it if your machine struggles with memory. The WebM script uses VP9 at a target bitrate of 6 Mbps. <a href="https://www.remotion.dev/docs/cli/render">See the CLI options</a>.</p>
<p>Posters come from frame 150, 2.5 seconds into the composition, when the opening scene has settled. You can choose another frame by changing <code>--frame</code> in the poster scripts.</p>
<p>Expect these outputs:</p>
<table>
<thead>
<tr>
<th>Output</th>
<th>Canvas</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>out/payload-4-0-teaser.mp4</code></td>
<td>1920×1080</td>
<td>Landscape H.264 video</td>
</tr>
<tr>
<td><code>out/payload-4-0-square.mp4</code></td>
<td>1080×1080</td>
<td>Square H.264 video</td>
</tr>
<tr>
<td><code>out/payload-4-0-teaser.webm</code></td>
<td>1920×1080</td>
<td>Landscape VP9 alternative</td>
</tr>
<tr>
<td><code>out/payload-4-0-poster.png</code></td>
<td>1920×1080</td>
<td>Landscape poster</td>
</tr>
<tr>
<td><code>out/payload-4-0-square-poster.png</code></td>
<td>1080×1080</td>
<td>Square poster</td>
</tr>
</tbody></table>
<p>Both video compositions are 15 seconds at 60 fps. This example has no audio track; silent playback is expected.</p>
<p>Here is the square reference export for comparison:</p>
<video controls preload="metadata" poster="/remotion-guide/payload-4-0-square-poster.png" width="1080" height="1080">
  <source src="/remotion-guide/payload-4-0-square.mp4" type="video/mp4" />
  Your browser cannot play this video. <a href="/remotion-guide/payload-4-0-square.mp4">Download the square MP4.</a>
</video><p>If you have <code>ffprobe</code> installed, inspect the actual encoded media rather than relying only on composition settings:</p>
<pre><code class="language-bash">ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=codec_name,width,height,r_frame_rate,nb_read_frames,pix_fmt,color_space:format=duration -of json out/payload-4-0-teaser.mp4
</code></pre>
<p>For the landscape MP4, expect H.264, 1920×1080, <code>60/1</code> fps, 900 decoded frames, approximately 15 seconds, <code>yuv420p</code>, and <code>bt709</code>. Check the square file separately; it should report 1080×1080.</p>
<p>Play the final files and seek into each scene. Studio confirms the React composition, while playback confirms the file you will actually share.</p>
<h2>9. Adapt the example to your own content</h2>
<p>Start by changing the title and slug in both compositions. The title controls the opening heading and subtitle; the slug controls the closing article path. Then change the scene content, logo, portrait, and brand labels.</p>
<p>There are several deliberate fixed values to revisit:</p>
<ul>
<li><code>Hook</code> always renders a highlighted <code>4.0</code>, and its tags refer to Payload&#39;s ecosystem.</li>
<li><code>AccessCard</code>, <code>RelationshipRow</code>, and <code>Frameworks</code> contain example-specific diagrams and labels.</li>
<li><code>Brand</code> contains fixed chapter boundaries and website text.</li>
<li><code>Background</code> calculates progress against 900 frames.</li>
<li><code>useSquare()</code> recognizes a square canvas. A vertical 1080×1920 composition needs its own layout decisions.</li>
</ul>
<p>Changing <code>defaultProps</code> alone does not turn this into a general-purpose video generator. To make it reusable across articles, extract the scene content into typed props after you have a second real example and know what varies.</p>
<p>If you change the duration, update the composition, sequence starts and lengths, <code>Scene</code> durations, chapter thresholds, and progress denominator together. A duration change at only the root will either cut content short or leave extra time after the intended ending.</p>
<p>Keep animated values derived from frames. If you add particles or randomly placed decorations, use Remotion&#39;s seeded <code>random()</code> rather than <code>Math.random()</code> so the placement is repeatable. <a href="https://www.remotion.dev/docs/random">See deterministic randomness</a>.</p>
<h2>10. Troubleshoot the common failures</h2>
<h3>A component or import cannot be found</h3>
<p>Make sure you copied every consecutive block into <code>src/Payload4Teaser.tsx</code>, including the imports at the top and exported component at the bottom. The blocks are parts of one file. Copying only an individual scene will leave its helpers undefined.</p>
<p>Run <code>npx tsc --noEmit</code> from the example directory. If the error mentions <code>FontFace</code> or <code>document.fonts</code>, compare the TypeScript <code>lib</code> array with the configuration above.</p>
<h3>Utility classes have no effect</h3>
<p>Check that the component imports <code>./style.css</code>, that the stylesheet imports Tailwind, and that <code>remotion.config.ts</code> calls <code>enableTailwind</code>. Our layout mixes utility classes and inline styles; missing Tailwind can break flex layouts even while colors still appear correctly.</p>
<h3>Fonts fail to load or the render times out</h3>
<p>Check all five requested font filenames, their copied paths, and the spelling of <code>public/fonts</code>. Use Studio&#39;s browser console to look for failed asset requests. The font gate intentionally cancels on a loading error.</p>
<p>A timeout can indicate work that never cleared its delay handle. Increasing the timeout does not repair a missing file or a stalled request. Trace the operation and make sure it either completes with <code>continueRender()</code> or fails with <code>cancelRender()</code>. <a href="https://www.remotion.dev/docs/delay-render">See render-delay troubleshooting</a>.</p>
<h3>Animation looks different after scrubbing</h3>
<p>Look for CSS keyframes, transitions, timers, or values calculated from wall-clock time. A composition must display the intended result when you jump straight to a frame. Calculate motion from <code>useCurrentFrame()</code> and keep your asset and input data stable.</p>
<h3>Square content clips or collides with the footer</h3>
<p>Inspect the entire scene&#39;s height, including headings, margins, query text, and notes. The reference square layout stacks access cards, tightens their spacing, and moves detail into their headers. Smaller fonts alone will not fix every layout problem.</p>
<h3>The final export is unreadable or fails</h3>
<p>Check available disk space and try reducing render concurrency. Inspect the actual output with a media player and <code>ffprobe</code>. A successful TypeScript check confirms types, not that the browser captured every frame correctly.</p>
<h2>Where to go after this tutorial</h2>
<p>You now have a concrete composition you can scrub, modify, and render. Try replacing the access comparison with a diagram from your own article while keeping the same timing and shared animation helpers.</p>
<p>For a next project, the <a href="https://www.remotion.dev/docs/player">Remotion Player</a> lets you embed a composition as an interactive preview in a React application. The <a href="https://www.remotion.dev/docs/renderer">Node rendering API</a> and <a href="https://www.remotion.dev/docs/lambda">Lambda documentation</a> cover automated exports when local rendering is no longer enough. Check the <a href="https://www.remotion.dev/docs/license">current licensing terms</a> when planning how to use it in your organization.</p>
<p>Build one clear scene, inspect its frames, and then extend the timeline. The same React composition skills carry through as the video grows.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/remotion-react-video-tutorial</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/remotion-react-video-tutorial</guid>
            <category><![CDATA[Tools]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;I wanted to turn an article about Payload CMS 4.0 into a short animated teaser. The content already had useful visual ideas: an access-control comparison, a relationship-depth diagram, and two framework adapters sharing one core. Remotion let me turn those ideas into video using React components, TypeScript, CSS, and SVG.&lt;/p&gt;
&lt;p&gt;Here is the finished 15-second video we will recreate:&lt;/p&gt;
&lt;video controls preload=&quot;metadata&quot; poster=&quot;/remotion-guide/payload-4-0-poster.png&quot; width=&quot;1920&quot; height=&quot;1080&quot;&gt;
  &lt;source src=&quot;/remotion-guide/payload-4-0-teaser.mp4&quot; type=&quot;video/mp4&quot; /&gt;
  &lt;source src=&quot;/remotion-guide/payload-4-0-teaser.webm&quot; type=&quot;video/webm&quot; /&gt;
  Your browser cannot play this video. &lt;a href=&quot;/remotion-guide/payload-4-0-teaser.mp4&quot;&gt;Download the MP4.&lt;/a&gt;
&lt;/video&gt;&lt;p&gt;By the end, you will have the same five-scene video in two formats: 1920×1080 landscape and 1080×1080 square. You will also understand how Remotion connects a frame number to what appears on screen, how scenes get their own timelines, and how to make fonts and images ready before a frame is captured.&lt;/p&gt;
&lt;p&gt;You should be comfortable with React components, hooks, TypeScript, and basic CSS. You do not need a Payload installation: all the Payload content in this example is text and graphics. The canary labels describe the example&amp;#39;s subject; this tutorial is about creating its animation.&lt;/p&gt;
&lt;p&gt;This is a complete implementation walkthrough. Each application source file appears below. The large component is split into consecutive blocks so we can discuss each part. Copy those blocks into the same file in the order shown.&lt;/p&gt;
&lt;h2&gt;1. Understand what Remotion renders&lt;/h2&gt;
&lt;!-- bwm:slider remotion-react-video-tutorial/remotion-pipeline-scenes --&gt;
&lt;div data-slider=&quot;true&quot; data-slider-id=&quot;remotion-react-video-tutorial/remotion-pipeline-scenes&quot; data-slider-source=&quot;video/src/articles/remotion-react-video-tutorial/remotion-pipeline-scenes&quot;&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/b0062x4y/file/original&quot; alt=&quot;UI = f(frame): The Mental Model: Remotion doesn&apos;t use timelines or keyframe tracks; every frame is a deterministic React render at frame N.&quot; title=&quot;UI = f(frame): The Mental Model&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/o3bbeuvz/file/original&quot; alt=&quot;Isolated Timelines with &amp;lt;Sequence&amp;gt;: Break complex animations into modular scene components with localized frame counters.&quot; title=&quot;Isolated Timelines with &amp;lt;Sequence&amp;gt;&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/lf9r63si/file/original&quot; alt=&quot;Natural Motion with spring(): Replace rigid linear easing with mass, damping, and stiffness for fluid UI physics.&quot; title=&quot;Natural Motion with spring()&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
  &lt;img src=&quot;https://img.buildwithmatija.com/api/images/oorsixjy/file/original&quot; alt=&quot;Responsive Video: 16:9 &amp;amp; 1:1: Use responsive layout hooks to render widescreen YouTube video and square social feeds from one component.&quot; title=&quot;Responsive Video: 16:9 &amp;amp; 1:1&quot; width=&quot;1080&quot; height=&quot;1080&quot; /&gt;
&lt;/div&gt;
&lt;!-- /bwm:slider --&gt;&lt;p&gt;Think of a composition as a React component with a video-sized canvas and a timeline. Remotion supplies the current frame. Your component calculates positions, opacity, scale, and visible content for that frame.&lt;/p&gt;
&lt;p&gt;At 60 frames per second, frame 60 represents one second into the video. Our composition lasts 900 frames, so its duration is &lt;code&gt;900 / 60 = 15&lt;/code&gt; seconds. Frames are zero-based: the first is 0 and the last is 899.&lt;/p&gt;
&lt;p&gt;In Studio, you can scrub directly to a frame and see the component at that point. During a local render, Remotion uses a browser to capture frames and encodes them into a video. The component must therefore produce the right visual even when you jump directly to a later frame.&lt;/p&gt;
&lt;p&gt;This changes how you animate. A web page often starts a CSS transition after a click and lets time pass. In a Remotion composition, the current frame determines the animation state. There is no need to play the previous 100 frames to know how frame 101 should look. Remotion explicitly recommends frame-driven animation instead of CSS transitions and keyframes. &lt;a href=&quot;https://www.remotion.dev/docs/troubleshooting/css-animations&quot;&gt;Read the animation guidance&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Our implementation uses two main tools: &lt;code&gt;interpolate()&lt;/code&gt; for mapping progress to visual values, and &lt;code&gt;spring()&lt;/code&gt; for entrances with a natural settling motion. Ordinary CSS still handles layout, typography, borders, gradients, and colors.&lt;/p&gt;
&lt;h2&gt;2. Create an isolated video project&lt;/h2&gt;
&lt;p&gt;Use Node.js 24 and pnpm 10.33.0 for this walkthrough. Create a fresh directory outside any existing pnpm workspace, so its dependencies and configuration belong to this example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;mkdir remotion-payload-teaser
cd remotion-payload-teaser
mkdir -p src public/fonts out
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;All following shell commands run from this directory. Create the package file before installing anything. These are the versions used by the reference implementation; keep the Remotion packages on the same exact version.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Create &lt;code&gt;package.json&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &amp;quot;name&amp;quot;: &amp;quot;bwm-payload-video&amp;quot;,
  &amp;quot;version&amp;quot;: &amp;quot;1.0.0&amp;quot;,
  &amp;quot;private&amp;quot;: true,
  &amp;quot;type&amp;quot;: &amp;quot;module&amp;quot;,
  &amp;quot;packageManager&amp;quot;: &amp;quot;pnpm@10.33.0&amp;quot;,
  &amp;quot;scripts&amp;quot;: {
    &amp;quot;start&amp;quot;: &amp;quot;remotion studio src/index.ts --port=3100&amp;quot;,
    &amp;quot;render:landscape&amp;quot;: &amp;quot;remotion render src/index.ts Payload4Teaser out/payload-4-0-teaser.mp4 --codec=h264 --pixel-format=yuv420p --crf=18 --concurrency=4 --color-space=bt709 --image-format=png&amp;quot;,
    &amp;quot;render:square&amp;quot;: &amp;quot;remotion render src/index.ts Payload4Square out/payload-4-0-square.mp4 --codec=h264 --pixel-format=yuv420p --crf=18 --concurrency=4 --color-space=bt709 --image-format=png&amp;quot;,
    &amp;quot;render:webm&amp;quot;: &amp;quot;remotion render src/index.ts Payload4Teaser out/payload-4-0-teaser.webm --codec=vp9 --video-bitrate=6M --concurrency=4 --color-space=bt709 --image-format=png&amp;quot;,
    &amp;quot;poster:landscape&amp;quot;: &amp;quot;remotion still src/index.ts Payload4Teaser out/payload-4-0-poster.png --frame=150&amp;quot;,
    &amp;quot;poster:square&amp;quot;: &amp;quot;remotion still src/index.ts Payload4Square out/payload-4-0-square-poster.png --frame=150&amp;quot;
  },
  &amp;quot;dependencies&amp;quot;: {
    &amp;quot;remotion&amp;quot;: &amp;quot;4.0.532&amp;quot;,
    &amp;quot;react&amp;quot;: &amp;quot;19.2.4&amp;quot;,
    &amp;quot;react-dom&amp;quot;: &amp;quot;19.2.4&amp;quot;,
    &amp;quot;lucide-react&amp;quot;: &amp;quot;0.475.0&amp;quot;
  },
  &amp;quot;devDependencies&amp;quot;: {
    &amp;quot;@remotion/cli&amp;quot;: &amp;quot;4.0.532&amp;quot;,
    &amp;quot;@remotion/tailwind-v4&amp;quot;: &amp;quot;4.0.532&amp;quot;,
    &amp;quot;@fontsource/inter&amp;quot;: &amp;quot;5.3.0&amp;quot;,
    &amp;quot;@fontsource/ibm-plex-mono&amp;quot;: &amp;quot;5.3.0&amp;quot;,
    &amp;quot;@types/react&amp;quot;: &amp;quot;19.2.2&amp;quot;,
    &amp;quot;@types/react-dom&amp;quot;: &amp;quot;19.2.2&amp;quot;,
    &amp;quot;typescript&amp;quot;: &amp;quot;5.9.3&amp;quot;,
    &amp;quot;tailwindcss&amp;quot;: &amp;quot;4.2.2&amp;quot;,
    &amp;quot;zod&amp;quot;: &amp;quot;4.5.4&amp;quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Install the dependencies:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm install
pnpm exec remotion versions
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first install generates &lt;code&gt;pnpm-lock.yaml&lt;/code&gt;. Keep that lockfile with your project. Once it exists, use &lt;code&gt;pnpm install --frozen-lockfile&lt;/code&gt; for repeat installations. You do not need to hand-write or copy hundreds of lockfile entries from an article.&lt;/p&gt;
&lt;p&gt;React and React DOM render our components. Remotion supplies the timeline primitives. The CLI opens Studio and exports media. Lucide provides SVG icons, the Fontsource packages supply local font files, and the Tailwind integration processes the utility classes used by the layout. Zod is pinned in the reference package; this composition does not define a custom props schema.&lt;/p&gt;
&lt;p&gt;The finished project will have this structure:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;remotion-payload-teaser/
  package.json
  pnpm-lock.yaml                 # generated by pnpm install
  remotion.config.ts
  tsconfig.json
  src/
    index.ts
    Root.tsx
    Payload4Teaser.tsx
    style.css
  public/
    bwm-logo.svg
    author.jpeg
    fonts/
      inter-400.woff2
      inter-500.woff2
      inter-600.woff2
      inter-700.woff2
      plex-mono-400.woff2
      inter-LICENSE.txt
      ibm-plex-mono-LICENSE.txt
  out/                           # generated videos and stills
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Configure TypeScript and Tailwind&lt;/h3&gt;
&lt;p&gt;The TypeScript configuration includes browser types because the font loader uses &lt;code&gt;FontFace&lt;/code&gt; and &lt;code&gt;document.fonts&lt;/code&gt;. This package is independent of any website&amp;#39;s TypeScript configuration.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Create &lt;code&gt;tsconfig.json&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &amp;quot;compilerOptions&amp;quot;: {
    &amp;quot;target&amp;quot;: &amp;quot;ES2022&amp;quot;,
    &amp;quot;lib&amp;quot;: [&amp;quot;DOM&amp;quot;, &amp;quot;ES2022&amp;quot;, &amp;quot;DOM.Iterable&amp;quot;],
    &amp;quot;jsx&amp;quot;: &amp;quot;react-jsx&amp;quot;,
    &amp;quot;module&amp;quot;: &amp;quot;ESNext&amp;quot;,
    &amp;quot;moduleResolution&amp;quot;: &amp;quot;Bundler&amp;quot;,
    &amp;quot;strict&amp;quot;: true,
    &amp;quot;esModuleInterop&amp;quot;: true,
    &amp;quot;skipLibCheck&amp;quot;: true,
    &amp;quot;noEmit&amp;quot;: true
  },
  &amp;quot;include&amp;quot;: [&amp;quot;src&amp;quot;, &amp;quot;remotion.config.ts&amp;quot;]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tailwind v4 needs a bundler integration in this project. Installing Tailwind alone does not make the classes in our components work. Use Remotion&amp;#39;s &lt;code&gt;enableTailwind()&lt;/code&gt; override. The overwrite setting allows subsequent exports to replace the same output filename. &lt;a href=&quot;https://www.remotion.dev/docs/tailwind-v4/enable-tailwind&quot;&gt;See the official integration&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Create &lt;code&gt;remotion.config.ts&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { Config } from &amp;quot;@remotion/cli/config&amp;quot;;
import { enableTailwind } from &amp;quot;@remotion/tailwind-v4&amp;quot;;

Config.overrideWebpackConfig((config) =&amp;gt; enableTailwind(config));
Config.setOverwriteOutput(true);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The stylesheet imports Tailwind, points source scanning at this directory, and uses border-box sizing. It contains no time-based CSS animation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Create &lt;code&gt;src/style.css&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-css&quot;&gt;@import &amp;quot;tailwindcss&amp;quot;;
@source &amp;#39;./&amp;#39;;

* {
  box-sizing: border-box;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Prepare the images and fonts&lt;/h3&gt;
&lt;p&gt;Download the &lt;a href=&quot;/remotion-guide/assets/bwm-logo.svg&quot;&gt;example logo&lt;/a&gt; and &lt;a href=&quot;/remotion-guide/assets/author.jpeg&quot;&gt;author portrait&lt;/a&gt; into &lt;code&gt;public/&lt;/code&gt;, keeping their filenames. These are the assets shown in the video. For your own video, replace them with your branding.&lt;/p&gt;
&lt;p&gt;On macOS or Linux, you can download them from the site with:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;curl --fail --location https://buildwithmatija.com/remotion-guide/assets/bwm-logo.svg --output public/bwm-logo.svg
curl --fail --location https://buildwithmatija.com/remotion-guide/assets/author.jpeg --output public/author.jpeg
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Copy the font files from the packages you just installed, and rename them to match the paths our component will request:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;for weight in 400 500 600 700; do
  cp &amp;quot;node_modules/@fontsource/inter/files/inter-latin-${weight}-normal.woff2&amp;quot; &amp;quot;public/fonts/inter-${weight}.woff2&amp;quot;
done
cp node_modules/@fontsource/ibm-plex-mono/files/ibm-plex-mono-latin-400-normal.woff2 public/fonts/plex-mono-400.woff2
cp node_modules/@fontsource/inter/LICENSE public/fonts/inter-LICENSE.txt
cp node_modules/@fontsource/ibm-plex-mono/LICENSE public/fonts/ibm-plex-mono-LICENSE.txt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The Latin subset covers the example&amp;#39;s text. If you adapt it to another writing system, select a font subset that includes those characters.&lt;/p&gt;
&lt;p&gt;Remotion&amp;#39;s &lt;code&gt;staticFile()&lt;/code&gt; resolves assets from the project&amp;#39;s &lt;code&gt;public/&lt;/code&gt; directory. We will use it for both the images and fonts, rather than relying on a website-relative URL. &lt;a href=&quot;https://www.remotion.dev/docs/staticfile&quot;&gt;See &lt;code&gt;staticFile()&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;3. Register the entrypoint and compositions&lt;/h2&gt;
&lt;p&gt;The CLI needs an entrypoint that registers our root component.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Create &lt;code&gt;src/index.ts&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;import { registerRoot } from &amp;quot;remotion&amp;quot;;
import { RemotionRoot } from &amp;quot;./Root&amp;quot;;

registerRoot(RemotionRoot);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The root registers two compositions. Each points to the same React component, but supplies different canvas dimensions. The IDs are what the render scripts select. &lt;a href=&quot;https://www.remotion.dev/docs/composition&quot;&gt;See the composition API&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Create &lt;code&gt;src/Root.tsx&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;import { Composition } from &amp;quot;remotion&amp;quot;;
import { Payload4Teaser } from &amp;quot;./Payload4Teaser&amp;quot;;

export const RemotionRoot = () =&amp;gt; {
  return (
    &amp;lt;&amp;gt;
      &amp;lt;Composition
        id=&amp;quot;Payload4Teaser&amp;quot;
        component={Payload4Teaser}
        durationInFrames={900}
        fps={60}
        width={1920}
        height={1080}
        defaultProps={{
          title: &amp;quot;Payload CMS 4.0: Breaking Changes &amp;amp; Canary Deep Dive&amp;quot;,
          slug: &amp;quot;payload-4-0&amp;quot;,
        }}
      /&amp;gt;
      &amp;lt;Composition
        id=&amp;quot;Payload4Square&amp;quot;
        component={Payload4Teaser}
        durationInFrames={900}
        fps={60}
        width={1080}
        height={1080}
        defaultProps={{
          title: &amp;quot;Payload CMS 4.0: Breaking Changes &amp;amp; Canary Deep Dive&amp;quot;,
          slug: &amp;quot;payload-4-0&amp;quot;,
        }}
      /&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both compositions run at 60 fps for 900 frames. The square video is a different layout of the same content, rather than a center crop of the landscape export.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;defaultProps&lt;/code&gt; supplies the title for the opening scene and the article slug for the closing URL. These props do not make every scene generic: the access-control diagrams and other Payload-specific text remain in the component.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Root.tsx&lt;/code&gt; imports &lt;code&gt;Payload4Teaser&lt;/code&gt;, which we create next. Wait until the final component is assembled before opening Studio.&lt;/p&gt;
&lt;h2&gt;4. Create the shared animation and layout components&lt;/h2&gt;
&lt;p&gt;Create &lt;code&gt;src/Payload4Teaser.tsx&lt;/code&gt;. &lt;strong&gt;Copy every TSX block from this section through section 6 into this one file, in order.&lt;/strong&gt; Each block adds new declarations; it does not replace the previous block. Together they are the complete source.&lt;/p&gt;
&lt;h3&gt;Imports, colors, and layout detection&lt;/h3&gt;
&lt;p&gt;Start the file with all imports and the shared constants:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;import { useEffect, useState, type CSSProperties, type ReactNode } from &amp;quot;react&amp;quot;;
import {
  AbsoluteFill,
  Img,
  Sequence,
  continueRender,
  delayRender,
  cancelRender,
  interpolate,
  spring,
  staticFile,
  useCurrentFrame,
  useVideoConfig,
} from &amp;quot;remotion&amp;quot;;
import {
  ArrowRight,
  ArrowUpRight,
  Code2,
  Database,
  GitBranch,
  LockKeyhole,
  ShieldCheck,
  Sparkles,
  Terminal,
  Users,
  Workflow,
} from &amp;quot;lucide-react&amp;quot;;
import &amp;quot;./style.css&amp;quot;;

export type TeaserProps = { title: string; slug: string };
const C = {
  bg: &amp;quot;#0b1120&amp;quot;,
  card: &amp;quot;#1e293b&amp;quot;,
  sky: &amp;quot;#38bdf8&amp;quot;,
  text: &amp;quot;#f1f5f9&amp;quot;,
  muted: &amp;quot;#94a3b8&amp;quot;,
  red: &amp;quot;#fb7185&amp;quot;,
  green: &amp;quot;#6ee7b7&amp;quot;,
  border: &amp;quot;#334155&amp;quot;,
};
const mono: CSSProperties = { fontFamily: &amp;quot;IBM Plex Mono, monospace&amp;quot; };
const clamp = { extrapolateLeft: &amp;quot;clamp&amp;quot;, extrapolateRight: &amp;quot;clamp&amp;quot; } as const;
const useSquare = () =&amp;gt; {
  const { width, height } = useVideoConfig();
  return width === height;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;C&lt;/code&gt; centralizes the palette. &lt;code&gt;mono&lt;/code&gt; gives code and labels a consistent font. &lt;code&gt;clamp&lt;/code&gt; prevents interpolation from continuing beyond its intended endpoints. The &lt;code&gt;useSquare()&lt;/code&gt; hook reads the composition dimensions; it does not use the browser window&amp;#39;s size.&lt;/p&gt;
&lt;p&gt;That distinction matters when the same composition is previewed at different zoom levels. A 1080×1080 canvas stays square even if Studio shows it inside a wide browser window.&lt;/p&gt;
&lt;h3&gt;Wait for bundled fonts&lt;/h3&gt;
&lt;p&gt;Append the font gate:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const FontGate = () =&amp;gt; {
  const [handle] = useState(() =&amp;gt; delayRender(&amp;quot;Loading bundled typography&amp;quot;));
  useEffect(() =&amp;gt; {
    let active = true;
    Promise.all(
      [
        ...[400, 500, 600, 700].map(
          (weight) =&amp;gt;
            new FontFace(
              &amp;quot;Inter&amp;quot;,
              `url(&amp;quot;${staticFile(`fonts/inter-${weight}.woff2`)}&amp;quot;)`,
              { weight: String(weight) },
            ),
        ),
        new FontFace(
          &amp;quot;IBM Plex Mono&amp;quot;,
          `url(&amp;quot;${staticFile(&amp;quot;fonts/plex-mono-400.woff2&amp;quot;)}&amp;quot;)`,
          { weight: &amp;quot;400&amp;quot; },
        ),
      ].map(async (font) =&amp;gt; {
        const loaded = await font.load();
        document.fonts.add(loaded);
      }),
    )
      .then(() =&amp;gt; {
        if (active) continueRender(handle);
      })
      .catch(cancelRender);
    return () =&amp;gt; {
      active = false;
    };
  }, [handle]);
  return null;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The gate creates a render-delay handle once for the mounted component. It loads the required weights, registers them with the browser, and clears the handle when all fonts are ready. A load failure calls &lt;code&gt;cancelRender&lt;/code&gt;, so an export fails rather than silently capturing fallback typography. &lt;a href=&quot;https://www.remotion.dev/docs/delay-render&quot;&gt;See the render-delay lifecycle&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The component renders nothing visible. Its purpose is to coordinate readiness. Loading the typefaces matters because fallback fonts can change text widths, line breaks, and diagram spacing.&lt;/p&gt;
&lt;p&gt;The cleanup flag prevents a completed request from continuing a render after this instance has unmounted. For a larger application, Remotion also provides font-loading utilities; here we retain the small &lt;code&gt;FontFace&lt;/code&gt; implementation used by the reference video. &lt;a href=&quot;https://www.remotion.dev/docs/fonts&quot;&gt;Read the font guide&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Badges and staggered entrances&lt;/h3&gt;
&lt;p&gt;Append the badge component:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Badge = ({
  children,
  color = C.sky,
  style,
}: {
  children: ReactNode;
  color?: string;
  style?: CSSProperties;
}) =&amp;gt; (
  &amp;lt;div
    style={{
      ...mono,
      display: &amp;quot;inline-flex&amp;quot;,
      alignItems: &amp;quot;center&amp;quot;,
      gap: 12,
      padding: &amp;quot;12px 18px&amp;quot;,
      fontSize: 22,
      color,
      background: `${color}10`,
      border: `1px solid ${color}40`,
      borderRadius: 12,
      whiteSpace: &amp;quot;nowrap&amp;quot;,
      ...style,
    }}
  &amp;gt;
    {children}
  &amp;lt;/div&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A badge is ordinary JSX and CSS. Its children can be text, an icon, or both. The same primitive styles the opening tags and the canary indicator.&lt;/p&gt;
&lt;p&gt;Now append the entrance animation:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Pop = ({
  children,
  delay = 0,
  style,
}: {
  children: ReactNode;
  delay?: number;
  style?: CSSProperties;
}) =&amp;gt; {
  const frame = useCurrentFrame();
  const { fps } = useVideoConfig();
  const progress = spring({
    frame: frame - delay,
    fps,
    config: { damping: 22, stiffness: 120, mass: 0.8 },
  });
  return (
    &amp;lt;div
      style={{
        opacity: interpolate(frame - delay, [-8, 16], [0, 1], clamp),
        transform: `translateY(${(1 - progress) * 28}px) scale(${0.97 + progress * 0.03})`,
        ...style,
      }}
    &amp;gt;
      {children}
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Pop&lt;/code&gt; combines two drivers. A spring moves the element from 28 pixels below its resting position and scales it from roughly 0.97 toward 1. Interpolation controls opacity. &lt;code&gt;delay&lt;/code&gt; shifts both calculations, allowing a heading, subtitle, and badges to enter in succession.&lt;/p&gt;
&lt;p&gt;The spring receives the composition&amp;#39;s &lt;code&gt;fps&lt;/code&gt;; the damping, stiffness, and mass values tune how it settles. The frame passed to it is &lt;code&gt;frame - delay&lt;/code&gt;, so each element uses the same entrance with a different start. &lt;a href=&quot;https://www.remotion.dev/docs/spring&quot;&gt;See the spring API&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;There is a subtle detail in the opacity curve: it maps &lt;code&gt;[-8, 16]&lt;/code&gt; to &lt;code&gt;[0, 1]&lt;/code&gt;. That starts fading eight frames before the spring&amp;#39;s nominal start and reaches full opacity sixteen frames after it. &lt;code&gt;delay&lt;/code&gt; therefore does not mean completely invisible until that exact frame.&lt;/p&gt;
&lt;p&gt;Clamping keeps opacity within the chosen range before and after the animation interval. Without clamping, interpolation continues along the line beyond its endpoints. &lt;a href=&quot;https://www.remotion.dev/docs/interpolate&quot;&gt;See interpolation and extrapolation&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Scene framing and headings&lt;/h3&gt;
&lt;p&gt;Append the shared scene wrapper:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Scene = ({
  children,
  duration = 180,
  hold = false,
}: {
  children: ReactNode;
  duration?: number;
  hold?: boolean;
}) =&amp;gt; {
  const frame = useCurrentFrame();
  const sq = useSquare();
  return (
    &amp;lt;AbsoluteFill
      style={{
        padding: sq ? &amp;quot;208px 68px 140px&amp;quot; : &amp;quot;220px 112px 140px&amp;quot;,
        opacity: interpolate(
          frame,
          [0, 16, duration - 13, duration - 1],
          [0.35, 1, 1, hold ? 1 : 0.35],
          clamp,
        ),
        transform: `translateY(${interpolate(frame, [0, 24, duration - 13, duration - 1], [14, 0, 0, hold ? 0 : -8], clamp)}px)`,
      }}
    &amp;gt;
      {children}
    &amp;lt;/AbsoluteFill&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;AbsoluteFill&lt;/code&gt; covers the composition. The wrapper supplies padding, a short entrance, and a short exit based on the scene&amp;#39;s local frame. Its default duration is 180 frames; the longer access scene and shorter depth scene pass explicit durations.&lt;/p&gt;
&lt;p&gt;This example fades between opacity 0.35 and 1, rather than fading completely to black. The final scene uses &lt;code&gt;hold&lt;/code&gt; to keep its end state visible. These are design choices you can change by adjusting the output ranges.&lt;/p&gt;
&lt;p&gt;Append the shared heading:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Heading = ({
  index,
  eyebrow,
  children,
  subtitle,
}: {
  index: string;
  eyebrow: string;
  children: ReactNode;
  subtitle?: ReactNode;
}) =&amp;gt; {
  const sq = useSquare();
  return (
    &amp;lt;div style={{ marginBottom: sq ? 30 : 42 }}&amp;gt;
      &amp;lt;div
        style={{
          ...mono,
          color: C.sky,
          fontSize: 23,
          letterSpacing: 3,
          textTransform: &amp;quot;uppercase&amp;quot;,
          marginBottom: 16,
        }}
      &amp;gt;
        {index} / {eyebrow}
      &amp;lt;/div&amp;gt;
      &amp;lt;h1
        style={{
          fontSize: sq ? 56 : 76,
          fontWeight: 600,
          letterSpacing: -3,
          lineHeight: 1.1,
          margin: 0,
        }}
      &amp;gt;
        {children}
      &amp;lt;/h1&amp;gt;
      {subtitle &amp;amp;&amp;amp; (
        &amp;lt;div
          style={{
            fontSize: sq ? 25 : 28,
            color: C.muted,
            lineHeight: 1.5,
            marginTop: 18,
          }}
        &amp;gt;
          {subtitle}
        &amp;lt;/div&amp;gt;
      )}
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The heading changes font sizes and spacing for the square composition. &lt;code&gt;ReactNode&lt;/code&gt; lets subtitles contain either plain text or JSX, such as a highlighted value.&lt;/p&gt;
&lt;h3&gt;Persistent background and branding&lt;/h3&gt;
&lt;p&gt;Append the background:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Background = () =&amp;gt; {
  const frame = useCurrentFrame();
  const { width } = useVideoConfig();
  return (
    &amp;lt;AbsoluteFill style={{ background: C.bg, overflow: &amp;quot;hidden&amp;quot; }}&amp;gt;
      &amp;lt;AbsoluteFill
        style={{
          background:
            &amp;quot;radial-gradient(ellipse at 82% 18%, #38bdf817 0%, transparent 52%), radial-gradient(ellipse at 12% 90%, #2563eb10 0%, transparent 45%)&amp;quot;,
        }}
      /&amp;gt;
      &amp;lt;AbsoluteFill
        style={{
          opacity: 0.15,
          backgroundImage:
            &amp;quot;linear-gradient(#334155 1px, transparent 1px), linear-gradient(90deg, #334155 1px, transparent 1px)&amp;quot;,
          backgroundSize: &amp;quot;80px 80px&amp;quot;,
          transform: `translateY(${(frame / 30) % 80}px)`,
          top: -80,
          bottom: -80,
        }}
      /&amp;gt;
      &amp;lt;div
        style={{
          position: &amp;quot;absolute&amp;quot;,
          width: 630,
          height: 630,
          border: &amp;quot;1px solid #38bdf814&amp;quot;,
          borderRadius: &amp;quot;50%&amp;quot;,
          right: -170,
          top: -180,
          transform: `scale(${1 + frame / 18000})`,
        }}
      /&amp;gt;
      &amp;lt;div
        style={{
          position: &amp;quot;absolute&amp;quot;,
          width: 840,
          height: 840,
          border: &amp;quot;1px solid #38bdf80b&amp;quot;,
          borderRadius: &amp;quot;50%&amp;quot;,
          right: -275,
          top: -285,
        }}
      /&amp;gt;
      &amp;lt;div
        style={{
          position: &amp;quot;absolute&amp;quot;,
          bottom: 0,
          left: 0,
          height: 5,
          width: (width * (frame + 1)) / 900,
          background: C.sky,
          boxShadow: &amp;quot;0 0 24px #38bdf880&amp;quot;,
        }}
      /&amp;gt;
    &amp;lt;/AbsoluteFill&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The gradient, grid, rings, and progress bar remain behind every scene. Their movement comes from the current frame. The grid translates using a repeating calculation, and the large ring slowly scales.&lt;/p&gt;
&lt;p&gt;The progress bar uses &lt;code&gt;(frame + 1) / 900&lt;/code&gt;, so it reaches full width on the last frame, 899. The denominator is deliberately tied to this video&amp;#39;s fixed duration. If you change the composition length, update it too, or derive it from &lt;code&gt;useVideoConfig()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Append the brand overlay:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Brand = () =&amp;gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const chapter =
    frame &amp;lt; 180
      ? &amp;quot;THE V4 BREAKDOWN&amp;quot;
      : frame &amp;lt; 420
        ? &amp;quot;SECURITY DEFAULTS&amp;quot;
        : frame &amp;lt; 540
          ? &amp;quot;QUERY DEPTH&amp;quot;
          : frame &amp;lt; 720
            ? &amp;quot;FRAMEWORK ADAPTERS&amp;quot;
            : &amp;quot;THE FULL GUIDE&amp;quot;;
  return (
    &amp;lt;&amp;gt;
      &amp;lt;div
        className=&amp;quot;flex items-center justify-between&amp;quot;
        style={{
          position: &amp;quot;absolute&amp;quot;,
          top: sq ? 66 : 64,
          left: sq ? 68 : 112,
          right: sq ? 68 : 112,
          height: 64,
        }}
      &amp;gt;
        &amp;lt;div className=&amp;quot;flex items-center&amp;quot; style={{ gap: 18 }}&amp;gt;
          &amp;lt;Img
            src={staticFile(&amp;quot;bwm-logo.svg&amp;quot;)}
            style={{ width: 54, height: 54, borderRadius: 9 }}
          /&amp;gt;
          &amp;lt;div
            style={{
              fontSize: sq ? 24 : 26,
              letterSpacing: -0.7,
              fontWeight: 600,
            }}
          &amp;gt;
            Build with Matija&amp;lt;span style={{ color: C.sky }}&amp;gt;.&amp;lt;/span&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;Badge style={{ fontSize: sq ? 17 : 19, padding: &amp;quot;10px 14px&amp;quot; }}&amp;gt;
          &amp;lt;span
            style={{
              width: 7,
              height: 7,
              borderRadius: &amp;quot;50%&amp;quot;,
              background: C.sky,
            }}
          /&amp;gt;
          V4 CANARY
        &amp;lt;/Badge&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div
        style={{
          position: &amp;quot;absolute&amp;quot;,
          bottom: 56,
          left: sq ? 68 : 112,
          right: sq ? 68 : 112,
          display: &amp;quot;flex&amp;quot;,
          justifyContent: &amp;quot;space-between&amp;quot;,
          color: C.muted,
          ...mono,
          fontSize: sq ? 17 : 20,
          letterSpacing: 1.2,
        }}
      &amp;gt;
        &amp;lt;span&amp;gt;{chapter}&amp;lt;/span&amp;gt;
        &amp;lt;span&amp;gt;buildwithmatija.com&amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The chapter labels switch at the same frame boundaries we will use for the scenes. The logo, canary badge, chapter label, and website address stay visible across the whole timeline.&lt;/p&gt;
&lt;p&gt;We will place &lt;code&gt;Background&lt;/code&gt; and &lt;code&gt;Brand&lt;/code&gt; outside the sequences. They therefore receive the composition&amp;#39;s frame, while the scene components inside a sequence receive a local frame. That lets the background stay continuous while each scene starts its own entrance at zero.&lt;/p&gt;
&lt;h2&gt;5. Build the five scenes&lt;/h2&gt;
&lt;p&gt;Continue appending these blocks to &lt;code&gt;src/Payload4Teaser.tsx&lt;/code&gt;. We are now composing the shared primitives into the exact content shown in the video.&lt;/p&gt;
&lt;h3&gt;Scene 1: title and hook&lt;/h3&gt;
&lt;p&gt;Append the opening scene:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Hook = ({ title }: { title: string }) =&amp;gt; {
  const sq = useSquare();
  const separator = title.indexOf(&amp;quot;:&amp;quot;);
  const headline = separator &amp;lt; 0 ? title : title.slice(0, separator);
  const subtitle =
    separator &amp;lt; 0
      ? &amp;quot;Breaking Changes &amp;amp; Canary Deep Dive&amp;quot;
      : title.slice(separator + 1).trim();
  return (
    &amp;lt;Scene&amp;gt;
      &amp;lt;Pop&amp;gt;
        &amp;lt;div
          style={{
            ...mono,
            fontSize: 23,
            color: C.sky,
            letterSpacing: 3,
            marginBottom: sq ? 36 : 34,
          }}
        &amp;gt;
          ARCHITECTURE / MIGRATION / WHAT’S NEXT
        &amp;lt;/div&amp;gt;
      &amp;lt;/Pop&amp;gt;
      &amp;lt;Pop delay={8}&amp;gt;
        &amp;lt;h1
          style={{
            fontSize: sq ? 104 : 146,
            lineHeight: 1.06,
            fontWeight: 600,
            letterSpacing: sq ? -6 : -8,
            margin: 0,
            maxWidth: sq ? 900 : 1600,
          }}
        &amp;gt;
          {headline.replace(&amp;quot; 4.0&amp;quot;, &amp;quot;&amp;quot;)}
          &amp;lt;br /&amp;gt;
          &amp;lt;span style={{ color: C.sky }}&amp;gt;4.0&amp;lt;/span&amp;gt;
          &amp;lt;span
            style={{
              fontSize: sq ? 27 : 32,
              letterSpacing: 0,
              color: C.muted,
              marginLeft: 28,
              verticalAlign: &amp;quot;middle&amp;quot;,
              ...mono,
            }}
          &amp;gt;
            THE NEXT CHAPTER
          &amp;lt;/span&amp;gt;
        &amp;lt;/h1&amp;gt;
      &amp;lt;/Pop&amp;gt;
      &amp;lt;Pop delay={20}&amp;gt;
        &amp;lt;div
          style={{
            fontSize: sq ? 40 : 49,
            lineHeight: 1.25,
            fontWeight: 500,
            letterSpacing: -1.3,
            maxWidth: sq ? 820 : 1400,
            marginTop: sq ? 28 : 32,
          }}
        &amp;gt;
          {subtitle}
        &amp;lt;/div&amp;gt;
      &amp;lt;/Pop&amp;gt;
      &amp;lt;div
        className=&amp;quot;flex flex-wrap&amp;quot;
        style={{ gap: 14, maxWidth: sq ? 810 : 1550, marginTop: sq ? 40 : 50 }}
      &amp;gt;
        {[
          &amp;quot;Node 24&amp;quot;,
          &amp;quot;Next.js 16&amp;quot;,
          &amp;quot;TanStack Start&amp;quot;,
          &amp;quot;overrideAccess: false&amp;quot;,
        ].map((tag, i) =&amp;gt; (
          &amp;lt;Pop key={tag} delay={32 + i * 8}&amp;gt;
            &amp;lt;Badge style={{ fontSize: sq ? 23 : 25 }}&amp;gt;{tag}&amp;lt;/Badge&amp;gt;
          &amp;lt;/Pop&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
      &amp;lt;Pop delay={70}&amp;gt;
        &amp;lt;div style={{ color: C.muted, fontSize: sq ? 24 : 26, marginTop: 30 }}&amp;gt;
          A closer look at the defaults that change your code.
        &amp;lt;/div&amp;gt;
      &amp;lt;/Pop&amp;gt;
    &amp;lt;/Scene&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The title is split at its first colon. The first part becomes the headline, and the rest becomes the subtitle. The highlighted &lt;code&gt;4.0&lt;/code&gt; and the supporting labels are specific to this example.&lt;/p&gt;
&lt;p&gt;The tags use delays of &lt;code&gt;32 + i * 8&lt;/code&gt; frames, so each starts eight frames after the previous tag. At 60 fps that spacing is about 0.13 seconds. The animation stays deterministic because the delay comes from the array index.&lt;/p&gt;
&lt;h3&gt;Scene 2: compare access defaults&lt;/h3&gt;
&lt;p&gt;Append the comparison card and its scene:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const AccessCard = ({ v4 }: { v4: boolean }) =&amp;gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const color = v4 ? C.green : C.red;
  const draw = interpolate(frame, [v4 ? 58 : 25, v4 ? 100 : 67], [0, 1], clamp);
  return (
    &amp;lt;div
      style={{
        background: &amp;quot;linear-gradient(135deg, #1e293b, #152033)&amp;quot;,
        border: `1px solid ${color}45`,
        borderRadius: 24,
        padding: sq ? &amp;quot;20px 28px&amp;quot; : &amp;quot;32px 36px&amp;quot;,
        flex: 1,
        position: &amp;quot;relative&amp;quot;,
        lineHeight: 1.2,
        boxShadow: &amp;quot;0 18px 60px #00000020&amp;quot;,
      }}
    &amp;gt;
      &amp;lt;div className=&amp;quot;flex items-center justify-between&amp;quot;&amp;gt;
        &amp;lt;div style={{ ...mono, fontSize: sq ? 20 : 24, color: C.muted }}&amp;gt;
          PAYLOAD {v4 ? &amp;quot;4&amp;quot; : &amp;quot;3&amp;quot;}
        &amp;lt;/div&amp;gt;
        &amp;lt;div style={{ color }}&amp;gt;
          {sq ? (
            &amp;lt;span style={{ ...mono, fontSize: 21 }}&amp;gt;
              overrideAccess: {v4 ? &amp;quot;false&amp;quot; : &amp;quot;true&amp;quot;}
            &amp;lt;/span&amp;gt;
          ) : (
            &amp;lt;ShieldCheck size={32} /&amp;gt;
          )}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div
        style={{
          display: &amp;quot;flex&amp;quot;,
          alignItems: &amp;quot;center&amp;quot;,
          gap: 20,
          marginTop: sq ? 12 : 28,
        }}
      &amp;gt;
        &amp;lt;Terminal color={C.muted} size={sq ? 28 : 36} /&amp;gt;
        &amp;lt;svg width={sq ? 140 : 180} height=&amp;quot;28&amp;quot; viewBox=&amp;quot;0 0 180 28&amp;quot;&amp;gt;
          &amp;lt;path
            d=&amp;quot;M0 14 H164&amp;quot;
            pathLength={1}
            stroke={color}
            strokeWidth={2}
            fill=&amp;quot;none&amp;quot;
            strokeDasharray=&amp;quot;1&amp;quot;
            strokeDashoffset={1 - draw}
          /&amp;gt;
          &amp;lt;path
            d=&amp;quot;M156 6 L164 14 L156 22&amp;quot;
            stroke={color}
            strokeWidth={2}
            fill=&amp;quot;none&amp;quot;
            opacity={draw}
          /&amp;gt;
        &amp;lt;/svg&amp;gt;
        &amp;lt;div style={{ color }}&amp;gt;
          {v4 ? (
            &amp;lt;LockKeyhole size={sq ? 28 : 36} /&amp;gt;
          ) : (
            &amp;lt;Database size={sq ? 28 : 36} /&amp;gt;
          )}
        &amp;lt;/div&amp;gt;
        &amp;lt;span style={{ ...mono, color, fontSize: sq ? 21 : 23 }}&amp;gt;
          {v4 ? &amp;quot;RULES EVALUATED&amp;quot; : &amp;quot;RULES BYPASSED&amp;quot;}
        &amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div
        style={{
          fontSize: sq ? 30 : 42,
          fontWeight: 600,
          letterSpacing: -1.2,
          marginTop: sq ? 12 : 28,
        }}
      &amp;gt;
        {v4 ? &amp;quot;Access enforced by default&amp;quot; : &amp;quot;Implicit superadmin&amp;quot;}
      &amp;lt;/div&amp;gt;
      {!sq &amp;amp;&amp;amp; (
        &amp;lt;div style={{ ...mono, fontSize: 26, color, marginTop: 16 }}&amp;gt;
          overrideAccess: {v4 ? &amp;quot;false&amp;quot; : &amp;quot;true&amp;quot;}
        &amp;lt;/div&amp;gt;
      )}
      &amp;lt;div
        style={{
          fontSize: sq ? 21 : 25,
          color: C.muted,
          marginTop: sq ? 12 : 24,
        }}
      &amp;gt;
        {v4 ? &amp;quot;Allow · Filter · Deny&amp;quot; : &amp;quot;Collection access checks skipped&amp;quot;}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const Access = () =&amp;gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  return (
    &amp;lt;Scene duration={240}&amp;gt;
      &amp;lt;Heading
        index=&amp;quot;01&amp;quot;
        eyebrow=&amp;quot;Secure by default&amp;quot;
        subtitle={&amp;lt;&amp;gt;Same Local API query. Different default.&amp;lt;/&amp;gt;}
      &amp;gt;
        The rules now apply.
      &amp;lt;/Heading&amp;gt;
      &amp;lt;Pop delay={4}&amp;gt;
        &amp;lt;div
          style={{
            ...mono,
            fontSize: sq ? 25 : 29,
            background: &amp;quot;#02061780&amp;quot;,
            border: `1px solid ${C.border}`,
            borderRadius: 14,
            padding: &amp;quot;18px 24px&amp;quot;,
            marginBottom: sq ? 22 : 30,
            color: C.text,
          }}
        &amp;gt;
          payload.find({&amp;quot;{&amp;quot;} collection:{&amp;quot; &amp;quot;}
          &amp;lt;span style={{ color: C.sky }}&amp;gt;&amp;#39;orders&amp;#39;&amp;lt;/span&amp;gt; {&amp;quot;}&amp;quot;})
          &amp;lt;span
            style={{
              color: C.muted,
              fontSize: sq ? 18 : 22,
              display: sq ? &amp;quot;block&amp;quot; : &amp;quot;inline&amp;quot;,
              marginLeft: sq ? 0 : 22,
              marginTop: sq ? 8 : 0,
            }}
          &amp;gt;
            // overrideAccess omitted
          &amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/Pop&amp;gt;
      &amp;lt;div
        style={{
          display: &amp;quot;flex&amp;quot;,
          flexDirection: sq ? &amp;quot;column&amp;quot; : &amp;quot;row&amp;quot;,
          gap: sq ? 18 : 28,
          transform: `scale(${interpolate(frame, [50, 190], [1, 1.012], clamp)})`,
          transformOrigin: &amp;quot;center&amp;quot;,
        }}
      &amp;gt;
        &amp;lt;Pop delay={12} style={{ flex: 1, display: &amp;quot;flex&amp;quot; }}&amp;gt;
          &amp;lt;AccessCard v4={false} /&amp;gt;
        &amp;lt;/Pop&amp;gt;
        &amp;lt;Pop delay={42} style={{ flex: 1, display: &amp;quot;flex&amp;quot; }}&amp;gt;
          &amp;lt;AccessCard v4 /&amp;gt;
        &amp;lt;/Pop&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;Pop delay={90}&amp;gt;
        &amp;lt;div
          style={{
            color: C.muted,
            fontSize: sq ? 21 : 25,
            marginTop: sq ? 20 : 28,
          }}
        &amp;gt;
          No user? Public access rules apply.
        &amp;lt;/div&amp;gt;
      &amp;lt;/Pop&amp;gt;
    &amp;lt;/Scene&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The two cards share one component. The &lt;code&gt;v4&lt;/code&gt; flag changes the labels, colors, icons, and connector timing. For the animated SVG line, &lt;code&gt;pathLength={1}&lt;/code&gt; normalizes the path length and &lt;code&gt;strokeDashoffset={1 - draw}&lt;/code&gt; reveals it as &lt;code&gt;draw&lt;/code&gt; moves toward 1.&lt;/p&gt;
&lt;p&gt;The square layout stacks the cards and moves the access-default text into each header. That removes repeated detail from the taller layout and keeps room for the query, heading, and footer. Simply changing the canvas size would not make the landscape scene fit.&lt;/p&gt;
&lt;p&gt;The scene lasts 240 frames, which is four seconds. Its card entrances use local frame values, so their delays are measured from the start of this scene, not from frame zero of the full video.&lt;/p&gt;
&lt;p&gt;The example&amp;#39;s message distinguishes access checks being evaluated from a request being granted. The green card still lists Allow, Filter, and Deny; the diagram should not imply that evaluating rules always allows access.&lt;/p&gt;
&lt;h3&gt;Scene 3: relationship depth&lt;/h3&gt;
&lt;p&gt;Append the relationship row and the depth scene:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const RelationshipRow = ({ v4 }: { v4: boolean }) =&amp;gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const draw = interpolate(frame, [v4 ? 25 : 8, v4 ? 65 : 42], [0, 1], clamp);
  const labels = [&amp;quot;Post&amp;quot;, &amp;quot;Author&amp;quot;, v4 ? &amp;quot;Avatar ID&amp;quot; : &amp;quot;Avatar document&amp;quot;];
  const icons = [
    &amp;lt;Code2 key=&amp;quot;post&amp;quot; size={32} /&amp;gt;,
    &amp;lt;Users key=&amp;quot;author&amp;quot; size={32} /&amp;gt;,
    &amp;lt;Database key=&amp;quot;avatar&amp;quot; size={32} /&amp;gt;,
  ];
  return (
    &amp;lt;div
      style={{
        padding: sq ? &amp;quot;26px 24px&amp;quot; : &amp;quot;30px 36px&amp;quot;,
        border: `1px solid ${v4 ? C.sky + &amp;quot;60&amp;quot; : C.border}`,
        borderRadius: 24,
        background: v4 ? &amp;quot;#12253b&amp;quot; : &amp;quot;#1e293b90&amp;quot;,
        lineHeight: 1.2,
      }}
    &amp;gt;
      &amp;lt;div
        style={{
          ...mono,
          color: v4 ? C.sky : C.muted,
          fontSize: 23,
          marginBottom: 24,
        }}
      &amp;gt;
        PAYLOAD {v4 ? &amp;quot;4&amp;quot; : &amp;quot;3&amp;quot;}{&amp;quot; &amp;quot;}
        &amp;lt;span style={{ color: C.muted }}&amp;gt;
          {&amp;quot; &amp;quot;}
          / DEFAULT DEPTH: {v4 ? &amp;quot;1&amp;quot; : &amp;quot;2&amp;quot;}
        &amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div className=&amp;quot;flex items-center&amp;quot; style={{ gap: sq ? 10 : 24 }}&amp;gt;
        {labels.map((label, i) =&amp;gt; (
          &amp;lt;div key={label} style={{ display: &amp;quot;contents&amp;quot; }}&amp;gt;
            {i &amp;gt; 0 &amp;amp;&amp;amp; (
              &amp;lt;svg
                width={sq ? 60 : 140}
                height=&amp;quot;30&amp;quot;
                viewBox=&amp;quot;0 0 140 30&amp;quot;
                style={{ flexShrink: 0 }}
              &amp;gt;
                &amp;lt;path
                  d=&amp;quot;M0 15 H126&amp;quot;
                  stroke={v4 &amp;amp;&amp;amp; i === 2 ? C.muted : C.sky}
                  strokeWidth={2}
                  strokeDasharray={v4 &amp;amp;&amp;amp; i === 2 ? &amp;quot;8 7&amp;quot; : undefined}
                  opacity={draw}
                /&amp;gt;
                &amp;lt;path
                  d=&amp;quot;M118 7 L126 15 L118 23&amp;quot;
                  stroke={v4 &amp;amp;&amp;amp; i === 2 ? C.muted : C.sky}
                  strokeWidth={2}
                  fill=&amp;quot;none&amp;quot;
                  opacity={draw}
                /&amp;gt;
              &amp;lt;/svg&amp;gt;
            )}
            &amp;lt;div
              style={{
                flex: 1,
                padding: sq ? &amp;quot;22px 12px&amp;quot; : &amp;quot;26px 30px&amp;quot;,
                border: `1px ${v4 &amp;amp;&amp;amp; i === 2 ? &amp;quot;dashed&amp;quot; : &amp;quot;solid&amp;quot;} ${C.border}`,
                background: &amp;quot;#0b1120a0&amp;quot;,
                borderRadius: 14,
                display: &amp;quot;flex&amp;quot;,
                flexDirection: sq ? &amp;quot;column&amp;quot; : &amp;quot;row&amp;quot;,
                alignItems: &amp;quot;center&amp;quot;,
                gap: 16,
                color: v4 &amp;amp;&amp;amp; i === 2 ? C.muted : C.text,
              }}
            &amp;gt;
              &amp;lt;span style={{ color: i === 2 &amp;amp;&amp;amp; v4 ? C.muted : C.sky }}&amp;gt;
                {icons[i]}
              &amp;lt;/span&amp;gt;
              &amp;lt;span
                style={{
                  fontSize: sq ? 25 : 32,
                  fontWeight: 500,
                  textAlign: &amp;quot;center&amp;quot;,
                  whiteSpace: &amp;quot;nowrap&amp;quot;,
                }}
              &amp;gt;
                {label}
              &amp;lt;/span&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

const Depth = () =&amp;gt; (
  &amp;lt;Scene duration={120}&amp;gt;
    &amp;lt;Heading
      index=&amp;quot;02&amp;quot;
      eyebrow=&amp;quot;Leaner queries&amp;quot;
      subtitle=&amp;quot;One fewer populated relationship level.&amp;quot;
    &amp;gt;
      Default depth: &amp;lt;span style={{ color: C.muted }}&amp;gt;2&amp;lt;/span&amp;gt;{&amp;quot; &amp;quot;}
      &amp;lt;span style={{ color: C.sky }}&amp;gt;→ 1&amp;lt;/span&amp;gt;
    &amp;lt;/Heading&amp;gt;
    &amp;lt;div style={{ display: &amp;quot;flex&amp;quot;, flexDirection: &amp;quot;column&amp;quot;, gap: 24 }}&amp;gt;
      &amp;lt;Pop&amp;gt;
        &amp;lt;RelationshipRow v4={false} /&amp;gt;
      &amp;lt;/Pop&amp;gt;
      &amp;lt;Pop delay={18}&amp;gt;
        &amp;lt;RelationshipRow v4 /&amp;gt;
      &amp;lt;/Pop&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;Pop delay={45}&amp;gt;
      &amp;lt;div style={{ marginTop: 28, fontSize: 25, color: C.muted }}&amp;gt;
        Need the avatar document? Set{&amp;quot; &amp;quot;}
        &amp;lt;span style={{ ...mono, color: C.sky }}&amp;gt;depth: 2&amp;lt;/span&amp;gt;.
      &amp;lt;/div&amp;gt;
    &amp;lt;/Pop&amp;gt;
  &amp;lt;/Scene&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This scene uses two rows to compare the diagrams. The last node is a populated document in one row and an ID in the other. Dashed styling carries that distinction even without relying on color.&lt;/p&gt;
&lt;p&gt;The node contents are React components, including Lucide SVG icons. The connectors are SVG paths. Remotion can animate them because their visible properties are calculated from frames, just like the earlier HTML cards.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Scene duration={120}&lt;/code&gt; keeps this scene&amp;#39;s entrance and exit aligned with its two-second sequence. The second row and explanatory note arrive later through &lt;code&gt;Pop&lt;/code&gt; delays.&lt;/p&gt;
&lt;h3&gt;Scene 4: framework adapters and the shared core&lt;/h3&gt;
&lt;p&gt;Append the framework scene:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const Frameworks = () =&amp;gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  const progress = interpolate(frame, [25, 72], [0, 1], clamp);
  return (
    &amp;lt;Scene&amp;gt;
      &amp;lt;Heading index=&amp;quot;03&amp;quot; eyebrow=&amp;quot;Framework boundary&amp;quot;&amp;gt;
        Two paths. One core.
      &amp;lt;/Heading&amp;gt;
      &amp;lt;div style={{ position: &amp;quot;relative&amp;quot; }}&amp;gt;
        &amp;lt;div className=&amp;quot;flex&amp;quot; style={{ gap: 24 }}&amp;gt;
          {[false, true].map((tanstack) =&amp;gt; (
            &amp;lt;Pop
              key={String(tanstack)}
              delay={tanstack ? 12 : 0}
              style={{ flex: 1 }}
            &amp;gt;
              &amp;lt;div
                style={{
                  padding: sq ? &amp;quot;26px 24px&amp;quot; : &amp;quot;24px 36px&amp;quot;,
                  lineHeight: 1.2,
                  background: &amp;quot;#1e293bcc&amp;quot;,
                  border: `1px ${tanstack ? &amp;quot;dashed&amp;quot; : &amp;quot;solid&amp;quot;} ${tanstack ? &amp;quot;#38bdf870&amp;quot; : C.border}`,
                  borderRadius: 24,
                }}
              &amp;gt;
                &amp;lt;div
                  style={{
                    display: &amp;quot;flex&amp;quot;,
                    gap: 16,
                    alignItems: &amp;quot;center&amp;quot;,
                    color: C.sky,
                  }}
                &amp;gt;
                  {tanstack ? &amp;lt;GitBranch size={32} /&amp;gt; : &amp;lt;Workflow size={32} /&amp;gt;}
                  &amp;lt;span
                    style={{
                      fontSize: sq ? 30 : 38,
                      fontWeight: 600,
                      letterSpacing: -1,
                    }}
                  &amp;gt;
                    {tanstack ? &amp;quot;TanStack Start&amp;quot; : &amp;quot;Next.js&amp;quot;}
                  &amp;lt;/span&amp;gt;
                &amp;lt;/div&amp;gt;
                &amp;lt;div
                  style={{
                    ...mono,
                    color: C.muted,
                    fontSize: sq ? 22 : 25,
                    marginTop: 18,
                  }}
                &amp;gt;
                  {tanstack ? &amp;quot;Vite / Router&amp;quot; : &amp;quot;App Router / RSC&amp;quot;}
                &amp;lt;/div&amp;gt;
                &amp;lt;div
                  style={{
                    color: tanstack ? C.sky : C.muted,
                    fontSize: sq ? 21 : 23,
                    marginTop: 16,
                  }}
                &amp;gt;
                  {tanstack ? &amp;quot;Experimental canary&amp;quot; : &amp;quot;Established adapter&amp;quot;}
                &amp;lt;/div&amp;gt;
              &amp;lt;/div&amp;gt;
            &amp;lt;/Pop&amp;gt;
          ))}
        &amp;lt;/div&amp;gt;
        &amp;lt;svg
          width=&amp;quot;100%&amp;quot;
          height={sq ? 96 : 116}
          viewBox=&amp;quot;0 0 1000 116&amp;quot;
          preserveAspectRatio=&amp;quot;none&amp;quot;
          style={{ display: &amp;quot;block&amp;quot; }}
        &amp;gt;
          &amp;lt;path
            d=&amp;quot;M245 0 V48 Q245 58 255 58 H490 Q500 58 500 68 V106&amp;quot;
            fill=&amp;quot;none&amp;quot;
            stroke={C.sky}
            strokeWidth={2}
            pathLength={1}
            strokeDasharray=&amp;quot;1&amp;quot;
            strokeDashoffset={1 - progress}
          /&amp;gt;
          &amp;lt;path
            d=&amp;quot;M755 0 V48 Q755 58 745 58 H500 V106&amp;quot;
            fill=&amp;quot;none&amp;quot;
            stroke={C.sky}
            strokeWidth={2}
            strokeDasharray=&amp;quot;8 7&amp;quot;
            opacity={progress}
          /&amp;gt;
          &amp;lt;path
            d=&amp;quot;M490 96 L500 106 L510 96&amp;quot;
            fill=&amp;quot;none&amp;quot;
            stroke={C.sky}
            strokeWidth={2}
            opacity={progress}
          /&amp;gt;
        &amp;lt;/svg&amp;gt;
        &amp;lt;Pop delay={30}&amp;gt;
          &amp;lt;div
            style={{
              border: &amp;quot;1px solid #38bdf870&amp;quot;,
              borderRadius: 24,
              padding: sq ? &amp;quot;28px&amp;quot; : &amp;quot;26px 42px&amp;quot;,
              lineHeight: 1.2,
              background: &amp;quot;linear-gradient(120deg, #0c2840, #122036)&amp;quot;,
              display: &amp;quot;flex&amp;quot;,
              alignItems: &amp;quot;center&amp;quot;,
              gap: 24,
            }}
          &amp;gt;
            &amp;lt;Database size={sq ? 48 : 62} color={C.sky} /&amp;gt;
            &amp;lt;div&amp;gt;
              &amp;lt;div
                style={{
                  fontSize: sq ? 39 : 49,
                  fontWeight: 600,
                  letterSpacing: -1.5,
                }}
              &amp;gt;
                Payload 4 Core
              &amp;lt;/div&amp;gt;
              &amp;lt;div
                style={{
                  fontSize: sq ? 22 : 26,
                  marginTop: 12,
                  color: C.muted,
                }}
              &amp;gt;
                Local API · Collections · Auth · Database adapters
              &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/Pop&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;Pop delay={58}&amp;gt;
        &amp;lt;div
          style={{
            display: &amp;quot;flex&amp;quot;,
            alignItems: &amp;quot;center&amp;quot;,
            gap: 18,
            marginTop: sq ? 30 : 28,
          }}
        &amp;gt;
          &amp;lt;Sparkles color={C.sky} size={30} /&amp;gt;
          &amp;lt;div&amp;gt;
            &amp;lt;div style={{ fontSize: sq ? 29 : 34, fontWeight: 500 }}&amp;gt;
              Zero Sass. Pure CSS variables.
            &amp;lt;/div&amp;gt;
            &amp;lt;div style={{ fontSize: 22, color: C.muted, marginTop: 8 }}&amp;gt;
              Semantic tokens for the refreshed admin.
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/Pop&amp;gt;
    &amp;lt;/Scene&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Both framework cards point toward one Payload core. The Next.js path is solid, while the TanStack Start card and path retain the example&amp;#39;s experimental-canary styling.&lt;/p&gt;
&lt;p&gt;The solid connector uses the same normalized path-length technique as the access cards. The dashed connector fades in through &lt;code&gt;opacity={progress}&lt;/code&gt;. The SVG view box provides a shared coordinate system while its rendered width follows the composition.&lt;/p&gt;
&lt;p&gt;The scene is ordinary React composition: two cards, a connector diagram, a core card, and an admin-style note. The motion is concentrated in entrances and connector reveals, making the content easier to read during its three seconds on screen.&lt;/p&gt;
&lt;h3&gt;Scene 5: hold the call to action&lt;/h3&gt;
&lt;p&gt;Append the closing scene:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;const CTA = ({ slug }: { slug: string }) =&amp;gt; {
  const sq = useSquare();
  const frame = useCurrentFrame();
  return (
    &amp;lt;Scene hold&amp;gt;
      &amp;lt;div
        style={{
          transform: `scale(${interpolate(frame, [0, 48], [1.025, 1], clamp)})`,
          transformOrigin: &amp;quot;center&amp;quot;,
        }}
      &amp;gt;
        &amp;lt;Pop&amp;gt;
          &amp;lt;div
            style={{
              ...mono,
              color: C.sky,
              fontSize: 23,
              letterSpacing: 3,
              marginBottom: 34,
            }}
          &amp;gt;
            YOUR NEXT MIGRATION STARTS HERE
          &amp;lt;/div&amp;gt;
        &amp;lt;/Pop&amp;gt;
        &amp;lt;Pop delay={6}&amp;gt;
          &amp;lt;h1
            style={{
              fontSize: sq ? 83 : 112,
              letterSpacing: -5,
              fontWeight: 600,
              lineHeight: 1.09,
              margin: 0,
            }}
          &amp;gt;
            Read the full guide
            &amp;lt;br /&amp;gt;
            &amp;lt;span style={{ color: C.sky }}&amp;gt;
              &amp;amp; migration
              &amp;lt;br className={sq ? &amp;quot;&amp;quot; : &amp;quot;hidden&amp;quot;} /&amp;gt; breakdown.
            &amp;lt;/span&amp;gt;
          &amp;lt;/h1&amp;gt;
        &amp;lt;/Pop&amp;gt;
        &amp;lt;Pop delay={18}&amp;gt;
          &amp;lt;div
            style={{
              display: &amp;quot;flex&amp;quot;,
              alignItems: &amp;quot;center&amp;quot;,
              gap: 20,
              marginTop: sq ? 34 : 42,
              padding: sq ? &amp;quot;22px 24px&amp;quot; : &amp;quot;24px 30px&amp;quot;,
              border: &amp;quot;1px solid #38bdf860&amp;quot;,
              borderRadius: 18,
              background: &amp;quot;#38bdf80d&amp;quot;,
              maxWidth: sq ? 940 : 1410,
            }}
          &amp;gt;
            &amp;lt;ArrowUpRight color={C.sky} size={36} /&amp;gt;
            &amp;lt;div style={{ ...mono, fontSize: sq ? 28 : 33, lineHeight: 1.5 }}&amp;gt;
              &amp;lt;span&amp;gt;buildwithmatija.com&amp;lt;/span&amp;gt;
              &amp;lt;span style={{ color: C.sky, display: sq ? &amp;quot;block&amp;quot; : &amp;quot;inline&amp;quot; }}&amp;gt;
                /blog/{slug}
              &amp;lt;/span&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/Pop&amp;gt;
        &amp;lt;Pop delay={30}&amp;gt;
          &amp;lt;div
            style={{
              display: &amp;quot;flex&amp;quot;,
              alignItems: &amp;quot;center&amp;quot;,
              gap: 22,
              marginTop: sq ? 34 : 44,
            }}
          &amp;gt;
            &amp;lt;Img
              src={staticFile(&amp;quot;author.jpeg&amp;quot;)}
              style={{
                width: 74,
                height: 74,
                borderRadius: &amp;quot;50%&amp;quot;,
                objectFit: &amp;quot;cover&amp;quot;,
                border: &amp;quot;2px solid #334155&amp;quot;,
              }}
            /&amp;gt;
            &amp;lt;div&amp;gt;
              &amp;lt;div style={{ fontSize: 29, fontWeight: 500 }}&amp;gt;
                Matija Žiberna
              &amp;lt;/div&amp;gt;
              &amp;lt;div style={{ fontSize: 22, color: C.muted, marginTop: 7 }}&amp;gt;
                Build with Matija
              &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;div style={{ marginLeft: &amp;quot;auto&amp;quot;, color: C.sky }}&amp;gt;
              &amp;lt;ArrowRight size={sq ? 46 : 62} strokeWidth={1.5} /&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/Pop&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/Scene&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The closing URL uses the &lt;code&gt;slug&lt;/code&gt; prop. Its square variant puts the path on a second line and wraps the heading deliberately. The portrait uses Remotion&amp;#39;s &lt;code&gt;Img&lt;/code&gt; component with &lt;code&gt;staticFile()&lt;/code&gt;, and the fixed display dimensions keep the surrounding layout stable.&lt;/p&gt;
&lt;p&gt;&lt;code&gt;Scene hold&lt;/code&gt; keeps the completed CTA at full opacity. Its small scale change settles during the first 48 frames, leaving time to read the URL before the video ends.&lt;/p&gt;
&lt;h2&gt;6. Assemble the timeline&lt;/h2&gt;
&lt;p&gt;Append the final exported component. This completes &lt;code&gt;src/Payload4Teaser.tsx&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;export const Payload4Teaser = ({ title, slug }: TeaserProps) =&amp;gt; (
  &amp;lt;AbsoluteFill
    style={{ fontFamily: &amp;quot;Inter, sans-serif&amp;quot;, color: C.text, background: C.bg }}
  &amp;gt;
    &amp;lt;FontGate /&amp;gt;
    &amp;lt;Background /&amp;gt;
    &amp;lt;Sequence from={0} durationInFrames={180} name=&amp;quot;Hook &amp;amp; title&amp;quot;&amp;gt;
      &amp;lt;Hook title={title} /&amp;gt;
    &amp;lt;/Sequence&amp;gt;
    &amp;lt;Sequence from={180} durationInFrames={240} name=&amp;quot;Access defaults&amp;quot;&amp;gt;
      &amp;lt;Access /&amp;gt;
    &amp;lt;/Sequence&amp;gt;
    &amp;lt;Sequence from={420} durationInFrames={120} name=&amp;quot;Relationship depth&amp;quot;&amp;gt;
      &amp;lt;Depth /&amp;gt;
    &amp;lt;/Sequence&amp;gt;
    &amp;lt;Sequence from={540} durationInFrames={180} name=&amp;quot;Frameworks &amp;amp; admin&amp;quot;&amp;gt;
      &amp;lt;Frameworks /&amp;gt;
    &amp;lt;/Sequence&amp;gt;
    &amp;lt;Sequence from={720} durationInFrames={180} name=&amp;quot;Read the guide&amp;quot;&amp;gt;
      &amp;lt;CTA slug={slug} /&amp;gt;
    &amp;lt;/Sequence&amp;gt;
    &amp;lt;Brand /&amp;gt;
  &amp;lt;/AbsoluteFill&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The order of the layers matters: font coordination first, then the background, then the timed scenes, then branding above them.&lt;/p&gt;
&lt;p&gt;Here is the full frame budget:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Scene&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;Start frame&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;Duration&lt;/th&gt;
&lt;th align=&quot;right&quot;&gt;Last frame&lt;/th&gt;
&lt;th&gt;Time interval&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Hook and title&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;0&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;180&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;179&lt;/td&gt;
&lt;td&gt;0–3 seconds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Access defaults&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;180&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;240&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;419&lt;/td&gt;
&lt;td&gt;3–7 seconds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Relationship depth&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;420&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;120&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;539&lt;/td&gt;
&lt;td&gt;7–9 seconds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Frameworks and admin&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;540&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;180&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;719&lt;/td&gt;
&lt;td&gt;9–12 seconds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Call to action&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;720&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;180&lt;/td&gt;
&lt;td align=&quot;right&quot;&gt;899&lt;/td&gt;
&lt;td&gt;12–15 seconds&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;A sequence&amp;#39;s &lt;code&gt;durationInFrames&lt;/code&gt; is a count. The first scene includes frames 0 through 179; frame 180 belongs to the next scene. These five intervals cover all 900 frames without a gap or overlap.&lt;/p&gt;
&lt;p&gt;Inside &lt;code&gt;&amp;lt;Sequence from={180}&amp;gt;&lt;/code&gt;, &lt;code&gt;useCurrentFrame()&lt;/code&gt; returns 0 at composition frame 180, 1 at frame 181, and so on. That is why the access cards can use small delays such as 12 and 42: they are relative to that scene. &lt;a href=&quot;https://www.remotion.dev/docs/sequence&quot;&gt;See sequence timing&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The background and brand are outside those sequences and keep the global frame number. Moving them inside a scene would reset their timing when the scene starts.&lt;/p&gt;
&lt;p&gt;A sequence also controls when its children appear. You do not need to hide every scene manually with conditions; the sequence supplies the visibility window and shifted timeline.&lt;/p&gt;
&lt;h2&gt;7. Preview the result in Studio&lt;/h2&gt;
&lt;p&gt;Check TypeScript and start Studio:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;npx tsc --noEmit
pnpm start
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Open &lt;code&gt;http://localhost:3100&lt;/code&gt; and select &lt;code&gt;Payload4Teaser&lt;/code&gt;. Play the composition, then switch to &lt;code&gt;Payload4Square&lt;/code&gt;. If the port is busy, use:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm exec remotion studio src/index.ts --port=3103
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Use representative frames to inspect each scene: 150, 340, 490, 660, and 850. Also inspect both sides of every boundary: 179/180, 419/420, 539/540, and 719/720. Check the opening frame 0 and the final frame 899.&lt;/p&gt;
&lt;p&gt;At each stop, check whether headings fit, connectors point to the intended nodes, and the persistent footer stays clear. Preview the square composition around social-feed display sizes as well as at full resolution. Large export dimensions do not guarantee readable text on a phone.&lt;/p&gt;
&lt;p&gt;You can save an individual frame for a closer look:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm exec remotion still src/index.ts Payload4Square out/check-square-access.png --frame=340
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Do not judge a composition only by one attractive poster. The frame before a scene change and the first frame after it reveal timing mistakes that a settled frame can hide.&lt;/p&gt;
&lt;h2&gt;8. Render MP4, WebM, and posters&lt;/h2&gt;
&lt;p&gt;The scripts in &lt;code&gt;package.json&lt;/code&gt; already specify the entrypoint, composition ID, and output filename. Run them from the example project:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm render:landscape
pnpm render:square
pnpm render:webm
pnpm poster:landscape
pnpm poster:square
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The first render may download Chrome Headless Shell. Let that finish before diagnosing a slow first export as an animation problem. &lt;a href=&quot;https://www.remotion.dev/docs/render&quot;&gt;See the rendering walkthrough&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The MP4 scripts use H.264, &lt;code&gt;yuv420p&lt;/code&gt;, CRF 18, and BT.709 color space. PNG frame capture avoids introducing JPEG artifacts before encoding around text and thin diagram strokes. &lt;code&gt;--concurrency=4&lt;/code&gt; is the reference setting; reduce it if your machine struggles with memory. The WebM script uses VP9 at a target bitrate of 6 Mbps. &lt;a href=&quot;https://www.remotion.dev/docs/cli/render&quot;&gt;See the CLI options&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Posters come from frame 150, 2.5 seconds into the composition, when the opening scene has settled. You can choose another frame by changing &lt;code&gt;--frame&lt;/code&gt; in the poster scripts.&lt;/p&gt;
&lt;p&gt;Expect these outputs:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Output&lt;/th&gt;
&lt;th&gt;Canvas&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;code&gt;out/payload-4-0-teaser.mp4&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;1920×1080&lt;/td&gt;
&lt;td&gt;Landscape H.264 video&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;out/payload-4-0-square.mp4&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;1080×1080&lt;/td&gt;
&lt;td&gt;Square H.264 video&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;out/payload-4-0-teaser.webm&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;1920×1080&lt;/td&gt;
&lt;td&gt;Landscape VP9 alternative&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;out/payload-4-0-poster.png&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;1920×1080&lt;/td&gt;
&lt;td&gt;Landscape poster&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;out/payload-4-0-square-poster.png&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;1080×1080&lt;/td&gt;
&lt;td&gt;Square poster&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Both video compositions are 15 seconds at 60 fps. This example has no audio track; silent playback is expected.&lt;/p&gt;
&lt;p&gt;Here is the square reference export for comparison:&lt;/p&gt;
&lt;video controls preload=&quot;metadata&quot; poster=&quot;/remotion-guide/payload-4-0-square-poster.png&quot; width=&quot;1080&quot; height=&quot;1080&quot;&gt;
  &lt;source src=&quot;/remotion-guide/payload-4-0-square.mp4&quot; type=&quot;video/mp4&quot; /&gt;
  Your browser cannot play this video. &lt;a href=&quot;/remotion-guide/payload-4-0-square.mp4&quot;&gt;Download the square MP4.&lt;/a&gt;
&lt;/video&gt;&lt;p&gt;If you have &lt;code&gt;ffprobe&lt;/code&gt; installed, inspect the actual encoded media rather than relying only on composition settings:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=codec_name,width,height,r_frame_rate,nb_read_frames,pix_fmt,color_space:format=duration -of json out/payload-4-0-teaser.mp4
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For the landscape MP4, expect H.264, 1920×1080, &lt;code&gt;60/1&lt;/code&gt; fps, 900 decoded frames, approximately 15 seconds, &lt;code&gt;yuv420p&lt;/code&gt;, and &lt;code&gt;bt709&lt;/code&gt;. Check the square file separately; it should report 1080×1080.&lt;/p&gt;
&lt;p&gt;Play the final files and seek into each scene. Studio confirms the React composition, while playback confirms the file you will actually share.&lt;/p&gt;
&lt;h2&gt;9. Adapt the example to your own content&lt;/h2&gt;
&lt;p&gt;Start by changing the title and slug in both compositions. The title controls the opening heading and subtitle; the slug controls the closing article path. Then change the scene content, logo, portrait, and brand labels.&lt;/p&gt;
&lt;p&gt;There are several deliberate fixed values to revisit:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Hook&lt;/code&gt; always renders a highlighted &lt;code&gt;4.0&lt;/code&gt;, and its tags refer to Payload&amp;#39;s ecosystem.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;AccessCard&lt;/code&gt;, &lt;code&gt;RelationshipRow&lt;/code&gt;, and &lt;code&gt;Frameworks&lt;/code&gt; contain example-specific diagrams and labels.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Brand&lt;/code&gt; contains fixed chapter boundaries and website text.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Background&lt;/code&gt; calculates progress against 900 frames.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;useSquare()&lt;/code&gt; recognizes a square canvas. A vertical 1080×1920 composition needs its own layout decisions.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Changing &lt;code&gt;defaultProps&lt;/code&gt; alone does not turn this into a general-purpose video generator. To make it reusable across articles, extract the scene content into typed props after you have a second real example and know what varies.&lt;/p&gt;
&lt;p&gt;If you change the duration, update the composition, sequence starts and lengths, &lt;code&gt;Scene&lt;/code&gt; durations, chapter thresholds, and progress denominator together. A duration change at only the root will either cut content short or leave extra time after the intended ending.&lt;/p&gt;
&lt;p&gt;Keep animated values derived from frames. If you add particles or randomly placed decorations, use Remotion&amp;#39;s seeded &lt;code&gt;random()&lt;/code&gt; rather than &lt;code&gt;Math.random()&lt;/code&gt; so the placement is repeatable. &lt;a href=&quot;https://www.remotion.dev/docs/random&quot;&gt;See deterministic randomness&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;10. Troubleshoot the common failures&lt;/h2&gt;
&lt;h3&gt;A component or import cannot be found&lt;/h3&gt;
&lt;p&gt;Make sure you copied every consecutive block into &lt;code&gt;src/Payload4Teaser.tsx&lt;/code&gt;, including the imports at the top and exported component at the bottom. The blocks are parts of one file. Copying only an individual scene will leave its helpers undefined.&lt;/p&gt;
&lt;p&gt;Run &lt;code&gt;npx tsc --noEmit&lt;/code&gt; from the example directory. If the error mentions &lt;code&gt;FontFace&lt;/code&gt; or &lt;code&gt;document.fonts&lt;/code&gt;, compare the TypeScript &lt;code&gt;lib&lt;/code&gt; array with the configuration above.&lt;/p&gt;
&lt;h3&gt;Utility classes have no effect&lt;/h3&gt;
&lt;p&gt;Check that the component imports &lt;code&gt;./style.css&lt;/code&gt;, that the stylesheet imports Tailwind, and that &lt;code&gt;remotion.config.ts&lt;/code&gt; calls &lt;code&gt;enableTailwind&lt;/code&gt;. Our layout mixes utility classes and inline styles; missing Tailwind can break flex layouts even while colors still appear correctly.&lt;/p&gt;
&lt;h3&gt;Fonts fail to load or the render times out&lt;/h3&gt;
&lt;p&gt;Check all five requested font filenames, their copied paths, and the spelling of &lt;code&gt;public/fonts&lt;/code&gt;. Use Studio&amp;#39;s browser console to look for failed asset requests. The font gate intentionally cancels on a loading error.&lt;/p&gt;
&lt;p&gt;A timeout can indicate work that never cleared its delay handle. Increasing the timeout does not repair a missing file or a stalled request. Trace the operation and make sure it either completes with &lt;code&gt;continueRender()&lt;/code&gt; or fails with &lt;code&gt;cancelRender()&lt;/code&gt;. &lt;a href=&quot;https://www.remotion.dev/docs/delay-render&quot;&gt;See render-delay troubleshooting&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Animation looks different after scrubbing&lt;/h3&gt;
&lt;p&gt;Look for CSS keyframes, transitions, timers, or values calculated from wall-clock time. A composition must display the intended result when you jump straight to a frame. Calculate motion from &lt;code&gt;useCurrentFrame()&lt;/code&gt; and keep your asset and input data stable.&lt;/p&gt;
&lt;h3&gt;Square content clips or collides with the footer&lt;/h3&gt;
&lt;p&gt;Inspect the entire scene&amp;#39;s height, including headings, margins, query text, and notes. The reference square layout stacks access cards, tightens their spacing, and moves detail into their headers. Smaller fonts alone will not fix every layout problem.&lt;/p&gt;
&lt;h3&gt;The final export is unreadable or fails&lt;/h3&gt;
&lt;p&gt;Check available disk space and try reducing render concurrency. Inspect the actual output with a media player and &lt;code&gt;ffprobe&lt;/code&gt;. A successful TypeScript check confirms types, not that the browser captured every frame correctly.&lt;/p&gt;
&lt;h2&gt;Where to go after this tutorial&lt;/h2&gt;
&lt;p&gt;You now have a concrete composition you can scrub, modify, and render. Try replacing the access comparison with a diagram from your own article while keeping the same timing and shared animation helpers.&lt;/p&gt;
&lt;p&gt;For a next project, the &lt;a href=&quot;https://www.remotion.dev/docs/player&quot;&gt;Remotion Player&lt;/a&gt; lets you embed a composition as an interactive preview in a React application. The &lt;a href=&quot;https://www.remotion.dev/docs/renderer&quot;&gt;Node rendering API&lt;/a&gt; and &lt;a href=&quot;https://www.remotion.dev/docs/lambda&quot;&gt;Lambda documentation&lt;/a&gt; cover automated exports when local rendering is no longer enough. Check the &lt;a href=&quot;https://www.remotion.dev/docs/license&quot;&gt;current licensing terms&lt;/a&gt; when planning how to use it in your organization.&lt;/p&gt;
&lt;p&gt;Build one clear scene, inspect its frames, and then extend the timeline. The same React composition skills carry through as the video grows.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/remotion-react-video-tutorial"/>
        </item>
        <item>
            <title><![CDATA[How to Add "Log In As User" Impersonation with Neon Auth in Next.js]]></title>
            <description><![CDATA[<p>While replacing the authentication provider on a multi-tenant client project from Stack Auth to Better Auth (hosted via Neon Auth), I needed to verify whether tenant views and edge-case permissions functioned correctly for specific users. In production or staging environments, administrators cannot and should not know customer passwords. Setting up &quot;log in as user&quot; impersonation is a standard operational requirement for multi-tenant SaaS applications: it allows support engineers and superadmins to view the application exactly as a customer sees it, diagnose bugs, and verify onboarding states without credential resets.</p>
<p>The impersonation API call itself worked on the first try. The trouble started right after: I was signed in as the customer on one page, and one click later the app was showing me my own superadmin account again. It took a look at the raw cookies in the browser to find out why, and the cause was a one-line mistake in how Next.js handles cookie expiry that no type checker or test would ever have caught.</p>
<p>This guide walks through the full implementation of user impersonation with Neon Auth (Better Auth under the hood) in Next.js, explains how the impersonation pattern works in principle, and covers the session cookie swapping and Next.js cookie bugs so you can ship impersonation without losing an afternoon to it.</p>
<h2>How user impersonation works in principle</h2>
<p>Before diving into service accounts and cookie mechanics, it helps to understand what user impersonation actually does at an architectural level.</p>
<p>In a normal authentication flow, a user proves their identity by providing credentials (a password, an OAuth grant, or an email OTP). The auth server verifies those credentials and issues a session token that binds incoming HTTP requests to that user&#39;s identity.</p>
<p>Impersonation bypasses password verification through an authorized administrative privilege grant:</p>
<ol>
<li><strong>Privileged Delegation:</strong> An authenticated superadmin triggers an impersonation request targeting a specific <code>userId</code>. Because plain users cannot impersonate others, this request must be authorized by an administrative identity (in Neon Auth, a service account carrying the Neon <code>admin</code> role).</li>
<li><strong>Session Minting with Provenance:</strong> The auth engine mints a valid session for the target user without requiring their password. Crucially, the auth engine records <em>provenance</em>—marking the session with metadata such as <code>impersonatedBy: adminUserId</code>. This audit trail proves that actions taken under this session originated from an administrator.</li>
<li><strong>Session Token Parking &amp; Swapping:</strong> In the browser, the superadmin&#39;s original session token is &quot;parked&quot; into a secure temporary storage cookie (e.g. <code>impersonator_token</code>), while the newly minted target user token takes over the primary session cookie (<code>session_token</code>). To the rest of the application, every standard auth check now resolves to the target user.</li>
<li><strong>Visual State &amp; Reversion Guardrails:</strong> The application inspects the session context. When <code>impersonatedBy</code> is present, it renders a persistent global warning banner (&quot;You are viewing as [Customer]&quot;) across all screens, disables irreversible or destructive account changes (like changing billing info or triggering welcome emails), and provides an instant &quot;Exit Impersonation&quot; action that revokes the temporary session and restores the parked superadmin token.</li>
</ol>
<h2>Why impersonation needs a service account</h2>
<p>Neon Auth exposes an <code>/admin/impersonate-user</code> endpoint, but it only answers to a signed-in session whose user has the Neon role <code>admin</code>. In my app the roles that matter (organisation admin, driver, superadmin) live in my own Prisma <code>User</code> table, and every Neon user keeps the plain <code>user</code> role. If I gave superadmins the Neon <code>admin</code> role, that would be a second, parallel permission system to keep in sync, so I did not.</p>
<p>Instead the server signs in as a dedicated service account that does have the Neon <code>admin</code> role, caches that account&#39;s session cookie in memory, and uses it for every admin call (the same pattern detailed in our <a href="/blog/neon-managed-better-auth-nextjs-vercel">Neon Managed Better Auth in Next.js on Vercel setup guide</a> and <a href="/blog/migrate-stack-auth-to-neon-better-auth">Stack Auth to Neon Auth migration</a>). The impersonation step is one of those calls. Everything else in this guide is about what to do with the result.</p>
<h2>Step 1: Ask Neon for an impersonated session</h2>
<p>The first piece is a small server-only function that asks Neon to create a session for a target user and hands back the session token. The subtle part is reading the response correctly, because Neon sends more than one <code>Set-Cookie</code> header.</p>
<pre><code class="language-typescript">// File: src/lib/auth/admin.ts
/**
 * Creates a Neon Auth session for `userId` (impersonated by the service
 * account) and returns its session token cookie value.
 */
export const impersonateAuthUser = async (userId: string): Promise&lt;string&gt; =&gt; {
  const { response } = await adminRequest(&quot;/admin/impersonate-user&quot;, {
    method: &quot;POST&quot;,
    body: { userId },
  });

  // The response first expires the caller&#39;s session cookie, then sets the new
  // one, so take the last non-empty session_token.
  const token = response.headers
    .getSetCookie()
    .map((header) =&gt; header.split(&quot;;&quot;)[0])
    .filter((cookie) =&gt; cookie.split(&quot;=&quot;)[0].endsWith(&quot;.session_token&quot;))
    .map((cookie) =&gt; cookie.split(&quot;=&quot;).slice(1).join(&quot;=&quot;))
    .findLast(Boolean);

  if (!token) {
    throw new AuthAdminError(&quot;Sistem za prijavo ni vrnil seje uporabnika.&quot;);
  }

  return token;
};
</code></pre>
<p><code>adminRequest</code> is the helper that attaches the service account&#39;s cached session cookie and retries once if that session has expired. The response to the impersonation call first expires the service account&#39;s own <code>session_token</code> (an empty value) and then sets the new one for the impersonated user. My first version took the first <code>session_token</code> it saw, which is the empty one, and the impersonation silently produced a blank session. Taking the last non-empty value fixes that.</p>
<p>With a token in hand, the next question is where it goes in the browser without destroying your own session.</p>
<h2>Step 2: Swap the cookies in a server action</h2>
<p>Impersonating means the browser must carry the target&#39;s session while you keep your own session safe somewhere, so you can come back. I park the superadmin&#39;s token in a separate cookie and put the impersonated token where the SDK expects to find it.</p>
<pre><code class="language-typescript">// File: src/lib/auth/impersonation.ts
// Mirrors the cookie names used by @neondatabase/auth (not exported by the SDK).
const SESSION_TOKEN_COOKIE = &quot;__Secure-neon-auth.session_token&quot;;
const SESSION_DATA_COOKIE = &quot;__Secure-neon-auth.local.session_data&quot;;
// Holds the superadmin&#39;s own session token while impersonating.
const IMPERSONATOR_COOKIE = &quot;__Secure-boneks.impersonator&quot;;

// Neon&#39;s default impersonation session lifetime.
const IMPERSONATION_MAX_AGE = 60 * 60;

const cookieOptions = {
  path: &quot;/&quot;,
  httpOnly: true,
  secure: true,
  sameSite: &quot;lax&quot;,
} as const;
</code></pre>
<p>The SDK does not export its cookie names, so I mirror them by hand. The impersonation lifetime matches Neon&#39;s default of one hour, which also caps how long a forgotten impersonation can stay open. Now the action that starts it:</p>
<pre><code class="language-typescript">// File: src/lib/auth/impersonation.ts
export async function startImpersonationAction(
  userId: string,
): Promise&lt;ActionState&lt;ImpersonationRedirect&gt;&gt; {
  const context = await requireAuthContext();

  if (!isSuperadmin(context) || context.impersonatedBy) {
    return createErrorState(&quot;Nimate dovoljenja za to dejanje.&quot;);
  }

  const target = await prisma.user.findFirst({
    where: { id: userId, deletedAt: null },
    select: {
      id: true,
      authUserId: true,
      email: true,
      role: true,
      status: true,
      organisationId: true,
    },
  });

  if (!target || !target.authUserId) {
    return createErrorState(&quot;Uporabnik ne obstaja.&quot;);
  }

  if (target.id === context.userId) {
    return createErrorState(&quot;Tega uporabnika ni mogoče prevzeti.&quot;);
  }

  if (target.status !== UserStatus.ACTIVE) {
    return createErrorState(&quot;Prevzamete lahko samo aktivne uporabnike.&quot;);
  }

  const cookieStore = await cookies();
  const ownToken = cookieStore.get(SESSION_TOKEN_COOKIE)?.value;

  if (!ownToken) {
    return createErrorState(&quot;Vaše seje ni bilo mogoče najti.&quot;);
  }

  let impersonatedToken: string;

  try {
    impersonatedToken = await impersonateAuthUser(target.authUserId);
  } catch (error) {
    console.error(&quot;[impersonation] Failed to start&quot;, error);
    return createErrorState(
      error instanceof AuthAdminError
        ? error.message
        : &quot;Prevzem uporabnika ni uspel.&quot;,
    );
  }

  cookieStore.set(IMPERSONATOR_COOKIE, ownToken, {
    ...cookieOptions,
    maxAge: IMPERSONATION_MAX_AGE,
  });
  cookieStore.set(SESSION_TOKEN_COOKIE, impersonatedToken, {
    ...cookieOptions,
    maxAge: IMPERSONATION_MAX_AGE,
  });
  expireCookie(cookieStore, SESSION_DATA_COOKIE);

  console.info(&quot;[impersonation] start&quot;, {
    superadminUserId: context.userId,
    targetUserId: target.id,
    targetEmail: target.email,
    targetRole: target.role,
    organisationId: target.organisationId,
  });

  return createSuccessState(&quot;update&quot;, &quot;Prevzem uporabnika je začel.&quot;, {
    redirectTo:
      target.role === UserRole.SUPERADMIN
        ? &quot;/superadmin&quot;
        : target.role === UserRole.DRIVER
          ? &quot;/vozniki&quot;
          : &quot;/admin&quot;,
  });
}
</code></pre>
<p>The checks at the top do the security work. Only a superadmin may start, and only when not already impersonating, so sessions cannot be chained. The target must exist in your own table, be active, and not be yourself. Impersonating another superadmin is allowed because it grants nothing you do not already have. The write happens only after Neon has issued the new token, so a failed impersonation leaves your session untouched. The last call, <code>expireCookie</code>, removes the SDK&#39;s cached session data. That line looks harmless, and it is where the bug lives, so I will come back to it in Step 6.</p>
<p>Notice that the action returns a URL instead of calling <code>redirect()</code>. That is deliberate and also explained in Step 6. Before that, the rest of the app needs to know an impersonation is in progress.</p>
<h2>Step 3: Detect an impersonated session</h2>
<p>Neon marks an impersonated session with an <code>impersonatedBy</code> field holding the id of the admin behind it. I read it in the same place the app already reads the current user and pass it into the auth context, so every layout and server action can see it.</p>
<pre><code class="language-typescript">// File: src/lib/auth/session.ts
const session = data.session as { impersonatedBy?: string | null } | undefined;

return {
  id: user.id,
  email: user.email,
  name: user.name ?? null,
  impersonatedBy: session?.impersonatedBy ?? null,
};
</code></pre>
<p>One more place needs to respect it. My app activates invited users on their first login, which is a state change. An impersonating admin visiting an invite-pending account must not trigger that, so the activation is skipped when <code>impersonatedBy</code> is set:</p>
<pre><code class="language-typescript">// File: src/lib/auth/session.ts
// Impersonation must not change the target&#39;s state.
if (
  prismaUser.status === UserStatus.INVITE_PENDING &amp;&amp;
  !authUser.impersonatedBy
) {
  // activate the user
}
</code></pre>
<p>With the flag available everywhere, the user interface can make the situation impossible to miss.</p>
<h2>Step 4: Show a banner and a way out</h2>
<p>While impersonating, every page needs a persistent notice and a button to end it. I render a banner from a server component that returns nothing unless the session is impersonated, and mount it in each layout through the shell&#39;s <code>banner</code> slot.</p>
<pre><code class="language-typescript">// File: src/components/impersonation/impersonation-banner.tsx
export async function ImpersonationBanner({ context }: { context: AuthContext }) {
  if (!context.impersonatedBy) {
    return null;
  }

  const user = await prisma.user.findUnique({
    where: { id: context.userId },
    select: { email: true, firstName: true, lastName: true },
  });
  const name =
    [user?.firstName, user?.lastName].filter(Boolean).join(&quot; &quot;) || user?.email;

  return (
    &lt;div className=&quot;flex flex-wrap items-center justify-between gap-2 border-b border-amber-300 bg-amber-100 px-4 py-2 text-sm text-amber-950 md:px-6&quot;&gt;
      &lt;p className=&quot;flex items-center gap-2&quot;&gt;
        &lt;UserRound className=&quot;h-4 w-4 shrink-0&quot; /&gt;
        &lt;span&gt;
          Prijavljeni ste kot &lt;strong&gt;{name}&lt;/strong&gt;
          {user?.email &amp;&amp; name !== user.email ? ` (${user.email})` : null}
        &lt;/span&gt;
      &lt;/p&gt;
      &lt;StopImpersonationButton /&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The banner must be mounted in every layout an impersonated user can reach. I mounted it in the admin and driver layouts first and forgot the superadmin layout, which mattered as soon as I allowed impersonating other superadmins: the session looked normal and had no way out. The button that ends the session is a small client component.</p>
<pre><code class="language-typescript">// File: src/components/impersonation/stop-impersonation-button.tsx
const handleStop = () =&gt; {
  startTransition(async () =&gt; {
    const result = await stopImpersonationAction();

    if (result.success &amp;&amp; result.data) {
      // Full page load so no page cached for the impersonated session survives.
      window.location.assign(result.data.redirectTo);
      return;
    }

    toast.error(result.message ?? &quot;Končanje prevzema ni uspelo.&quot;);
  });
};
</code></pre>
<p>The button calls the stop action, which is the mirror image of the start action.</p>
<h2>Step 5: Stop impersonating and restore your session</h2>
<p>Stopping has three jobs: revoke the impersonated session on Neon, put the superadmin&#39;s own token back, and clear the impersonation cookies.</p>
<pre><code class="language-typescript">// File: src/lib/auth/impersonation.ts
export async function stopImpersonationAction(): Promise&lt;
  ActionState&lt;ImpersonationRedirect&gt;
&gt; {
  const cookieStore = await cookies();
  const ownToken = cookieStore.get(IMPERSONATOR_COOKIE)?.value;

  if (!ownToken) {
    return createErrorState(&quot;Ne prevzemate nobenega uporabnika.&quot;);
  }

  const context = await getCurrentAuthContext().catch(() =&gt; null);
  const impersonatedToken = cookieStore.get(SESSION_TOKEN_COOKIE)?.value;

  // Revoke the impersonated session (best-effort).
  if (impersonatedToken &amp;&amp; context?.impersonatedBy) {
    await fetch(`${requireEnv(&quot;NEON_AUTH_BASE_URL&quot;)}/sign-out`, {
      method: &quot;POST&quot;,
      headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
        Cookie: `${SESSION_TOKEN_COOKIE}=${impersonatedToken}`,
        Origin: new URL(requireEnv(&quot;NEXT_PUBLIC_ADDRESS&quot;)).origin,
      },
      body: &quot;{}&quot;,
      cache: &quot;no-store&quot;,
    }).catch((error: unknown) =&gt; {
      console.error(&quot;[impersonation] Failed to revoke session&quot;, error);
    });
  }

  cookieStore.set(SESSION_TOKEN_COOKIE, ownToken, {
    ...cookieOptions,
    maxAge: SESSION_MAX_AGE,
  });
  expireCookie(cookieStore, SESSION_DATA_COOKIE);
  expireCookie(cookieStore, IMPERSONATOR_COOKIE);

  console.info(&quot;[impersonation] stop&quot;, {
    impersonatedUserId: context?.userId ?? null,
    organisationId: context?.organisationId ?? null,
  });

  return createSuccessState(&quot;update&quot;, &quot;Prevzem uporabnika je končan.&quot;, {
    redirectTo: context
      ? `/superadmin/organisations/${context.organisationId}`
      : &quot;/superadmin&quot;,
  });
}
</code></pre>
<p>If there is no impersonator cookie the action returns an error without touching anything, and that behaviour is useful. It lets the ordinary sign-out button call the stop action first and fall back to a real sign-out, so pressing &quot;Odjava&quot; while impersonating ends the impersonation instead of logging the superadmin out entirely:</p>
<pre><code class="language-typescript">// File: src/lib/auth/sign-out.ts
export const signOutOrStopImpersonation = async (): Promise&lt;boolean&gt; =&gt; {
  const stopResult = await stopImpersonationAction().catch(() =&gt; null);

  if (stopResult?.success &amp;&amp; stopResult.data) {
    window.location.assign(stopResult.data.redirectTo);
    return false;
  }

  await authClient.signOut();
  return true;
};
</code></pre>
<p>This is the complete flow, and on paper it is done. In practice it had one bug left, and both the start and stop actions contain the line responsible.</p>
<h2>Step 6: The bug that resets you to your own account</h2>
<p>After starting an impersonation I landed on the impersonated user&#39;s dashboard with the banner showing. Then I clicked a link to another section, and the app was showing my own superadmin account. Reloading did not help. The banner was correct on one page and wrong on the next.</p>
<p>My first theory was the client router cache, because the sidebar prefetches links before you switch accounts. That is a real problem in general, and it is why the actions return a URL and the callers use <code>window.location.assign</code> instead of a server-side <code>redirect()</code>: a full page load discards everything the router cached for the previous session. It was not the cause here, though. The behaviour survived the change.</p>
<p>The answer was in the browser&#39;s cookie list. Next to the impersonated <code>session_token</code> there was a <code>__Secure-neon-auth.local.session_data</code> cookie, and decoding its JWT payload showed my own user with <code>impersonatedBy: null</code>. Neon Auth&#39;s server SDK caches the session in that signed cookie, and when it is valid and a session token is present, <code>getSession</code> returns the cached payload without asking Neon anything. So any request that carried the stale cache resolved to my own account, even though the token next to it belonged to someone else.</p>
<p>My code was already trying to delete that cache. The problem is how it deleted it:</p>
<pre><code class="language-typescript">// File: src/lib/auth/impersonation.ts (before)
cookieStore.delete(SESSION_DATA_COOKIE);
</code></pre>
<p><code>cookieStore.delete()</code> sends a <code>Set-Cookie</code> header with an expiry in the past, but it does not include the <code>Secure</code> attribute. Browsers refuse to modify a cookie whose name starts with <code>__Secure-</code> unless the header that does it is also marked <code>Secure</code>. The delete was therefore ignored without any error, and the cache stayed. The fix is to expire the cookie with a normal <code>set</code> call that carries the same attributes it was created with:</p>
<pre><code class="language-typescript">// File: src/lib/auth/impersonation.ts
// `cookieStore.delete()` omits `Secure`, which browsers reject for `__Secure-`
// cookies, so the cookie would survive. Expire it explicitly instead.
const expireCookie = (
  cookieStore: Awaited&lt;ReturnType&lt;typeof cookies&gt;&gt;,
  name: string,
) =&gt; cookieStore.set(name, &quot;&quot;, { ...cookieOptions, maxAge: 0 });
</code></pre>
<p>I use this helper for the session cache on both start and stop, and for the impersonator cookie on stop. The stop path had the same flaw in reverse: without it, ending an impersonation could leave the impersonated user&#39;s cached session behind and sign the superadmin in as the wrong person.</p>
<p>The lesson is broader than this app. Any cookie with a <code>__Secure-</code> or <code>__Host-</code> prefix has to be written and cleared with <code>Secure</code> set, and Next.js <code>delete()</code> will not do that for you.</p>
<h2>Conclusion</h2>
<p>I set out to add impersonation to a Next.js app on Neon Auth and hit an odd failure where the app flipped back to my own account. The implementation is a service account that asks Neon for an impersonated session, a server action that parks your own token in a separate cookie and installs the impersonated one, an <code>impersonatedBy</code> flag that drives a banner in every layout, and a stop action that restores your session. The bug that cost me the most time came from the SDK&#39;s cached session cookie surviving a <code>cookieStore.delete()</code> that browsers ignore for <code>__Secure-</code> cookies, and it is fixed by expiring such cookies with <code>Secure</code> and <code>maxAge: 0</code>.</p>
<p>You can now build a safe &quot;log in as user&quot; feature on Neon Auth and avoid the stale-session trap. Let me know in the comments if you have questions, and subscribe for more practical development guides.</p>
<p>Thanks,
Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/neon-auth-nextjs-user-impersonation</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/neon-auth-nextjs-user-impersonation</guid>
            <category><![CDATA[Next.js]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 21:30:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;While replacing the authentication provider on a multi-tenant client project from Stack Auth to Better Auth (hosted via Neon Auth), I needed to verify whether tenant views and edge-case permissions functioned correctly for specific users. In production or staging environments, administrators cannot and should not know customer passwords. Setting up &amp;quot;log in as user&amp;quot; impersonation is a standard operational requirement for multi-tenant SaaS applications: it allows support engineers and superadmins to view the application exactly as a customer sees it, diagnose bugs, and verify onboarding states without credential resets.&lt;/p&gt;
&lt;p&gt;The impersonation API call itself worked on the first try. The trouble started right after: I was signed in as the customer on one page, and one click later the app was showing me my own superadmin account again. It took a look at the raw cookies in the browser to find out why, and the cause was a one-line mistake in how Next.js handles cookie expiry that no type checker or test would ever have caught.&lt;/p&gt;
&lt;p&gt;This guide walks through the full implementation of user impersonation with Neon Auth (Better Auth under the hood) in Next.js, explains how the impersonation pattern works in principle, and covers the session cookie swapping and Next.js cookie bugs so you can ship impersonation without losing an afternoon to it.&lt;/p&gt;
&lt;h2&gt;How user impersonation works in principle&lt;/h2&gt;
&lt;p&gt;Before diving into service accounts and cookie mechanics, it helps to understand what user impersonation actually does at an architectural level.&lt;/p&gt;
&lt;p&gt;In a normal authentication flow, a user proves their identity by providing credentials (a password, an OAuth grant, or an email OTP). The auth server verifies those credentials and issues a session token that binds incoming HTTP requests to that user&amp;#39;s identity.&lt;/p&gt;
&lt;p&gt;Impersonation bypasses password verification through an authorized administrative privilege grant:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Privileged Delegation:&lt;/strong&gt; An authenticated superadmin triggers an impersonation request targeting a specific &lt;code&gt;userId&lt;/code&gt;. Because plain users cannot impersonate others, this request must be authorized by an administrative identity (in Neon Auth, a service account carrying the Neon &lt;code&gt;admin&lt;/code&gt; role).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Session Minting with Provenance:&lt;/strong&gt; The auth engine mints a valid session for the target user without requiring their password. Crucially, the auth engine records &lt;em&gt;provenance&lt;/em&gt;—marking the session with metadata such as &lt;code&gt;impersonatedBy: adminUserId&lt;/code&gt;. This audit trail proves that actions taken under this session originated from an administrator.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Session Token Parking &amp;amp; Swapping:&lt;/strong&gt; In the browser, the superadmin&amp;#39;s original session token is &amp;quot;parked&amp;quot; into a secure temporary storage cookie (e.g. &lt;code&gt;impersonator_token&lt;/code&gt;), while the newly minted target user token takes over the primary session cookie (&lt;code&gt;session_token&lt;/code&gt;). To the rest of the application, every standard auth check now resolves to the target user.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visual State &amp;amp; Reversion Guardrails:&lt;/strong&gt; The application inspects the session context. When &lt;code&gt;impersonatedBy&lt;/code&gt; is present, it renders a persistent global warning banner (&amp;quot;You are viewing as [Customer]&amp;quot;) across all screens, disables irreversible or destructive account changes (like changing billing info or triggering welcome emails), and provides an instant &amp;quot;Exit Impersonation&amp;quot; action that revokes the temporary session and restores the parked superadmin token.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Why impersonation needs a service account&lt;/h2&gt;
&lt;p&gt;Neon Auth exposes an &lt;code&gt;/admin/impersonate-user&lt;/code&gt; endpoint, but it only answers to a signed-in session whose user has the Neon role &lt;code&gt;admin&lt;/code&gt;. In my app the roles that matter (organisation admin, driver, superadmin) live in my own Prisma &lt;code&gt;User&lt;/code&gt; table, and every Neon user keeps the plain &lt;code&gt;user&lt;/code&gt; role. If I gave superadmins the Neon &lt;code&gt;admin&lt;/code&gt; role, that would be a second, parallel permission system to keep in sync, so I did not.&lt;/p&gt;
&lt;p&gt;Instead the server signs in as a dedicated service account that does have the Neon &lt;code&gt;admin&lt;/code&gt; role, caches that account&amp;#39;s session cookie in memory, and uses it for every admin call (the same pattern detailed in our &lt;a href=&quot;/blog/neon-managed-better-auth-nextjs-vercel&quot;&gt;Neon Managed Better Auth in Next.js on Vercel setup guide&lt;/a&gt; and &lt;a href=&quot;/blog/migrate-stack-auth-to-neon-better-auth&quot;&gt;Stack Auth to Neon Auth migration&lt;/a&gt;). The impersonation step is one of those calls. Everything else in this guide is about what to do with the result.&lt;/p&gt;
&lt;h2&gt;Step 1: Ask Neon for an impersonated session&lt;/h2&gt;
&lt;p&gt;The first piece is a small server-only function that asks Neon to create a session for a target user and hands back the session token. The subtle part is reading the response correctly, because Neon sends more than one &lt;code&gt;Set-Cookie&lt;/code&gt; header.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/admin.ts
/**
 * Creates a Neon Auth session for `userId` (impersonated by the service
 * account) and returns its session token cookie value.
 */
export const impersonateAuthUser = async (userId: string): Promise&amp;lt;string&amp;gt; =&amp;gt; {
  const { response } = await adminRequest(&amp;quot;/admin/impersonate-user&amp;quot;, {
    method: &amp;quot;POST&amp;quot;,
    body: { userId },
  });

  // The response first expires the caller&amp;#39;s session cookie, then sets the new
  // one, so take the last non-empty session_token.
  const token = response.headers
    .getSetCookie()
    .map((header) =&amp;gt; header.split(&amp;quot;;&amp;quot;)[0])
    .filter((cookie) =&amp;gt; cookie.split(&amp;quot;=&amp;quot;)[0].endsWith(&amp;quot;.session_token&amp;quot;))
    .map((cookie) =&amp;gt; cookie.split(&amp;quot;=&amp;quot;).slice(1).join(&amp;quot;=&amp;quot;))
    .findLast(Boolean);

  if (!token) {
    throw new AuthAdminError(&amp;quot;Sistem za prijavo ni vrnil seje uporabnika.&amp;quot;);
  }

  return token;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;adminRequest&lt;/code&gt; is the helper that attaches the service account&amp;#39;s cached session cookie and retries once if that session has expired. The response to the impersonation call first expires the service account&amp;#39;s own &lt;code&gt;session_token&lt;/code&gt; (an empty value) and then sets the new one for the impersonated user. My first version took the first &lt;code&gt;session_token&lt;/code&gt; it saw, which is the empty one, and the impersonation silently produced a blank session. Taking the last non-empty value fixes that.&lt;/p&gt;
&lt;p&gt;With a token in hand, the next question is where it goes in the browser without destroying your own session.&lt;/p&gt;
&lt;h2&gt;Step 2: Swap the cookies in a server action&lt;/h2&gt;
&lt;p&gt;Impersonating means the browser must carry the target&amp;#39;s session while you keep your own session safe somewhere, so you can come back. I park the superadmin&amp;#39;s token in a separate cookie and put the impersonated token where the SDK expects to find it.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/impersonation.ts
// Mirrors the cookie names used by @neondatabase/auth (not exported by the SDK).
const SESSION_TOKEN_COOKIE = &amp;quot;__Secure-neon-auth.session_token&amp;quot;;
const SESSION_DATA_COOKIE = &amp;quot;__Secure-neon-auth.local.session_data&amp;quot;;
// Holds the superadmin&amp;#39;s own session token while impersonating.
const IMPERSONATOR_COOKIE = &amp;quot;__Secure-boneks.impersonator&amp;quot;;

// Neon&amp;#39;s default impersonation session lifetime.
const IMPERSONATION_MAX_AGE = 60 * 60;

const cookieOptions = {
  path: &amp;quot;/&amp;quot;,
  httpOnly: true,
  secure: true,
  sameSite: &amp;quot;lax&amp;quot;,
} as const;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The SDK does not export its cookie names, so I mirror them by hand. The impersonation lifetime matches Neon&amp;#39;s default of one hour, which also caps how long a forgotten impersonation can stay open. Now the action that starts it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/impersonation.ts
export async function startImpersonationAction(
  userId: string,
): Promise&amp;lt;ActionState&amp;lt;ImpersonationRedirect&amp;gt;&amp;gt; {
  const context = await requireAuthContext();

  if (!isSuperadmin(context) || context.impersonatedBy) {
    return createErrorState(&amp;quot;Nimate dovoljenja za to dejanje.&amp;quot;);
  }

  const target = await prisma.user.findFirst({
    where: { id: userId, deletedAt: null },
    select: {
      id: true,
      authUserId: true,
      email: true,
      role: true,
      status: true,
      organisationId: true,
    },
  });

  if (!target || !target.authUserId) {
    return createErrorState(&amp;quot;Uporabnik ne obstaja.&amp;quot;);
  }

  if (target.id === context.userId) {
    return createErrorState(&amp;quot;Tega uporabnika ni mogoče prevzeti.&amp;quot;);
  }

  if (target.status !== UserStatus.ACTIVE) {
    return createErrorState(&amp;quot;Prevzamete lahko samo aktivne uporabnike.&amp;quot;);
  }

  const cookieStore = await cookies();
  const ownToken = cookieStore.get(SESSION_TOKEN_COOKIE)?.value;

  if (!ownToken) {
    return createErrorState(&amp;quot;Vaše seje ni bilo mogoče najti.&amp;quot;);
  }

  let impersonatedToken: string;

  try {
    impersonatedToken = await impersonateAuthUser(target.authUserId);
  } catch (error) {
    console.error(&amp;quot;[impersonation] Failed to start&amp;quot;, error);
    return createErrorState(
      error instanceof AuthAdminError
        ? error.message
        : &amp;quot;Prevzem uporabnika ni uspel.&amp;quot;,
    );
  }

  cookieStore.set(IMPERSONATOR_COOKIE, ownToken, {
    ...cookieOptions,
    maxAge: IMPERSONATION_MAX_AGE,
  });
  cookieStore.set(SESSION_TOKEN_COOKIE, impersonatedToken, {
    ...cookieOptions,
    maxAge: IMPERSONATION_MAX_AGE,
  });
  expireCookie(cookieStore, SESSION_DATA_COOKIE);

  console.info(&amp;quot;[impersonation] start&amp;quot;, {
    superadminUserId: context.userId,
    targetUserId: target.id,
    targetEmail: target.email,
    targetRole: target.role,
    organisationId: target.organisationId,
  });

  return createSuccessState(&amp;quot;update&amp;quot;, &amp;quot;Prevzem uporabnika je začel.&amp;quot;, {
    redirectTo:
      target.role === UserRole.SUPERADMIN
        ? &amp;quot;/superadmin&amp;quot;
        : target.role === UserRole.DRIVER
          ? &amp;quot;/vozniki&amp;quot;
          : &amp;quot;/admin&amp;quot;,
  });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The checks at the top do the security work. Only a superadmin may start, and only when not already impersonating, so sessions cannot be chained. The target must exist in your own table, be active, and not be yourself. Impersonating another superadmin is allowed because it grants nothing you do not already have. The write happens only after Neon has issued the new token, so a failed impersonation leaves your session untouched. The last call, &lt;code&gt;expireCookie&lt;/code&gt;, removes the SDK&amp;#39;s cached session data. That line looks harmless, and it is where the bug lives, so I will come back to it in Step 6.&lt;/p&gt;
&lt;p&gt;Notice that the action returns a URL instead of calling &lt;code&gt;redirect()&lt;/code&gt;. That is deliberate and also explained in Step 6. Before that, the rest of the app needs to know an impersonation is in progress.&lt;/p&gt;
&lt;h2&gt;Step 3: Detect an impersonated session&lt;/h2&gt;
&lt;p&gt;Neon marks an impersonated session with an &lt;code&gt;impersonatedBy&lt;/code&gt; field holding the id of the admin behind it. I read it in the same place the app already reads the current user and pass it into the auth context, so every layout and server action can see it.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/session.ts
const session = data.session as { impersonatedBy?: string | null } | undefined;

return {
  id: user.id,
  email: user.email,
  name: user.name ?? null,
  impersonatedBy: session?.impersonatedBy ?? null,
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;One more place needs to respect it. My app activates invited users on their first login, which is a state change. An impersonating admin visiting an invite-pending account must not trigger that, so the activation is skipped when &lt;code&gt;impersonatedBy&lt;/code&gt; is set:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/session.ts
// Impersonation must not change the target&amp;#39;s state.
if (
  prismaUser.status === UserStatus.INVITE_PENDING &amp;amp;&amp;amp;
  !authUser.impersonatedBy
) {
  // activate the user
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With the flag available everywhere, the user interface can make the situation impossible to miss.&lt;/p&gt;
&lt;h2&gt;Step 4: Show a banner and a way out&lt;/h2&gt;
&lt;p&gt;While impersonating, every page needs a persistent notice and a button to end it. I render a banner from a server component that returns nothing unless the session is impersonated, and mount it in each layout through the shell&amp;#39;s &lt;code&gt;banner&lt;/code&gt; slot.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/impersonation/impersonation-banner.tsx
export async function ImpersonationBanner({ context }: { context: AuthContext }) {
  if (!context.impersonatedBy) {
    return null;
  }

  const user = await prisma.user.findUnique({
    where: { id: context.userId },
    select: { email: true, firstName: true, lastName: true },
  });
  const name =
    [user?.firstName, user?.lastName].filter(Boolean).join(&amp;quot; &amp;quot;) || user?.email;

  return (
    &amp;lt;div className=&amp;quot;flex flex-wrap items-center justify-between gap-2 border-b border-amber-300 bg-amber-100 px-4 py-2 text-sm text-amber-950 md:px-6&amp;quot;&amp;gt;
      &amp;lt;p className=&amp;quot;flex items-center gap-2&amp;quot;&amp;gt;
        &amp;lt;UserRound className=&amp;quot;h-4 w-4 shrink-0&amp;quot; /&amp;gt;
        &amp;lt;span&amp;gt;
          Prijavljeni ste kot &amp;lt;strong&amp;gt;{name}&amp;lt;/strong&amp;gt;
          {user?.email &amp;amp;&amp;amp; name !== user.email ? ` (${user.email})` : null}
        &amp;lt;/span&amp;gt;
      &amp;lt;/p&amp;gt;
      &amp;lt;StopImpersonationButton /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The banner must be mounted in every layout an impersonated user can reach. I mounted it in the admin and driver layouts first and forgot the superadmin layout, which mattered as soon as I allowed impersonating other superadmins: the session looked normal and had no way out. The button that ends the session is a small client component.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/impersonation/stop-impersonation-button.tsx
const handleStop = () =&amp;gt; {
  startTransition(async () =&amp;gt; {
    const result = await stopImpersonationAction();

    if (result.success &amp;amp;&amp;amp; result.data) {
      // Full page load so no page cached for the impersonated session survives.
      window.location.assign(result.data.redirectTo);
      return;
    }

    toast.error(result.message ?? &amp;quot;Končanje prevzema ni uspelo.&amp;quot;);
  });
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The button calls the stop action, which is the mirror image of the start action.&lt;/p&gt;
&lt;h2&gt;Step 5: Stop impersonating and restore your session&lt;/h2&gt;
&lt;p&gt;Stopping has three jobs: revoke the impersonated session on Neon, put the superadmin&amp;#39;s own token back, and clear the impersonation cookies.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/impersonation.ts
export async function stopImpersonationAction(): Promise&amp;lt;
  ActionState&amp;lt;ImpersonationRedirect&amp;gt;
&amp;gt; {
  const cookieStore = await cookies();
  const ownToken = cookieStore.get(IMPERSONATOR_COOKIE)?.value;

  if (!ownToken) {
    return createErrorState(&amp;quot;Ne prevzemate nobenega uporabnika.&amp;quot;);
  }

  const context = await getCurrentAuthContext().catch(() =&amp;gt; null);
  const impersonatedToken = cookieStore.get(SESSION_TOKEN_COOKIE)?.value;

  // Revoke the impersonated session (best-effort).
  if (impersonatedToken &amp;amp;&amp;amp; context?.impersonatedBy) {
    await fetch(`${requireEnv(&amp;quot;NEON_AUTH_BASE_URL&amp;quot;)}/sign-out`, {
      method: &amp;quot;POST&amp;quot;,
      headers: {
        &amp;quot;Content-Type&amp;quot;: &amp;quot;application/json&amp;quot;,
        Cookie: `${SESSION_TOKEN_COOKIE}=${impersonatedToken}`,
        Origin: new URL(requireEnv(&amp;quot;NEXT_PUBLIC_ADDRESS&amp;quot;)).origin,
      },
      body: &amp;quot;{}&amp;quot;,
      cache: &amp;quot;no-store&amp;quot;,
    }).catch((error: unknown) =&amp;gt; {
      console.error(&amp;quot;[impersonation] Failed to revoke session&amp;quot;, error);
    });
  }

  cookieStore.set(SESSION_TOKEN_COOKIE, ownToken, {
    ...cookieOptions,
    maxAge: SESSION_MAX_AGE,
  });
  expireCookie(cookieStore, SESSION_DATA_COOKIE);
  expireCookie(cookieStore, IMPERSONATOR_COOKIE);

  console.info(&amp;quot;[impersonation] stop&amp;quot;, {
    impersonatedUserId: context?.userId ?? null,
    organisationId: context?.organisationId ?? null,
  });

  return createSuccessState(&amp;quot;update&amp;quot;, &amp;quot;Prevzem uporabnika je končan.&amp;quot;, {
    redirectTo: context
      ? `/superadmin/organisations/${context.organisationId}`
      : &amp;quot;/superadmin&amp;quot;,
  });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If there is no impersonator cookie the action returns an error without touching anything, and that behaviour is useful. It lets the ordinary sign-out button call the stop action first and fall back to a real sign-out, so pressing &amp;quot;Odjava&amp;quot; while impersonating ends the impersonation instead of logging the superadmin out entirely:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/sign-out.ts
export const signOutOrStopImpersonation = async (): Promise&amp;lt;boolean&amp;gt; =&amp;gt; {
  const stopResult = await stopImpersonationAction().catch(() =&amp;gt; null);

  if (stopResult?.success &amp;amp;&amp;amp; stopResult.data) {
    window.location.assign(stopResult.data.redirectTo);
    return false;
  }

  await authClient.signOut();
  return true;
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is the complete flow, and on paper it is done. In practice it had one bug left, and both the start and stop actions contain the line responsible.&lt;/p&gt;
&lt;h2&gt;Step 6: The bug that resets you to your own account&lt;/h2&gt;
&lt;p&gt;After starting an impersonation I landed on the impersonated user&amp;#39;s dashboard with the banner showing. Then I clicked a link to another section, and the app was showing my own superadmin account. Reloading did not help. The banner was correct on one page and wrong on the next.&lt;/p&gt;
&lt;p&gt;My first theory was the client router cache, because the sidebar prefetches links before you switch accounts. That is a real problem in general, and it is why the actions return a URL and the callers use &lt;code&gt;window.location.assign&lt;/code&gt; instead of a server-side &lt;code&gt;redirect()&lt;/code&gt;: a full page load discards everything the router cached for the previous session. It was not the cause here, though. The behaviour survived the change.&lt;/p&gt;
&lt;p&gt;The answer was in the browser&amp;#39;s cookie list. Next to the impersonated &lt;code&gt;session_token&lt;/code&gt; there was a &lt;code&gt;__Secure-neon-auth.local.session_data&lt;/code&gt; cookie, and decoding its JWT payload showed my own user with &lt;code&gt;impersonatedBy: null&lt;/code&gt;. Neon Auth&amp;#39;s server SDK caches the session in that signed cookie, and when it is valid and a session token is present, &lt;code&gt;getSession&lt;/code&gt; returns the cached payload without asking Neon anything. So any request that carried the stale cache resolved to my own account, even though the token next to it belonged to someone else.&lt;/p&gt;
&lt;p&gt;My code was already trying to delete that cache. The problem is how it deleted it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/impersonation.ts (before)
cookieStore.delete(SESSION_DATA_COOKIE);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;cookieStore.delete()&lt;/code&gt; sends a &lt;code&gt;Set-Cookie&lt;/code&gt; header with an expiry in the past, but it does not include the &lt;code&gt;Secure&lt;/code&gt; attribute. Browsers refuse to modify a cookie whose name starts with &lt;code&gt;__Secure-&lt;/code&gt; unless the header that does it is also marked &lt;code&gt;Secure&lt;/code&gt;. The delete was therefore ignored without any error, and the cache stayed. The fix is to expire the cookie with a normal &lt;code&gt;set&lt;/code&gt; call that carries the same attributes it was created with:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/lib/auth/impersonation.ts
// `cookieStore.delete()` omits `Secure`, which browsers reject for `__Secure-`
// cookies, so the cookie would survive. Expire it explicitly instead.
const expireCookie = (
  cookieStore: Awaited&amp;lt;ReturnType&amp;lt;typeof cookies&amp;gt;&amp;gt;,
  name: string,
) =&amp;gt; cookieStore.set(name, &amp;quot;&amp;quot;, { ...cookieOptions, maxAge: 0 });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I use this helper for the session cache on both start and stop, and for the impersonator cookie on stop. The stop path had the same flaw in reverse: without it, ending an impersonation could leave the impersonated user&amp;#39;s cached session behind and sign the superadmin in as the wrong person.&lt;/p&gt;
&lt;p&gt;The lesson is broader than this app. Any cookie with a &lt;code&gt;__Secure-&lt;/code&gt; or &lt;code&gt;__Host-&lt;/code&gt; prefix has to be written and cleared with &lt;code&gt;Secure&lt;/code&gt; set, and Next.js &lt;code&gt;delete()&lt;/code&gt; will not do that for you.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;I set out to add impersonation to a Next.js app on Neon Auth and hit an odd failure where the app flipped back to my own account. The implementation is a service account that asks Neon for an impersonated session, a server action that parks your own token in a separate cookie and installs the impersonated one, an &lt;code&gt;impersonatedBy&lt;/code&gt; flag that drives a banner in every layout, and a stop action that restores your session. The bug that cost me the most time came from the SDK&amp;#39;s cached session cookie surviving a &lt;code&gt;cookieStore.delete()&lt;/code&gt; that browsers ignore for &lt;code&gt;__Secure-&lt;/code&gt; cookies, and it is fixed by expiring such cookies with &lt;code&gt;Secure&lt;/code&gt; and &lt;code&gt;maxAge: 0&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;You can now build a safe &amp;quot;log in as user&amp;quot; feature on Neon Auth and avoid the stale-session trap. Let me know in the comments if you have questions, and subscribe for more practical development guides.&lt;/p&gt;
&lt;p&gt;Thanks,
Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/neon-auth-nextjs-user-impersonation"/>
        </item>
        <item>
            <title><![CDATA[Next.js 16.4 Is Out: Cache Components, React 19.3, and Upgrade Guide]]></title>
            <description><![CDATA[<p>Next.js 16.4 is officially available. The <a href="https://nextjs.org/blog/next-16-4">release announcement</a>, dated October 6, 2026, replaces the canary outlook this article originally covered on September 29. This update keeps the original URL and publication date, but uses the released APIs and current documentation.</p>
<p>The central shift is the recommendation to adopt Cache Components, now enabled by default in newly generated apps. Existing apps still need a deliberate migration. The release also brings React 19.3 and practical Turbopack improvements.</p>
<h2>What changed since the 16.4 canary article</h2>
<table>
<thead>
<tr>
<th>Preview coverage</th>
<th>Released guidance</th>
</tr>
</thead>
<tbody><tr>
<td><code>unstable_ensureStatic</code> with two values</td>
<td>Use <code>ensureStatic</code>; static levels include <code>&quot;shell&quot;</code>, <code>&quot;prefetch&quot;</code>, and <code>&quot;navigation&quot;</code></td>
</tr>
<tr>
<td>Partial Prefetching presented as a new 16.4 feature</td>
<td>It shipped in 16.3; 16.4 adds controls that refine the model</td>
</tr>
<tr>
<td>React version still uncertain</td>
<td>Next.js 16.4 ships with React 19.3</td>
</tr>
<tr>
<td>Agent upgrades described as always isolated</td>
<td>A separate Git worktree is an optional choice when starting a new agent session</td>
</tr>
<tr>
<td>Canary installation recommended</td>
<td>Use the stable 16.4 release for the app; canary upgrade tooling is a separate choice</td>
</tr>
</tbody></table>
<p>The old preview also emphasized internal Parallel Route matching changes. The stable guide below treats direct loads and slot fallbacks as regression checks, rather than promising a universal new routing rule.</p>
<h2>Cache Components and Partial Prefetching</h2>
<p>Cache Components let you cache selected components and functions with <code>&#39;use cache&#39;</code> while keeping other work dynamic. Cache lifetimes and invalidation belong alongside the cached work. That makes the boundaries visible in the code; moving an app to this model requires checking request-specific reads, loading fallbacks, and invalidation behavior. Start with the <a href="https://nextjs.org/docs/app/getting-started/caching">official caching guide</a> and my <a href="/blog/nextjs-use-cache-migration-guide">Cache Components migration guide</a>.</p>
<p>For an existing app adopting the combined model, configure both flags:</p>
<pre><code class="language-typescript">// next.config.ts
import type { NextConfig } from &#39;next&#39;

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
}

export default nextConfig
</code></pre>
<p><a href="https://nextjs.org/docs/app/api-reference/config/next-config-js/partialPrefetching">Partial Prefetching</a> requires Cache Components. A default link prepares a reusable App Shell; <code>&lt;Link prefetch={true}&gt;</code> can also prepare URL-specific content. Navigation completes the remaining work. Partial Prefetching was introduced in 16.3, so the useful question for 16.4 is how to control those stages.</p>
<p>The distinction matters on a listing with many links. Preparing shared UI is different from fetching every item&#39;s full detail view. Test how much data your links request before enabling additional per-link prefetching across a large page. My <a href="/blog/nextjs-cache-components-static-shell-pattern">static shell pattern guide</a> explains how to structure the reusable UI.</p>
<h2><code>ensureStatic</code>: choose the static boundary</h2>
<p>The stable route export is <a href="https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic"><code>ensureStatic</code></a>, replacing the preview&#39;s <code>unstable_ensureStatic</code> spelling.</p>
<table>
<thead>
<tr>
<th>Value</th>
<th>Required static output</th>
</tr>
</thead>
<tbody><tr>
<td><code>&quot;auto&quot;</code></td>
<td>No extra requirement; the default</td>
</tr>
<tr>
<td><code>&quot;shell&quot;</code></td>
<td>App Shell</td>
</tr>
<tr>
<td><code>&quot;prefetch&quot;</code></td>
<td>App Shell and per-link prefetch</td>
</tr>
<tr>
<td><code>&quot;navigation&quot;</code></td>
<td>Complete server-rendered route</td>
</tr>
</tbody></table>
<p><code>false</code> prevents other segments from imposing a static level on that route. The shell and prefetch levels depend on Partial Prefetching; the navigation level works with Cache Components alone.</p>
<p>For a page that must never introduce request-time server rendering:</p>
<pre><code class="language-typescript">// app/about/page.tsx
export const ensureStatic = &#39;navigation&#39;

export default function AboutPage() {
  return &lt;main&gt;About our company&lt;/main&gt;
}
</code></pre>
<p>With <code>&quot;navigation&quot;</code>, dynamic content causes build validation to fail. The shell and prefetch levels can move request-specific work behind Suspense to later stages; they do not add the same build validation. Choose the level based on the route&#39;s actual requirements. A personalized dashboard and a static company page need different guarantees.</p>
<h2><code>navigation()</code> and <code>prefetch()</code>: defer expensive work</h2>
<p><a href="https://nextjs.org/docs/app/api-reference/functions/navigation"><code>navigation()</code></a> keeps runtime work below the call out of the App Shell and per-link prefetches. It lets reusable content retain caching while waiting until navigation to generate it. Static prerenders can still include that content.</p>
<p>For example, an expensive report can sit behind a loading boundary:</p>
<pre><code class="language-typescript">import { Suspense } from &#39;react&#39;
import { navigation } from &#39;next/cache&#39;

export default function ReportPage() {
  return (
    &lt;main&gt;
      &lt;h1&gt;Report&lt;/h1&gt;
      &lt;Suspense fallback={&lt;p&gt;Loading report...&lt;/p&gt;}&gt;
        &lt;Report /&gt;
      &lt;/Suspense&gt;
    &lt;/main&gt;
  )
}

async function Report() {
  await navigation()
  return &lt;p&gt;{await getReportSummary()}&lt;/p&gt;
}

async function getReportSummary() {
  &#39;use cache&#39;
  // Replace this illustrative result with your expensive data query.
  return &#39;Report summary&#39;
}
</code></pre>
<p><a href="https://nextjs.org/docs/app/api-reference/functions/prefetch"><code>prefetch()</code></a> defers runtime work out of the App Shell, but allows it during an explicit per-link prefetch or navigation. It requires Cache Components and has no effect without Partial Prefetching. Place either call before the work to defer and wrap that component in Suspense.</p>
<p>Use <code>prefetch()</code> when a link should prepare the content ahead of a click. Use <code>navigation()</code> when generating it for every visible link would be too expensive. Neither is a substitute for authorization checks or correct cache keys.</p>
<h2><code>next analyze</code>: inspect what each route ships</h2>
<p>The <a href="https://nextjs.org/docs/app/guides/package-bundling">Turbopack bundle analyzer guide</a> documents the stable CLI entry point:</p>
<pre><code class="language-bash">pnpm next analyze

# Save analysis for comparison or sharing
pnpm next analyze --output
</code></pre>
<p>Use route and environment filters to find large client imports, then inspect import chains to see why each module is included. Keep a baseline before changing imports so you can compare the result.</p>
<p>For apps that intentionally use Webpack, follow the guide&#39;s separate <code>@next/bundle-analyzer</code> instructions. The Turbopack analyzer and the Webpack plugin are different paths.</p>
<h2>Turbopack improvements and experimental options</h2>
<p>The <a href="https://nextjs.org/blog/next-16-4">16.4 announcement</a> reports a 20–25% smaller disk cache, lazy server HMR, a shared runtime chunk, shorter production CSS Module names, and export mangling. These are framework improvements; measure their effect on your own app rather than treating them as guaranteed project-level speedups.</p>
<p>The following options remain experimental:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>Purpose</th>
<th>Documentation</th>
</tr>
</thead>
<tbody><tr>
<td><code>experimental.turbopackGc</code></td>
<td>Reclaim unused compilation work from memory and disk</td>
<td><a href="https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackGc">Garbage collection</a></td>
</tr>
<tr>
<td><code>experimental.turbopackLazyDynamicImports</code></td>
<td>Compile client dynamic imports when requested in development; some <code>next/dynamic</code> imports remain eager</td>
<td><a href="https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackLazyDynamicImports">Lazy dynamic imports</a></td>
</tr>
<tr>
<td><code>experimental.turbopackRustReactCompiler</code></td>
<td>Use the Rust React Compiler with <code>reactCompiler: true</code></td>
<td><a href="https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackRustReactCompiler">Rust compiler</a></td>
</tr>
</tbody></table>
<p>Try these individually on a branch. Compare compilation behavior and resource use across a realistic editing session, including revisiting routes and loading deferred UI.</p>
<h2>React 19.3 is part of the release</h2>
<p>React 19.3 brings stable View Transitions and Fragment Refs, alongside the new <code>browser()</code> API. Read the <a href="https://react.dev/blog/2026/09/09/react-19-3">React 19.3 announcement</a> before adopting individual APIs.</p>
<p>For an existing CMS app, check the supported Next.js and React ranges of its plugins and integrations before changing dependencies. A framework release does not establish compatibility for every integration. My <a href="/blog/nextjs-16-2-caching-unstable-cache-vs-use-cache">unstable_cache versus use cache comparison</a> is useful if your CMS data access still uses the earlier caching model.</p>
<h2>Agent-assisted upgrades are documented, but experimental</h2>
<p>The <a href="https://nextjs.org/docs/app/guides/upgrading/agent-upgrade">agent upgrade guide</a> documents:</p>
<pre><code class="language-bash">npx next@canary upgrade --agent=latest
</code></pre>
<p>Here, <code>next@canary</code> runs current upgrade tooling. For a stable app, the <code>latest</code> policy targets the stable release; an existing canary app stays on the canary channel.</p>
<p>The tool prepares version-specific migration guidance and verification steps. When starting a new agent session interactively, a separate Git worktree is an option, depending on the agent and CLI version. It is not an unconditional isolation guarantee.</p>
<p>The docs still label the workflow experimental. Review the diff and verification results before accepting a migration. Upgrading dependencies and adopting Cache Components are separate decisions you can review independently.</p>
<h2>What to test when upgrading to stable 16.4</h2>
<p>Install the stable version on a branch:</p>
<pre><code class="language-bash">pnpm add next@16.4.0
npx tsc --noEmit
</code></pre>
<p>Check React and React DOM versions against the framework and integration requirements, and update them together where needed.</p>
<ol>
<li><strong>Direct loads and client navigation:</strong> Exercise Parallel Routes, intercepted routes, slot fallbacks, and authenticated redirects in fresh tabs as well as through links.</li>
<li><strong>Cache correctness:</strong> Navigate between sibling dynamic routes, then test sign-in, sign-out, content edits, and invalidation. Confirm cached content belongs to the right URL and session.</li>
<li><strong>Prefetch cost:</strong> Inspect requests on a page with many links. Compare default links with explicit prefetching and check whether expensive work waits for navigation.</li>
<li><strong>Static guarantees:</strong> Identify routes that need <code>ensureStatic</code>, and choose the intended stage. Fully static routes need the navigation level.</li>
<li><strong>Bundle and deployment behavior:</strong> Compare route analysis, deferred imports, CSS output, and standalone file tracing where your hosting setup relies on it.</li>
</ol>
<p>These are recommended checks for your app, not a claim that this site has already completed a 16.4 migration.</p>
<h2>FAQ</h2>
<p><strong>Is Next.js 16.4 stable now?</strong>
Yes. The official announcement is dated October 6, 2026. This article was refreshed on October 7 from its September canary coverage.</p>
<p><strong>Should I still use <code>unstable_ensureStatic</code>?</strong>
Use the documented <code>ensureStatic</code> export in stable 16.4. Recheck the intended stage when migrating a canary configuration.</p>
<p><strong>Does upgrading turn on Cache Components in my existing app?</strong>
Review your configuration and migration requirements. The new-app default does not mean an existing codebase has completed that migration.</p>
<p><strong>Should I enable all the experimental Turbopack flags?</strong>
Evaluate them separately against an observed development problem. Keep the stable upgrade and optional experiments easy to review.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/nextjs-16-4-canary-partial-prefetching-next-analyze</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/nextjs-16-4-canary-partial-prefetching-next-analyze</guid>
            <category><![CDATA[Next.js]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 21:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;Next.js 16.4 is officially available. The &lt;a href=&quot;https://nextjs.org/blog/next-16-4&quot;&gt;release announcement&lt;/a&gt;, dated October 6, 2026, replaces the canary outlook this article originally covered on September 29. This update keeps the original URL and publication date, but uses the released APIs and current documentation.&lt;/p&gt;
&lt;p&gt;The central shift is the recommendation to adopt Cache Components, now enabled by default in newly generated apps. Existing apps still need a deliberate migration. The release also brings React 19.3 and practical Turbopack improvements.&lt;/p&gt;
&lt;h2&gt;What changed since the 16.4 canary article&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Preview coverage&lt;/th&gt;
&lt;th&gt;Released guidance&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;code&gt;unstable_ensureStatic&lt;/code&gt; with two values&lt;/td&gt;
&lt;td&gt;Use &lt;code&gt;ensureStatic&lt;/code&gt;; static levels include &lt;code&gt;&amp;quot;shell&amp;quot;&lt;/code&gt;, &lt;code&gt;&amp;quot;prefetch&amp;quot;&lt;/code&gt;, and &lt;code&gt;&amp;quot;navigation&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Partial Prefetching presented as a new 16.4 feature&lt;/td&gt;
&lt;td&gt;It shipped in 16.3; 16.4 adds controls that refine the model&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;React version still uncertain&lt;/td&gt;
&lt;td&gt;Next.js 16.4 ships with React 19.3&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Agent upgrades described as always isolated&lt;/td&gt;
&lt;td&gt;A separate Git worktree is an optional choice when starting a new agent session&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Canary installation recommended&lt;/td&gt;
&lt;td&gt;Use the stable 16.4 release for the app; canary upgrade tooling is a separate choice&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;The old preview also emphasized internal Parallel Route matching changes. The stable guide below treats direct loads and slot fallbacks as regression checks, rather than promising a universal new routing rule.&lt;/p&gt;
&lt;h2&gt;Cache Components and Partial Prefetching&lt;/h2&gt;
&lt;p&gt;Cache Components let you cache selected components and functions with &lt;code&gt;&amp;#39;use cache&amp;#39;&lt;/code&gt; while keeping other work dynamic. Cache lifetimes and invalidation belong alongside the cached work. That makes the boundaries visible in the code; moving an app to this model requires checking request-specific reads, loading fallbacks, and invalidation behavior. Start with the &lt;a href=&quot;https://nextjs.org/docs/app/getting-started/caching&quot;&gt;official caching guide&lt;/a&gt; and my &lt;a href=&quot;/blog/nextjs-use-cache-migration-guide&quot;&gt;Cache Components migration guide&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;For an existing app adopting the combined model, configure both flags:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// next.config.ts
import type { NextConfig } from &amp;#39;next&amp;#39;

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
}

export default nextConfig
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://nextjs.org/docs/app/api-reference/config/next-config-js/partialPrefetching&quot;&gt;Partial Prefetching&lt;/a&gt; requires Cache Components. A default link prepares a reusable App Shell; &lt;code&gt;&amp;lt;Link prefetch={true}&amp;gt;&lt;/code&gt; can also prepare URL-specific content. Navigation completes the remaining work. Partial Prefetching was introduced in 16.3, so the useful question for 16.4 is how to control those stages.&lt;/p&gt;
&lt;p&gt;The distinction matters on a listing with many links. Preparing shared UI is different from fetching every item&amp;#39;s full detail view. Test how much data your links request before enabling additional per-link prefetching across a large page. My &lt;a href=&quot;/blog/nextjs-cache-components-static-shell-pattern&quot;&gt;static shell pattern guide&lt;/a&gt; explains how to structure the reusable UI.&lt;/p&gt;
&lt;h2&gt;&lt;code&gt;ensureStatic&lt;/code&gt;: choose the static boundary&lt;/h2&gt;
&lt;p&gt;The stable route export is &lt;a href=&quot;https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config/ensureStatic&quot;&gt;&lt;code&gt;ensureStatic&lt;/code&gt;&lt;/a&gt;, replacing the preview&amp;#39;s &lt;code&gt;unstable_ensureStatic&lt;/code&gt; spelling.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Value&lt;/th&gt;
&lt;th&gt;Required static output&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;code&gt;&amp;quot;auto&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;No extra requirement; the default&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;&amp;quot;shell&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;App Shell&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;&amp;quot;prefetch&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;App Shell and per-link prefetch&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;&amp;quot;navigation&amp;quot;&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Complete server-rendered route&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;&lt;code&gt;false&lt;/code&gt; prevents other segments from imposing a static level on that route. The shell and prefetch levels depend on Partial Prefetching; the navigation level works with Cache Components alone.&lt;/p&gt;
&lt;p&gt;For a page that must never introduce request-time server rendering:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// app/about/page.tsx
export const ensureStatic = &amp;#39;navigation&amp;#39;

export default function AboutPage() {
  return &amp;lt;main&amp;gt;About our company&amp;lt;/main&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With &lt;code&gt;&amp;quot;navigation&amp;quot;&lt;/code&gt;, dynamic content causes build validation to fail. The shell and prefetch levels can move request-specific work behind Suspense to later stages; they do not add the same build validation. Choose the level based on the route&amp;#39;s actual requirements. A personalized dashboard and a static company page need different guarantees.&lt;/p&gt;
&lt;h2&gt;&lt;code&gt;navigation()&lt;/code&gt; and &lt;code&gt;prefetch()&lt;/code&gt;: defer expensive work&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://nextjs.org/docs/app/api-reference/functions/navigation&quot;&gt;&lt;code&gt;navigation()&lt;/code&gt;&lt;/a&gt; keeps runtime work below the call out of the App Shell and per-link prefetches. It lets reusable content retain caching while waiting until navigation to generate it. Static prerenders can still include that content.&lt;/p&gt;
&lt;p&gt;For example, an expensive report can sit behind a loading boundary:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;import { Suspense } from &amp;#39;react&amp;#39;
import { navigation } from &amp;#39;next/cache&amp;#39;

export default function ReportPage() {
  return (
    &amp;lt;main&amp;gt;
      &amp;lt;h1&amp;gt;Report&amp;lt;/h1&amp;gt;
      &amp;lt;Suspense fallback={&amp;lt;p&amp;gt;Loading report...&amp;lt;/p&amp;gt;}&amp;gt;
        &amp;lt;Report /&amp;gt;
      &amp;lt;/Suspense&amp;gt;
    &amp;lt;/main&amp;gt;
  )
}

async function Report() {
  await navigation()
  return &amp;lt;p&amp;gt;{await getReportSummary()}&amp;lt;/p&amp;gt;
}

async function getReportSummary() {
  &amp;#39;use cache&amp;#39;
  // Replace this illustrative result with your expensive data query.
  return &amp;#39;Report summary&amp;#39;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;a href=&quot;https://nextjs.org/docs/app/api-reference/functions/prefetch&quot;&gt;&lt;code&gt;prefetch()&lt;/code&gt;&lt;/a&gt; defers runtime work out of the App Shell, but allows it during an explicit per-link prefetch or navigation. It requires Cache Components and has no effect without Partial Prefetching. Place either call before the work to defer and wrap that component in Suspense.&lt;/p&gt;
&lt;p&gt;Use &lt;code&gt;prefetch()&lt;/code&gt; when a link should prepare the content ahead of a click. Use &lt;code&gt;navigation()&lt;/code&gt; when generating it for every visible link would be too expensive. Neither is a substitute for authorization checks or correct cache keys.&lt;/p&gt;
&lt;h2&gt;&lt;code&gt;next analyze&lt;/code&gt;: inspect what each route ships&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://nextjs.org/docs/app/guides/package-bundling&quot;&gt;Turbopack bundle analyzer guide&lt;/a&gt; documents the stable CLI entry point:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm next analyze

# Save analysis for comparison or sharing
pnpm next analyze --output
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Use route and environment filters to find large client imports, then inspect import chains to see why each module is included. Keep a baseline before changing imports so you can compare the result.&lt;/p&gt;
&lt;p&gt;For apps that intentionally use Webpack, follow the guide&amp;#39;s separate &lt;code&gt;@next/bundle-analyzer&lt;/code&gt; instructions. The Turbopack analyzer and the Webpack plugin are different paths.&lt;/p&gt;
&lt;h2&gt;Turbopack improvements and experimental options&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://nextjs.org/blog/next-16-4&quot;&gt;16.4 announcement&lt;/a&gt; reports a 20–25% smaller disk cache, lazy server HMR, a shared runtime chunk, shorter production CSS Module names, and export mangling. These are framework improvements; measure their effect on your own app rather than treating them as guaranteed project-level speedups.&lt;/p&gt;
&lt;p&gt;The following options remain experimental:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Option&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;th&gt;Documentation&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;&lt;code&gt;experimental.turbopackGc&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Reclaim unused compilation work from memory and disk&lt;/td&gt;
&lt;td&gt;&lt;a href=&quot;https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackGc&quot;&gt;Garbage collection&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;experimental.turbopackLazyDynamicImports&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Compile client dynamic imports when requested in development; some &lt;code&gt;next/dynamic&lt;/code&gt; imports remain eager&lt;/td&gt;
&lt;td&gt;&lt;a href=&quot;https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackLazyDynamicImports&quot;&gt;Lazy dynamic imports&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;experimental.turbopackRustReactCompiler&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Use the Rust React Compiler with &lt;code&gt;reactCompiler: true&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;&lt;a href=&quot;https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackRustReactCompiler&quot;&gt;Rust compiler&lt;/a&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Try these individually on a branch. Compare compilation behavior and resource use across a realistic editing session, including revisiting routes and loading deferred UI.&lt;/p&gt;
&lt;h2&gt;React 19.3 is part of the release&lt;/h2&gt;
&lt;p&gt;React 19.3 brings stable View Transitions and Fragment Refs, alongside the new &lt;code&gt;browser()&lt;/code&gt; API. Read the &lt;a href=&quot;https://react.dev/blog/2026/09/09/react-19-3&quot;&gt;React 19.3 announcement&lt;/a&gt; before adopting individual APIs.&lt;/p&gt;
&lt;p&gt;For an existing CMS app, check the supported Next.js and React ranges of its plugins and integrations before changing dependencies. A framework release does not establish compatibility for every integration. My &lt;a href=&quot;/blog/nextjs-16-2-caching-unstable-cache-vs-use-cache&quot;&gt;unstable_cache versus use cache comparison&lt;/a&gt; is useful if your CMS data access still uses the earlier caching model.&lt;/p&gt;
&lt;h2&gt;Agent-assisted upgrades are documented, but experimental&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://nextjs.org/docs/app/guides/upgrading/agent-upgrade&quot;&gt;agent upgrade guide&lt;/a&gt; documents:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;npx next@canary upgrade --agent=latest
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, &lt;code&gt;next@canary&lt;/code&gt; runs current upgrade tooling. For a stable app, the &lt;code&gt;latest&lt;/code&gt; policy targets the stable release; an existing canary app stays on the canary channel.&lt;/p&gt;
&lt;p&gt;The tool prepares version-specific migration guidance and verification steps. When starting a new agent session interactively, a separate Git worktree is an option, depending on the agent and CLI version. It is not an unconditional isolation guarantee.&lt;/p&gt;
&lt;p&gt;The docs still label the workflow experimental. Review the diff and verification results before accepting a migration. Upgrading dependencies and adopting Cache Components are separate decisions you can review independently.&lt;/p&gt;
&lt;h2&gt;What to test when upgrading to stable 16.4&lt;/h2&gt;
&lt;p&gt;Install the stable version on a branch:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm add next@16.4.0
npx tsc --noEmit
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Check React and React DOM versions against the framework and integration requirements, and update them together where needed.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Direct loads and client navigation:&lt;/strong&gt; Exercise Parallel Routes, intercepted routes, slot fallbacks, and authenticated redirects in fresh tabs as well as through links.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cache correctness:&lt;/strong&gt; Navigate between sibling dynamic routes, then test sign-in, sign-out, content edits, and invalidation. Confirm cached content belongs to the right URL and session.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prefetch cost:&lt;/strong&gt; Inspect requests on a page with many links. Compare default links with explicit prefetching and check whether expensive work waits for navigation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Static guarantees:&lt;/strong&gt; Identify routes that need &lt;code&gt;ensureStatic&lt;/code&gt;, and choose the intended stage. Fully static routes need the navigation level.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bundle and deployment behavior:&lt;/strong&gt; Compare route analysis, deferred imports, CSS output, and standalone file tracing where your hosting setup relies on it.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These are recommended checks for your app, not a claim that this site has already completed a 16.4 migration.&lt;/p&gt;
&lt;h2&gt;FAQ&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Is Next.js 16.4 stable now?&lt;/strong&gt;
Yes. The official announcement is dated October 6, 2026. This article was refreshed on October 7 from its September canary coverage.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Should I still use &lt;code&gt;unstable_ensureStatic&lt;/code&gt;?&lt;/strong&gt;
Use the documented &lt;code&gt;ensureStatic&lt;/code&gt; export in stable 16.4. Recheck the intended stage when migrating a canary configuration.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Does upgrading turn on Cache Components in my existing app?&lt;/strong&gt;
Review your configuration and migration requirements. The new-app default does not mean an existing codebase has completed that migration.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Should I enable all the experimental Turbopack flags?&lt;/strong&gt;
Evaluate them separately against an observed development problem. Keep the stable upgrade and optional experiments easy to review.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/nextjs-16-4-canary-partial-prefetching-next-analyze"/>
        </item>
        <item>
            <title><![CDATA[Neon Managed Better Auth in Next.js on Vercel: A Production Setup Guide]]></title>
            <description><![CDATA[<p><em>By Matija. Last updated: 25 September 2026. Tested with Next.js 16.3.6 (App Router), <code>@neondatabase/auth</code> 0.5.0-beta, neonctl 6.0.0, Prisma 7, Postgres 17, and Neon installed through the Vercel Marketplace.</em></p>
<p>Better Auth has rapidly become one of the most compelling modern authentication frameworks in the TypeScript ecosystem—modular, type-safe, and designed for full developer ownership over user tables. For teams running Next.js on Vercel paired with Neon Postgres, authentication previously leaned towards third-party managed providers like Stack Auth. However, as teams migrate to native solutions that live directly alongside their database, Neon Managed Better Auth has emerged as the premier choice.</p>
<p>Neon Managed Better Auth gives you a hosted Better Auth server that stores its data directly in your own Neon database, and on Vercel most of the platform plumbing is already automated for you. Whether you are migrating away from Stack Auth or starting fresh on a new stack, this guide teaches you exactly how to set up production authentication on your project.</p>
<p>A production setup comes down to six pieces: configure the Neon branch from the CLI and API, add four environment variables in Vercel, create one server auth instance and one client, proxy <code>/api/auth</code> through your app while blocking the admin endpoints, keep your own user table as the source of truth, and route auth emails through your own mailer with a signed webhook. This guide shows the setup I run in production for a multi-tenant Next.js app, including the parts the quick start skips: custom forms instead of <code>&lt;AuthView /&gt;</code>, six-digit reset codes, admin operations that need a service account, and a beta client that throws where you expect it to return an error.</p>
<h2>What the quick start does not cover</h2>
<p>I set this up while moving a multi-tenant delivery-note SaaS onto Managed Better Auth. If you are coming from Stack Auth, the migration itself (backups, the provider lock, re-creating users) is covered in <a href="/blog/migrate-stack-auth-to-neon-better-auth">How to Migrate from Stack Auth to Neon Managed Better Auth in Next.js</a>. The Neon quick start is fine for a demo. You mount a handler, drop in <code>&lt;AuthView /&gt;</code> and <code>&lt;UserButton /&gt;</code>, and read <code>useSession()</code>. A real app needs a bit more than that. My app has organisations, roles and statuses that live in Prisma. Admins create accounts for their team members, reset passwords and delete users. The UI is in Slovenian, all form feedback uses toasts, and every email has to come from the product&#39;s own sender address.</p>
<p>None of that is exotic, but each piece has a Neon- or Vercel-specific detail that is easy to miss. It helps to know where everything lives before looking at code:</p>
<table>
<thead>
<tr>
<th>Piece</th>
<th>Where it lives</th>
<th>What it does</th>
</tr>
</thead>
<tbody><tr>
<td>Better Auth server</td>
<td>Neon (hosted, per branch)</td>
<td>Sign-in, sessions, reset codes, admin endpoints</td>
</tr>
<tr>
<td>Auth tables</td>
<td>Your Neon database, <code>neon_auth</code> schema</td>
<td><code>user</code>, <code>account</code>, <code>session</code>, <code>verification</code>, and a few more</td>
</tr>
<tr>
<td>Branch configuration</td>
<td>Neon CLI and API</td>
<td>Sign-up policy, SMTP, trusted domains, webhooks, roles</td>
</tr>
<tr>
<td>Secrets and base URL</td>
<td>Vercel environment variables</td>
<td>Base URL, cookie secret, service-account credentials</td>
</tr>
<tr>
<td>Proxy route and session layer</td>
<td>Your Next.js app</td>
<td><code>/api/auth/[...path]</code>, <code>getAuthenticatedUser</code>, role checks</td>
</tr>
<tr>
<td>Organisation, role, status</td>
<td>Your own user table (Prisma)</td>
<td>Source of truth, linked by <code>authUserId</code></td>
</tr>
</tbody></table>
<p>The rest of this guide goes through those pieces in the order you would set them up.</p>
<h2>Configure the Neon branch from the CLI and API</h2>
<p>Managed Better Auth is enabled per branch, and nearly all of its configuration can be scripted. That matters because you want preview, development and production branches set up identically, and a script is the only reliable way to get there. The Neon CLI&#39;s <code>neon-auth</code> command group covers most settings, and the REST API covers the rest. These are the operations I needed and how each one is done:</p>
<table>
<thead>
<tr>
<th>Need</th>
<th>Available via CLI/API?</th>
<th>How</th>
</tr>
</thead>
<tbody><tr>
<td>Enable Better Auth on a branch</td>
<td>API</td>
<td><code>POST /projects/{id}/branches/{branch}/auth</code> with <code>{&quot;auth_provider&quot;:&quot;better_auth&quot;}</code></td>
</tr>
<tr>
<td>Disable public sign-up</td>
<td>CLI and API</td>
<td><code>neon neon-auth config email-password update --disable-sign-up</code></td>
</tr>
<tr>
<td>Custom SMTP sender</td>
<td>CLI</td>
<td><code>neon neon-auth config email-provider update --type standard --host … --port …</code></td>
</tr>
<tr>
<td>Webhooks</td>
<td>CLI and API</td>
<td><code>PUT …/auth/webhooks</code></td>
</tr>
<tr>
<td>Trusted domains</td>
<td>CLI</td>
<td><code>neon neon-auth domain add https://www.example.com</code></td>
</tr>
<tr>
<td>Create or delete a user, set a role</td>
<td>CLI and API</td>
<td><code>neon neon-auth user create</code>, <code>user set-role &lt;id&gt; --roles admin</code></td>
</tr>
<tr>
<td>Set a user&#39;s password</td>
<td>No</td>
<td>Better Auth <code>/admin/set-user-password</code>, needs an admin session</td>
</tr>
<tr>
<td>Change a user&#39;s email or name</td>
<td>No</td>
<td>Better Auth <code>/admin/update-user</code>, needs an admin session</td>
</tr>
</tbody></table>
<p>Enabling is a single API call. The CLI&#39;s <code>enable</code> command has no way to choose the provider, so a direct request is the reliable path:</p>
<pre><code class="language-bash"># File: scripts/neon-auth-setup.sh
curl -sS --fail-with-body -X POST &quot;$API/branches/$BRANCH_ID/auth&quot; \
  -H &quot;Authorization: Bearer $TOKEN&quot; -H &quot;Content-Type: application/json&quot; \
  -d &#39;{&quot;auth_provider&quot;:&quot;better_auth&quot;,&quot;database_name&quot;:&quot;neondb&quot;}&#39;
</code></pre>
<p>The response includes the branch&#39;s <code>base_url</code>, which is the only URL your app needs. Two settings deserve a word. Add every origin your app is served from as a trusted domain (I added both <code>https://www.example.com</code> and the bare <code>https://example.com</code>), because Better Auth rejects requests whose <code>Origin</code> it does not recognise. And if users should not be able to register themselves, disable sign-up. Admin-created accounts and password reset keep working with sign-up disabled; I checked both on a test branch before relying on it.</p>
<p>I wrapped all of this in one idempotent shell script that takes <code>--branch</code> and <code>--app-url</code> arguments. Idempotent is the important word. When a step fails halfway, you want to fix the problem and rerun the script without creating duplicates or losing a generated password.</p>
<h2>Environment variables on Vercel</h2>
<p>If you installed Neon through the Vercel Marketplace, you already have some of this. After I enabled Better Auth on the production branch, the integration added <code>NEON_AUTH_BASE_URL</code> to the project&#39;s production environment by itself, marked as an integration-managed variable. Check that its value matches the <code>base_url</code> from the enable call before adding anything by hand. Mine matched, and trying to add it again gives an &quot;already exists&quot; error.</p>
<p>The remaining variables you add yourself. Pipe the value in on stdin so it never ends up in your shell history:</p>
<pre><code class="language-bash"># File: terminal
openssl rand -base64 32 | tr -d &#39;\n&#39; | vercel env add NEON_AUTH_COOKIE_SECRET production
printf &#39;%s&#39; &quot;$SERVICE_EMAIL&quot; | vercel env add NEON_AUTH_SERVICE_EMAIL production
printf &#39;%s&#39; &quot;$SERVICE_PASSWORD&quot; | vercel env add NEON_AUTH_SERVICE_PASSWORD production
</code></pre>
<p>The cookie secret signs the session cache cookie and must be at least 32 characters. The two service-account variables are explained in the admin section below. The app also needs to know its own public origin; I use the existing <code>NEXT_PUBLIC_ADDRESS</code> for that, both as the <code>Origin</code> header on server-side auth calls and for links in emails. For local development, <code>vercel env pull .env.local</code> brings everything down once the development environment has values too.</p>
<p>Because Managed Better Auth is tied directly to your Neon branches, running separate configurations across development, preview, and production environments is essential. If you haven&#39;t yet structured your environment variables and database branch isolation on Vercel, follow our <a href="/blog/vercel-neon-nextjs-3-tier-setup">Vercel Neon Setup for Next.js: 3-Tier Enterprise Guide</a> to establish that branching foundation before deploying authentication.</p>
<h2>Create the server and client instances</h2>
<p>With the branch configured and the variables in place, the app needs exactly one server instance and one client. On the server, <code>createNeonAuth</code> gives you session reads plus the handler you mount under <code>/api/auth</code>:</p>
<pre><code class="language-ts">// File: src/lib/auth/server.ts
import { createNeonAuth } from &quot;@neondatabase/auth/next/server&quot;;

import { requireEnv } from &quot;./env&quot;;

export const auth = createNeonAuth({
  baseUrl: requireEnv(&quot;NEON_AUTH_BASE_URL&quot;),
  cookies: { secret: requireEnv(&quot;NEON_AUTH_COOKIE_SECRET&quot;) },
});
</code></pre>
<p><code>requireEnv</code> is a three-line helper that throws a clear error when a variable is missing, which is much easier to debug than a request failing later with an undefined base URL. I deliberately left <code>import &quot;server-only&quot;</code> out of this file, because it is also imported from places that run outside the React Server Components environment. The client is even simpler:</p>
<pre><code class="language-ts">// File: src/lib/auth/client.ts
&quot;use client&quot;;

import { createAuthClient } from &quot;@neondatabase/auth/next&quot;;

export const authClient = createAuthClient();
</code></pre>
<p>It takes no arguments and talks to your own <code>/api/auth</code> route on the same origin. It already includes the plugins you need later, including email OTP for password reset, and it needs no provider component. I removed the old provider wrapper from the root layout entirely.</p>
<h2>Proxy <code>/api/auth</code> and block the admin endpoints</h2>
<p>The browser never talks to Neon directly. It talks to your app, and your app forwards the request to Neon. That is what <code>auth.handler()</code> does, and it only needs a catch-all route. I wrapped it so admin endpoints can never be reached from the browser through my domain:</p>
<pre><code class="language-ts">// File: src/app/api/auth/[...path]/route.ts
import { auth } from &quot;@/lib/auth/server&quot;;

const handlers = auth.handler();

type RouteContext = { params: Promise&lt;{ path: string[] }&gt; };
type Handler = (request: Request, context: RouteContext) =&gt; Promise&lt;Response&gt;;

const blockAdminPaths =
  (handler: Handler): Handler =&gt;
  async (request, context) =&gt; {
    const { path } = await context.params;
    if (path[0] === &quot;admin&quot;) {
      return Response.json({ message: &quot;Forbidden&quot; }, { status: 403 });
    }
    return handler(request, context);
  };

export const GET = blockAdminPaths(handlers.GET);
export const POST = blockAdminPaths(handlers.POST);
</code></pre>
<p>The folder must be named <code>[...path]</code>, because the handler reads <code>params.path</code>. The block is defence in depth: Neon already refuses admin calls from users without the admin role, but the admin endpoints have no legitimate caller in the browser, so there is no reason to forward them at all.</p>
<h2>Keep your own user table as the source of truth</h2>
<p>This is the decision that keeps the rest of the setup simple. Better Auth knows who someone is. Your database knows which organisation they belong to, what their role is and whether their account is active. I keep those apart and link them with one column, <code>User.authUserId</code>, which points at <code>neon_auth.user.id</code>.</p>
<p>The only function that talks to Better Auth about the current user is small, and it is cached per request so several server components can call it without repeating the lookup:</p>
<pre><code class="language-ts">// File: src/lib/auth/session.ts
export const getAuthenticatedUser = cache(
  async (): Promise&lt;AuthenticatedUser | null&gt; =&gt; {
    const { data } = await auth.getSession();
    const user = data?.user;
    if (!user) return null;
    return { id: user.id, email: user.email, name: user.name ?? null };
  },
);
</code></pre>
<p>Everything else builds on top of that. <code>getCurrentAuthContext</code> finds the Prisma user by <code>authUserId</code>. If there is none, it falls back to a matching email and relinks the row, and it activates invited users on their first sign-in:</p>
<pre><code class="language-ts">// File: src/lib/auth/provision.ts
const shouldActivate = existingByEmail.status === UserStatus.INVITE_PENDING;
const shouldRelink = existingByEmail.authUserId !== authUser.id;
</code></pre>
<p>That email fallback turned out to be useful in more than one way: it is what makes re-created auth accounts reconnect to existing app users on their own. Layouts then call <code>requireAuthContext()</code> and redirect by role, so drivers and admins end up in their own areas without any route-level middleware.</p>
<p>A related trap is Next.js proxy (middleware) placement. In Next.js 16, route-level request interceptors shifted with the middleware-to-proxy evolution (for a detailed breakdown of this transition and how file locations changed, see our guide on <a href="/blog/nextjs16-middleware-change">Why Next.js is Moving Away from Middleware: Understanding the proxy.ts Rename</a>). If your app lives in <code>src/app</code>, Next.js only picks up <code>src/proxy.ts</code>. A <code>proxy.ts</code> at the repository root is silently ignored. The app I worked on had one there for months, and it had never run once. I deleted it and kept role enforcement in the layouts, which already did the job.</p>
<h2>Build your own sign-in form</h2>
<p><code>&lt;AuthView /&gt;</code> is fine for English-language apps that accept its look. I wanted a form in the app&#39;s own design and language, with the same toast feedback as every other form, so I wrote a small one on top of <code>authClient.signIn.email</code>. The Better Auth client normally returns <code>{ data, error }</code>, and the TypeScript types say the same. In practice, <code>@neondatabase/auth</code> 0.5.0-beta throws on a failed sign-in. My first version never reset its loading state after a wrong password; the button just sat there saying it was signing in. Handle both styles and the problem goes away:</p>
<pre><code class="language-ts">// File: src/app/prijava/_components/sign-in-form.tsx
try {
  const { error } = await authClient.signIn.email({ email, password });
  if (error) throw error;
} catch (error) {
  toast.error(getAuthErrorMessage(error, &quot;Prijava ni uspela. Poskusite znova.&quot;));
  setIsPending(false);
  return;
}

toast.success(&quot;Prijava uspešna.&quot;);
router.refresh();
router.push(&quot;/admin&quot;);
</code></pre>
<p>The thrown value is a Supabase-style <code>AuthError</code> with a <code>message</code> such as &quot;Invalid email or password&quot; and a <code>status</code>, so <code>getAuthErrorMessage</code> maps known codes and known messages to translated text and falls back to a generic line. While testing this I also noticed every toast appeared twice. The root layout mounted a second toaster next to the provider that already rendered one. That had nothing to do with auth, but auth errors were where I first noticed it.</p>
<p>The sign-in page itself redirects users who are already signed in, but only when the full app context resolves. A signed-in user who has no app account, or whose account is inactive, would otherwise bounce between the login page and the dashboard forever, because the dashboard layout sends them back to login.</p>
<h2>Password reset with six-digit codes</h2>
<p>One of the great out-of-the-box benefits of Neon Managed Better Auth is that Neon can manage transactional emailing for you. You don&#39;t need to configure a custom SMTP server, set up Resend or Postmark API keys, or manage sender domains just to get verification emails and reset codes flowing during development and early production. If you want full custom domain branding and tailored HTML templates later, you can still switch to a custom SMTP server or signed webhooks at any time. But having zero-config, Neon-managed email delivery out of the box eliminates a major friction point when standing up auth.</p>
<p>Managed Better Auth defaults to one-time codes for password reset, not links, and that changes how you build the flow. The user asks for a code, receives six digits by email, and submits the code together with a new password. Both steps are client calls:</p>
<pre><code class="language-ts">// File: src/app/prijava/_components/password-reset-form.tsx
await authClient.forgetPassword.emailOtp({ email });

await authClient.emailOtp.resetPassword({ email, otp, password });
</code></pre>
<p>Two properties of the codes should shape your UI. A code expires after five minutes, and requesting a new code invalidates the previous one. I learned the first one when my own test code came back as <code>OTP_EXPIRED</code>. Both calls also throw like sign-in does, so they get the same try/catch treatment. My reset form has two steps on one page: an email step, and a code-plus-password step with a six-slot OTP input. A second route opens the form directly on the code step with the email filled in, which is where the button in the reset email points. The form states the five-minute limit and offers &quot;send a new code&quot;, because otherwise &quot;my code doesn&#39;t work&quot; will be your most common support request.</p>
<h2>Admin operations through a service account</h2>
<p>If your admins manage other users, this section matters more than any other. Better Auth&#39;s admin endpoints only accept a signed-in session whose user has the Neon role <code>admin</code>. There is no server key that bypasses this.</p>
<p>Do not solve it by giving your app&#39;s admins that role. The Neon role is project-wide, not tenant-scoped. In a multi-tenant app, any organisation admin holding it could call Neon&#39;s admin API directly with their own session cookie and reset the password of a user in another organisation. I tested the opposite case to be sure: a normal user calling <code>/admin/list-users</code> gets <code>YOU_ARE_NOT_ALLOWED_TO_LIST_USERS</code>, and <code>/admin/set-user-password</code> is refused the same way. That is the behaviour you want for everyone except one identity.</p>
<p>That identity is a dedicated service account. The setup script creates it while sign-up is still open, gives it the role with <code>neon neon-auth user set-role &lt;id&gt; --roles admin</code>, and only then closes sign-up. A server-only module signs in as it and caches the resulting session cookie per server instance:</p>
<pre><code class="language-ts">// File: src/lib/auth/admin.ts
const response = await fetch(`${baseUrl}/sign-in/email`, {
  method: &quot;POST&quot;,
  headers: { &quot;Content-Type&quot;: &quot;application/json&quot;, Origin: origin },
  body: JSON.stringify({ email, password }),
  cache: &quot;no-store&quot;,
});

const cookie = response.headers
  .getSetCookie()
  .map((header) =&gt; header.split(&quot;;&quot;)[0])
  .join(&quot;; &quot;);
</code></pre>
<p>Every admin request then sends that cookie together with an <code>Origin</code> that is one of the trusted domains, and a 401 triggers one fresh sign-in and a retry. On top of that sit five small helpers: <code>createAuthUser</code>, <code>setAuthUserPassword</code>, <code>updateAuthUser</code>, <code>removeAuthUser</code> and <code>findAuthUserByEmail</code>. They are the only way the rest of the app touches user management in Better Auth. My server actions check the organisation and role in Prisma first, exactly as before, and only then call a helper. Authorisation stays in your code; the service account only carries it out. For extending this service account pattern to let superadmins troubleshoot issues, see our complete guide to <a href="/blog/neon-auth-nextjs-user-impersonation">adding &quot;log in as user&quot; impersonation with Neon Auth</a>.</p>
<h2>Send auth emails through your own mailer</h2>
<p>By default Neon sends verification and reset emails from a shared sender with its own template. You can make them yours in two ways, and I use both.</p>
<p>Setting a custom SMTP provider on the branch (<code>config email-provider update --type standard …</code> with your SMTP credentials) makes Neon&#39;s default emails come from your own address. Subscribing to the <code>send.otp</code> webhook goes one step further: Neon skips its email entirely and calls your endpoint with the code, and you send whatever template you like. The SMTP setting then remains a fallback, because disabling the webhook brings Neon&#39;s own emails back, still from your sender.</p>
<p>The webhook is signed with a detached Ed25519 JWS over the timestamp and the raw request body, so read the body as text and verify it before parsing:</p>
<pre><code class="language-ts">// File: src/app/api/webhooks/neon-auth/route.ts
export async function POST(request: Request) {
  const rawBody = await request.text();

  try {
    await verifyNeonAuthWebhook(rawBody, request.headers);
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return Response.json({ message: &quot;Invalid signature&quot; }, { status: 401 });
    }
    throw error;
  }

  const event = JSON.parse(rawBody) as NeonAuthWebhookEvent;
  // event.event_data.otp_code, event.event_data.otp_type, event.user.email
}
</code></pre>
<p>The verification fetches the public key from <code>${NEON_AUTH_BASE_URL}/.well-known/jwks.json</code>, picks the key named in the <code>x-neon-signature-kid</code> header, rebuilds the signing input as <code>header.base64url(timestamp + &quot;.&quot; + base64url(rawBody))</code>, and rejects anything older than five minutes. After that, the route looks at <code>otp_type</code>. For <code>forget-password</code> it renders my reset template with the code and a link to the reset page and sends it through the app&#39;s existing mailer. It must answer within the timeout you configured (up to ten seconds, I use five), and Neon retries 5xx responses, so I keep a small set of already-delivered event ids to avoid sending the same email twice.</p>
<p>Emails that Neon does not send at all, such as onboarding messages with temporary passwords, go through the same mailer directly from the server actions that create users. One detail from my mailer is worth copying: it copies an admin address on outgoing mail by default, and for credential emails I explicitly pass empty <code>cc</code> and <code>bcc</code> so temporary passwords go to exactly one inbox.</p>
<h2>Testing webhooks when Vercel previews are protected</h2>
<p>This is the Vercel detail that caught me out. Neon has to reach your webhook URL from the internet. If your preview deployments sit behind Vercel&#39;s deployment protection, Neon gets redirected to Vercel&#39;s SSO login and your handler never runs. I checked an existing preview URL first: it answered with a 302 to <code>vercel.com/sso-api</code>.</p>
<p>Rather than change the project&#39;s protection settings, I tested against my local dev server through a temporary Cloudflare quick tunnel. I pointed the test branch&#39;s webhook at the tunnel URL, requested a reset code, and watched the real signed request arrive, pass verification and send the email in under a second. If you already use <code>cloudflared</code> with a named tunnel, pass an empty config file (<code>cloudflared --config /path/to/empty.yml tunnel --url http://localhost:3000</code>). Otherwise the ingress rules in your <code>~/.cloudflared/config.yml</code> take over and answer every request with 404. In production the webhook points at your real domain, where there is no protection in the way.</p>
<h2>FAQ</h2>
<p><strong>Do I need <code>&lt;AuthView /&gt;</code> and the auth UI package?</strong>
No. The client from <code>@neondatabase/auth/next</code> already covers sign-in, sign-out and the OTP reset calls, so you can build your own forms and drop the UI package completely. Use <code>&lt;AuthView /&gt;</code> if its look and language fit your app.</p>
<p><strong>Can my admins manage users without a service account?</strong>
Only if you give them the Neon admin role, which is project-wide. In a single-tenant app that can be acceptable. In a multi-tenant app it lets one organisation&#39;s admin manage users of another, so use a service account and keep app roles in your database.</p>
<p><strong>Why does my sign-in button stay stuck after a wrong password?</strong>
<code>@neondatabase/auth</code> 0.5.0-beta throws on failed auth calls instead of returning <code>{ error }</code>. Wrap each client call in try/catch and treat a thrown error and a returned error the same way.</p>
<p><strong>Why do users say their reset code does not work?</strong>
Codes expire after five minutes, and each new request invalidates the previous code. Say both things in the form and in the email.</p>
<p><strong>Does disabling sign-up break password reset or admin-created accounts?</strong>
No. I tested both with sign-up disabled: the service account can still create users, and existing users can still reset their passwords.</p>
<h2>Conclusion</h2>
<p>A production setup of Neon Managed Better Auth on Vercel comes down to a few clear boundaries. Neon hosts the auth server and keeps its tables in your database, configured per branch through a script. Vercel holds four variables, one of which the Marketplace integration adds for you. Your app mounts one proxy route that forwards everything except the admin endpoints, and keeps its own user table as the source of truth, linked by <code>authUserId</code>. On top of that come custom forms that handle a client that throws, a six-digit reset flow with honest expiry copy, a single service account for admin operations, and a signed webhook that routes auth emails through your own mailer.</p>
<p>If you are setting this up now, start with the setup script and the proxy route. The rest builds on those two pieces, and they are the parts where a small mistake is hardest to spot later.</p>
<p>Let me know in the comments if you have questions, and subscribe for more practical development guides.</p>
<p>Thanks,
Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/neon-managed-better-auth-nextjs-vercel</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/neon-managed-better-auth-nextjs-vercel</guid>
            <category><![CDATA[Next.js]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;&lt;em&gt;By Matija. Last updated: 25 September 2026. Tested with Next.js 16.3.6 (App Router), &lt;code&gt;@neondatabase/auth&lt;/code&gt; 0.5.0-beta, neonctl 6.0.0, Prisma 7, Postgres 17, and Neon installed through the Vercel Marketplace.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Better Auth has rapidly become one of the most compelling modern authentication frameworks in the TypeScript ecosystem—modular, type-safe, and designed for full developer ownership over user tables. For teams running Next.js on Vercel paired with Neon Postgres, authentication previously leaned towards third-party managed providers like Stack Auth. However, as teams migrate to native solutions that live directly alongside their database, Neon Managed Better Auth has emerged as the premier choice.&lt;/p&gt;
&lt;p&gt;Neon Managed Better Auth gives you a hosted Better Auth server that stores its data directly in your own Neon database, and on Vercel most of the platform plumbing is already automated for you. Whether you are migrating away from Stack Auth or starting fresh on a new stack, this guide teaches you exactly how to set up production authentication on your project.&lt;/p&gt;
&lt;p&gt;A production setup comes down to six pieces: configure the Neon branch from the CLI and API, add four environment variables in Vercel, create one server auth instance and one client, proxy &lt;code&gt;/api/auth&lt;/code&gt; through your app while blocking the admin endpoints, keep your own user table as the source of truth, and route auth emails through your own mailer with a signed webhook. This guide shows the setup I run in production for a multi-tenant Next.js app, including the parts the quick start skips: custom forms instead of &lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt;, six-digit reset codes, admin operations that need a service account, and a beta client that throws where you expect it to return an error.&lt;/p&gt;
&lt;h2&gt;What the quick start does not cover&lt;/h2&gt;
&lt;p&gt;I set this up while moving a multi-tenant delivery-note SaaS onto Managed Better Auth. If you are coming from Stack Auth, the migration itself (backups, the provider lock, re-creating users) is covered in &lt;a href=&quot;/blog/migrate-stack-auth-to-neon-better-auth&quot;&gt;How to Migrate from Stack Auth to Neon Managed Better Auth in Next.js&lt;/a&gt;. The Neon quick start is fine for a demo. You mount a handler, drop in &lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;UserButton /&amp;gt;&lt;/code&gt;, and read &lt;code&gt;useSession()&lt;/code&gt;. A real app needs a bit more than that. My app has organisations, roles and statuses that live in Prisma. Admins create accounts for their team members, reset passwords and delete users. The UI is in Slovenian, all form feedback uses toasts, and every email has to come from the product&amp;#39;s own sender address.&lt;/p&gt;
&lt;p&gt;None of that is exotic, but each piece has a Neon- or Vercel-specific detail that is easy to miss. It helps to know where everything lives before looking at code:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Piece&lt;/th&gt;
&lt;th&gt;Where it lives&lt;/th&gt;
&lt;th&gt;What it does&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Better Auth server&lt;/td&gt;
&lt;td&gt;Neon (hosted, per branch)&lt;/td&gt;
&lt;td&gt;Sign-in, sessions, reset codes, admin endpoints&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Auth tables&lt;/td&gt;
&lt;td&gt;Your Neon database, &lt;code&gt;neon_auth&lt;/code&gt; schema&lt;/td&gt;
&lt;td&gt;&lt;code&gt;user&lt;/code&gt;, &lt;code&gt;account&lt;/code&gt;, &lt;code&gt;session&lt;/code&gt;, &lt;code&gt;verification&lt;/code&gt;, and a few more&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Branch configuration&lt;/td&gt;
&lt;td&gt;Neon CLI and API&lt;/td&gt;
&lt;td&gt;Sign-up policy, SMTP, trusted domains, webhooks, roles&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Secrets and base URL&lt;/td&gt;
&lt;td&gt;Vercel environment variables&lt;/td&gt;
&lt;td&gt;Base URL, cookie secret, service-account credentials&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Proxy route and session layer&lt;/td&gt;
&lt;td&gt;Your Next.js app&lt;/td&gt;
&lt;td&gt;&lt;code&gt;/api/auth/[...path]&lt;/code&gt;, &lt;code&gt;getAuthenticatedUser&lt;/code&gt;, role checks&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Organisation, role, status&lt;/td&gt;
&lt;td&gt;Your own user table (Prisma)&lt;/td&gt;
&lt;td&gt;Source of truth, linked by &lt;code&gt;authUserId&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;The rest of this guide goes through those pieces in the order you would set them up.&lt;/p&gt;
&lt;h2&gt;Configure the Neon branch from the CLI and API&lt;/h2&gt;
&lt;p&gt;Managed Better Auth is enabled per branch, and nearly all of its configuration can be scripted. That matters because you want preview, development and production branches set up identically, and a script is the only reliable way to get there. The Neon CLI&amp;#39;s &lt;code&gt;neon-auth&lt;/code&gt; command group covers most settings, and the REST API covers the rest. These are the operations I needed and how each one is done:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Need&lt;/th&gt;
&lt;th&gt;Available via CLI/API?&lt;/th&gt;
&lt;th&gt;How&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Enable Better Auth on a branch&lt;/td&gt;
&lt;td&gt;API&lt;/td&gt;
&lt;td&gt;&lt;code&gt;POST /projects/{id}/branches/{branch}/auth&lt;/code&gt; with &lt;code&gt;{&amp;quot;auth_provider&amp;quot;:&amp;quot;better_auth&amp;quot;}&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Disable public sign-up&lt;/td&gt;
&lt;td&gt;CLI and API&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth config email-password update --disable-sign-up&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Custom SMTP sender&lt;/td&gt;
&lt;td&gt;CLI&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth config email-provider update --type standard --host … --port …&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Webhooks&lt;/td&gt;
&lt;td&gt;CLI and API&lt;/td&gt;
&lt;td&gt;&lt;code&gt;PUT …/auth/webhooks&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Trusted domains&lt;/td&gt;
&lt;td&gt;CLI&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth domain add https://www.example.com&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Create or delete a user, set a role&lt;/td&gt;
&lt;td&gt;CLI and API&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth user create&lt;/code&gt;, &lt;code&gt;user set-role &amp;lt;id&amp;gt; --roles admin&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Set a user&amp;#39;s password&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Better Auth &lt;code&gt;/admin/set-user-password&lt;/code&gt;, needs an admin session&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Change a user&amp;#39;s email or name&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Better Auth &lt;code&gt;/admin/update-user&lt;/code&gt;, needs an admin session&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Enabling is a single API call. The CLI&amp;#39;s &lt;code&gt;enable&lt;/code&gt; command has no way to choose the provider, so a direct request is the reliable path:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# File: scripts/neon-auth-setup.sh
curl -sS --fail-with-body -X POST &amp;quot;$API/branches/$BRANCH_ID/auth&amp;quot; \
  -H &amp;quot;Authorization: Bearer $TOKEN&amp;quot; -H &amp;quot;Content-Type: application/json&amp;quot; \
  -d &amp;#39;{&amp;quot;auth_provider&amp;quot;:&amp;quot;better_auth&amp;quot;,&amp;quot;database_name&amp;quot;:&amp;quot;neondb&amp;quot;}&amp;#39;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The response includes the branch&amp;#39;s &lt;code&gt;base_url&lt;/code&gt;, which is the only URL your app needs. Two settings deserve a word. Add every origin your app is served from as a trusted domain (I added both &lt;code&gt;https://www.example.com&lt;/code&gt; and the bare &lt;code&gt;https://example.com&lt;/code&gt;), because Better Auth rejects requests whose &lt;code&gt;Origin&lt;/code&gt; it does not recognise. And if users should not be able to register themselves, disable sign-up. Admin-created accounts and password reset keep working with sign-up disabled; I checked both on a test branch before relying on it.&lt;/p&gt;
&lt;p&gt;I wrapped all of this in one idempotent shell script that takes &lt;code&gt;--branch&lt;/code&gt; and &lt;code&gt;--app-url&lt;/code&gt; arguments. Idempotent is the important word. When a step fails halfway, you want to fix the problem and rerun the script without creating duplicates or losing a generated password.&lt;/p&gt;
&lt;h2&gt;Environment variables on Vercel&lt;/h2&gt;
&lt;p&gt;If you installed Neon through the Vercel Marketplace, you already have some of this. After I enabled Better Auth on the production branch, the integration added &lt;code&gt;NEON_AUTH_BASE_URL&lt;/code&gt; to the project&amp;#39;s production environment by itself, marked as an integration-managed variable. Check that its value matches the &lt;code&gt;base_url&lt;/code&gt; from the enable call before adding anything by hand. Mine matched, and trying to add it again gives an &amp;quot;already exists&amp;quot; error.&lt;/p&gt;
&lt;p&gt;The remaining variables you add yourself. Pipe the value in on stdin so it never ends up in your shell history:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# File: terminal
openssl rand -base64 32 | tr -d &amp;#39;\n&amp;#39; | vercel env add NEON_AUTH_COOKIE_SECRET production
printf &amp;#39;%s&amp;#39; &amp;quot;$SERVICE_EMAIL&amp;quot; | vercel env add NEON_AUTH_SERVICE_EMAIL production
printf &amp;#39;%s&amp;#39; &amp;quot;$SERVICE_PASSWORD&amp;quot; | vercel env add NEON_AUTH_SERVICE_PASSWORD production
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The cookie secret signs the session cache cookie and must be at least 32 characters. The two service-account variables are explained in the admin section below. The app also needs to know its own public origin; I use the existing &lt;code&gt;NEXT_PUBLIC_ADDRESS&lt;/code&gt; for that, both as the &lt;code&gt;Origin&lt;/code&gt; header on server-side auth calls and for links in emails. For local development, &lt;code&gt;vercel env pull .env.local&lt;/code&gt; brings everything down once the development environment has values too.&lt;/p&gt;
&lt;p&gt;Because Managed Better Auth is tied directly to your Neon branches, running separate configurations across development, preview, and production environments is essential. If you haven&amp;#39;t yet structured your environment variables and database branch isolation on Vercel, follow our &lt;a href=&quot;/blog/vercel-neon-nextjs-3-tier-setup&quot;&gt;Vercel Neon Setup for Next.js: 3-Tier Enterprise Guide&lt;/a&gt; to establish that branching foundation before deploying authentication.&lt;/p&gt;
&lt;h2&gt;Create the server and client instances&lt;/h2&gt;
&lt;p&gt;With the branch configured and the variables in place, the app needs exactly one server instance and one client. On the server, &lt;code&gt;createNeonAuth&lt;/code&gt; gives you session reads plus the handler you mount under &lt;code&gt;/api/auth&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/server.ts
import { createNeonAuth } from &amp;quot;@neondatabase/auth/next/server&amp;quot;;

import { requireEnv } from &amp;quot;./env&amp;quot;;

export const auth = createNeonAuth({
  baseUrl: requireEnv(&amp;quot;NEON_AUTH_BASE_URL&amp;quot;),
  cookies: { secret: requireEnv(&amp;quot;NEON_AUTH_COOKIE_SECRET&amp;quot;) },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;requireEnv&lt;/code&gt; is a three-line helper that throws a clear error when a variable is missing, which is much easier to debug than a request failing later with an undefined base URL. I deliberately left &lt;code&gt;import &amp;quot;server-only&amp;quot;&lt;/code&gt; out of this file, because it is also imported from places that run outside the React Server Components environment. The client is even simpler:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/client.ts
&amp;quot;use client&amp;quot;;

import { createAuthClient } from &amp;quot;@neondatabase/auth/next&amp;quot;;

export const authClient = createAuthClient();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It takes no arguments and talks to your own &lt;code&gt;/api/auth&lt;/code&gt; route on the same origin. It already includes the plugins you need later, including email OTP for password reset, and it needs no provider component. I removed the old provider wrapper from the root layout entirely.&lt;/p&gt;
&lt;h2&gt;Proxy &lt;code&gt;/api/auth&lt;/code&gt; and block the admin endpoints&lt;/h2&gt;
&lt;p&gt;The browser never talks to Neon directly. It talks to your app, and your app forwards the request to Neon. That is what &lt;code&gt;auth.handler()&lt;/code&gt; does, and it only needs a catch-all route. I wrapped it so admin endpoints can never be reached from the browser through my domain:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/app/api/auth/[...path]/route.ts
import { auth } from &amp;quot;@/lib/auth/server&amp;quot;;

const handlers = auth.handler();

type RouteContext = { params: Promise&amp;lt;{ path: string[] }&amp;gt; };
type Handler = (request: Request, context: RouteContext) =&amp;gt; Promise&amp;lt;Response&amp;gt;;

const blockAdminPaths =
  (handler: Handler): Handler =&amp;gt;
  async (request, context) =&amp;gt; {
    const { path } = await context.params;
    if (path[0] === &amp;quot;admin&amp;quot;) {
      return Response.json({ message: &amp;quot;Forbidden&amp;quot; }, { status: 403 });
    }
    return handler(request, context);
  };

export const GET = blockAdminPaths(handlers.GET);
export const POST = blockAdminPaths(handlers.POST);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The folder must be named &lt;code&gt;[...path]&lt;/code&gt;, because the handler reads &lt;code&gt;params.path&lt;/code&gt;. The block is defence in depth: Neon already refuses admin calls from users without the admin role, but the admin endpoints have no legitimate caller in the browser, so there is no reason to forward them at all.&lt;/p&gt;
&lt;h2&gt;Keep your own user table as the source of truth&lt;/h2&gt;
&lt;p&gt;This is the decision that keeps the rest of the setup simple. Better Auth knows who someone is. Your database knows which organisation they belong to, what their role is and whether their account is active. I keep those apart and link them with one column, &lt;code&gt;User.authUserId&lt;/code&gt;, which points at &lt;code&gt;neon_auth.user.id&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The only function that talks to Better Auth about the current user is small, and it is cached per request so several server components can call it without repeating the lookup:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/session.ts
export const getAuthenticatedUser = cache(
  async (): Promise&amp;lt;AuthenticatedUser | null&amp;gt; =&amp;gt; {
    const { data } = await auth.getSession();
    const user = data?.user;
    if (!user) return null;
    return { id: user.id, email: user.email, name: user.name ?? null };
  },
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Everything else builds on top of that. &lt;code&gt;getCurrentAuthContext&lt;/code&gt; finds the Prisma user by &lt;code&gt;authUserId&lt;/code&gt;. If there is none, it falls back to a matching email and relinks the row, and it activates invited users on their first sign-in:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/provision.ts
const shouldActivate = existingByEmail.status === UserStatus.INVITE_PENDING;
const shouldRelink = existingByEmail.authUserId !== authUser.id;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That email fallback turned out to be useful in more than one way: it is what makes re-created auth accounts reconnect to existing app users on their own. Layouts then call &lt;code&gt;requireAuthContext()&lt;/code&gt; and redirect by role, so drivers and admins end up in their own areas without any route-level middleware.&lt;/p&gt;
&lt;p&gt;A related trap is Next.js proxy (middleware) placement. In Next.js 16, route-level request interceptors shifted with the middleware-to-proxy evolution (for a detailed breakdown of this transition and how file locations changed, see our guide on &lt;a href=&quot;/blog/nextjs16-middleware-change&quot;&gt;Why Next.js is Moving Away from Middleware: Understanding the proxy.ts Rename&lt;/a&gt;). If your app lives in &lt;code&gt;src/app&lt;/code&gt;, Next.js only picks up &lt;code&gt;src/proxy.ts&lt;/code&gt;. A &lt;code&gt;proxy.ts&lt;/code&gt; at the repository root is silently ignored. The app I worked on had one there for months, and it had never run once. I deleted it and kept role enforcement in the layouts, which already did the job.&lt;/p&gt;
&lt;h2&gt;Build your own sign-in form&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt; is fine for English-language apps that accept its look. I wanted a form in the app&amp;#39;s own design and language, with the same toast feedback as every other form, so I wrote a small one on top of &lt;code&gt;authClient.signIn.email&lt;/code&gt;. The Better Auth client normally returns &lt;code&gt;{ data, error }&lt;/code&gt;, and the TypeScript types say the same. In practice, &lt;code&gt;@neondatabase/auth&lt;/code&gt; 0.5.0-beta throws on a failed sign-in. My first version never reset its loading state after a wrong password; the button just sat there saying it was signing in. Handle both styles and the problem goes away:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/app/prijava/_components/sign-in-form.tsx
try {
  const { error } = await authClient.signIn.email({ email, password });
  if (error) throw error;
} catch (error) {
  toast.error(getAuthErrorMessage(error, &amp;quot;Prijava ni uspela. Poskusite znova.&amp;quot;));
  setIsPending(false);
  return;
}

toast.success(&amp;quot;Prijava uspešna.&amp;quot;);
router.refresh();
router.push(&amp;quot;/admin&amp;quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The thrown value is a Supabase-style &lt;code&gt;AuthError&lt;/code&gt; with a &lt;code&gt;message&lt;/code&gt; such as &amp;quot;Invalid email or password&amp;quot; and a &lt;code&gt;status&lt;/code&gt;, so &lt;code&gt;getAuthErrorMessage&lt;/code&gt; maps known codes and known messages to translated text and falls back to a generic line. While testing this I also noticed every toast appeared twice. The root layout mounted a second toaster next to the provider that already rendered one. That had nothing to do with auth, but auth errors were where I first noticed it.&lt;/p&gt;
&lt;p&gt;The sign-in page itself redirects users who are already signed in, but only when the full app context resolves. A signed-in user who has no app account, or whose account is inactive, would otherwise bounce between the login page and the dashboard forever, because the dashboard layout sends them back to login.&lt;/p&gt;
&lt;h2&gt;Password reset with six-digit codes&lt;/h2&gt;
&lt;p&gt;One of the great out-of-the-box benefits of Neon Managed Better Auth is that Neon can manage transactional emailing for you. You don&amp;#39;t need to configure a custom SMTP server, set up Resend or Postmark API keys, or manage sender domains just to get verification emails and reset codes flowing during development and early production. If you want full custom domain branding and tailored HTML templates later, you can still switch to a custom SMTP server or signed webhooks at any time. But having zero-config, Neon-managed email delivery out of the box eliminates a major friction point when standing up auth.&lt;/p&gt;
&lt;p&gt;Managed Better Auth defaults to one-time codes for password reset, not links, and that changes how you build the flow. The user asks for a code, receives six digits by email, and submits the code together with a new password. Both steps are client calls:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/app/prijava/_components/password-reset-form.tsx
await authClient.forgetPassword.emailOtp({ email });

await authClient.emailOtp.resetPassword({ email, otp, password });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Two properties of the codes should shape your UI. A code expires after five minutes, and requesting a new code invalidates the previous one. I learned the first one when my own test code came back as &lt;code&gt;OTP_EXPIRED&lt;/code&gt;. Both calls also throw like sign-in does, so they get the same try/catch treatment. My reset form has two steps on one page: an email step, and a code-plus-password step with a six-slot OTP input. A second route opens the form directly on the code step with the email filled in, which is where the button in the reset email points. The form states the five-minute limit and offers &amp;quot;send a new code&amp;quot;, because otherwise &amp;quot;my code doesn&amp;#39;t work&amp;quot; will be your most common support request.&lt;/p&gt;
&lt;h2&gt;Admin operations through a service account&lt;/h2&gt;
&lt;p&gt;If your admins manage other users, this section matters more than any other. Better Auth&amp;#39;s admin endpoints only accept a signed-in session whose user has the Neon role &lt;code&gt;admin&lt;/code&gt;. There is no server key that bypasses this.&lt;/p&gt;
&lt;p&gt;Do not solve it by giving your app&amp;#39;s admins that role. The Neon role is project-wide, not tenant-scoped. In a multi-tenant app, any organisation admin holding it could call Neon&amp;#39;s admin API directly with their own session cookie and reset the password of a user in another organisation. I tested the opposite case to be sure: a normal user calling &lt;code&gt;/admin/list-users&lt;/code&gt; gets &lt;code&gt;YOU_ARE_NOT_ALLOWED_TO_LIST_USERS&lt;/code&gt;, and &lt;code&gt;/admin/set-user-password&lt;/code&gt; is refused the same way. That is the behaviour you want for everyone except one identity.&lt;/p&gt;
&lt;p&gt;That identity is a dedicated service account. The setup script creates it while sign-up is still open, gives it the role with &lt;code&gt;neon neon-auth user set-role &amp;lt;id&amp;gt; --roles admin&lt;/code&gt;, and only then closes sign-up. A server-only module signs in as it and caches the resulting session cookie per server instance:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/admin.ts
const response = await fetch(`${baseUrl}/sign-in/email`, {
  method: &amp;quot;POST&amp;quot;,
  headers: { &amp;quot;Content-Type&amp;quot;: &amp;quot;application/json&amp;quot;, Origin: origin },
  body: JSON.stringify({ email, password }),
  cache: &amp;quot;no-store&amp;quot;,
});

const cookie = response.headers
  .getSetCookie()
  .map((header) =&amp;gt; header.split(&amp;quot;;&amp;quot;)[0])
  .join(&amp;quot;; &amp;quot;);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every admin request then sends that cookie together with an &lt;code&gt;Origin&lt;/code&gt; that is one of the trusted domains, and a 401 triggers one fresh sign-in and a retry. On top of that sit five small helpers: &lt;code&gt;createAuthUser&lt;/code&gt;, &lt;code&gt;setAuthUserPassword&lt;/code&gt;, &lt;code&gt;updateAuthUser&lt;/code&gt;, &lt;code&gt;removeAuthUser&lt;/code&gt; and &lt;code&gt;findAuthUserByEmail&lt;/code&gt;. They are the only way the rest of the app touches user management in Better Auth. My server actions check the organisation and role in Prisma first, exactly as before, and only then call a helper. Authorisation stays in your code; the service account only carries it out. For extending this service account pattern to let superadmins troubleshoot issues, see our complete guide to &lt;a href=&quot;/blog/neon-auth-nextjs-user-impersonation&quot;&gt;adding &amp;quot;log in as user&amp;quot; impersonation with Neon Auth&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Send auth emails through your own mailer&lt;/h2&gt;
&lt;p&gt;By default Neon sends verification and reset emails from a shared sender with its own template. You can make them yours in two ways, and I use both.&lt;/p&gt;
&lt;p&gt;Setting a custom SMTP provider on the branch (&lt;code&gt;config email-provider update --type standard …&lt;/code&gt; with your SMTP credentials) makes Neon&amp;#39;s default emails come from your own address. Subscribing to the &lt;code&gt;send.otp&lt;/code&gt; webhook goes one step further: Neon skips its email entirely and calls your endpoint with the code, and you send whatever template you like. The SMTP setting then remains a fallback, because disabling the webhook brings Neon&amp;#39;s own emails back, still from your sender.&lt;/p&gt;
&lt;p&gt;The webhook is signed with a detached Ed25519 JWS over the timestamp and the raw request body, so read the body as text and verify it before parsing:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/app/api/webhooks/neon-auth/route.ts
export async function POST(request: Request) {
  const rawBody = await request.text();

  try {
    await verifyNeonAuthWebhook(rawBody, request.headers);
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return Response.json({ message: &amp;quot;Invalid signature&amp;quot; }, { status: 401 });
    }
    throw error;
  }

  const event = JSON.parse(rawBody) as NeonAuthWebhookEvent;
  // event.event_data.otp_code, event.event_data.otp_type, event.user.email
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The verification fetches the public key from &lt;code&gt;${NEON_AUTH_BASE_URL}/.well-known/jwks.json&lt;/code&gt;, picks the key named in the &lt;code&gt;x-neon-signature-kid&lt;/code&gt; header, rebuilds the signing input as &lt;code&gt;header.base64url(timestamp + &amp;quot;.&amp;quot; + base64url(rawBody))&lt;/code&gt;, and rejects anything older than five minutes. After that, the route looks at &lt;code&gt;otp_type&lt;/code&gt;. For &lt;code&gt;forget-password&lt;/code&gt; it renders my reset template with the code and a link to the reset page and sends it through the app&amp;#39;s existing mailer. It must answer within the timeout you configured (up to ten seconds, I use five), and Neon retries 5xx responses, so I keep a small set of already-delivered event ids to avoid sending the same email twice.&lt;/p&gt;
&lt;p&gt;Emails that Neon does not send at all, such as onboarding messages with temporary passwords, go through the same mailer directly from the server actions that create users. One detail from my mailer is worth copying: it copies an admin address on outgoing mail by default, and for credential emails I explicitly pass empty &lt;code&gt;cc&lt;/code&gt; and &lt;code&gt;bcc&lt;/code&gt; so temporary passwords go to exactly one inbox.&lt;/p&gt;
&lt;h2&gt;Testing webhooks when Vercel previews are protected&lt;/h2&gt;
&lt;p&gt;This is the Vercel detail that caught me out. Neon has to reach your webhook URL from the internet. If your preview deployments sit behind Vercel&amp;#39;s deployment protection, Neon gets redirected to Vercel&amp;#39;s SSO login and your handler never runs. I checked an existing preview URL first: it answered with a 302 to &lt;code&gt;vercel.com/sso-api&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Rather than change the project&amp;#39;s protection settings, I tested against my local dev server through a temporary Cloudflare quick tunnel. I pointed the test branch&amp;#39;s webhook at the tunnel URL, requested a reset code, and watched the real signed request arrive, pass verification and send the email in under a second. If you already use &lt;code&gt;cloudflared&lt;/code&gt; with a named tunnel, pass an empty config file (&lt;code&gt;cloudflared --config /path/to/empty.yml tunnel --url http://localhost:3000&lt;/code&gt;). Otherwise the ingress rules in your &lt;code&gt;~/.cloudflared/config.yml&lt;/code&gt; take over and answer every request with 404. In production the webhook points at your real domain, where there is no protection in the way.&lt;/p&gt;
&lt;h2&gt;FAQ&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Do I need &lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt; and the auth UI package?&lt;/strong&gt;
No. The client from &lt;code&gt;@neondatabase/auth/next&lt;/code&gt; already covers sign-in, sign-out and the OTP reset calls, so you can build your own forms and drop the UI package completely. Use &lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt; if its look and language fit your app.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Can my admins manage users without a service account?&lt;/strong&gt;
Only if you give them the Neon admin role, which is project-wide. In a single-tenant app that can be acceptable. In a multi-tenant app it lets one organisation&amp;#39;s admin manage users of another, so use a service account and keep app roles in your database.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why does my sign-in button stay stuck after a wrong password?&lt;/strong&gt;
&lt;code&gt;@neondatabase/auth&lt;/code&gt; 0.5.0-beta throws on failed auth calls instead of returning &lt;code&gt;{ error }&lt;/code&gt;. Wrap each client call in try/catch and treat a thrown error and a returned error the same way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why do users say their reset code does not work?&lt;/strong&gt;
Codes expire after five minutes, and each new request invalidates the previous code. Say both things in the form and in the email.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Does disabling sign-up break password reset or admin-created accounts?&lt;/strong&gt;
No. I tested both with sign-up disabled: the service account can still create users, and existing users can still reset their passwords.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;A production setup of Neon Managed Better Auth on Vercel comes down to a few clear boundaries. Neon hosts the auth server and keeps its tables in your database, configured per branch through a script. Vercel holds four variables, one of which the Marketplace integration adds for you. Your app mounts one proxy route that forwards everything except the admin endpoints, and keeps its own user table as the source of truth, linked by &lt;code&gt;authUserId&lt;/code&gt;. On top of that come custom forms that handle a client that throws, a six-digit reset flow with honest expiry copy, a single service account for admin operations, and a signed webhook that routes auth emails through your own mailer.&lt;/p&gt;
&lt;p&gt;If you are setting this up now, start with the setup script and the proxy route. The rest builds on those two pieces, and they are the parts where a small mistake is hardest to spot later.&lt;/p&gt;
&lt;p&gt;Let me know in the comments if you have questions, and subscribe for more practical development guides.&lt;/p&gt;
&lt;p&gt;Thanks,
Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/neon-managed-better-auth-nextjs-vercel"/>
        </item>
        <item>
            <title><![CDATA[How to Migrate from Stack Auth to Neon Managed Better Auth in Next.js]]></title>
            <description><![CDATA[<p><em>By Matija. Last updated: 25 September 2026. Tested with Next.js 16.3.6, <code>@neondatabase/auth</code> 0.5.0-beta, neonctl 6.0.0, Prisma 7 and Postgres 17.</em></p>
<p>I recently revisited an internal web application built for a client after they reported an urgent operational issue: they were suddenly unable to invite or onboard new team members. When the app was originally architected, it relied on Stack Auth—the turnkey authentication provider Neon officially backed at launch. However, as Better Auth gained massive adoption across the TypeScript ecosystem (culminating in Vercel&#39;s backing), Neon announced the sunsetting of Stack Auth in favor of Neon Managed Better Auth. With legacy features degrading and unmaintained dependencies threatening onboarding, upgrading wasn&#39;t optional. But there was a catch: Neon enforces exactly one auth provider per project, meaning you cannot run Stack Auth and Better Auth side-by-side during a transition. This guide shares the exact, production-tested steps I took to execute that hard cutover on Next.js, covering the unspoken gotchas—from non-transferable password hashes and schema clashes to admin session workarounds and idempotent user relinking.</p>
<h2>Why the official migration guide is not enough</h2>
<p>I recently moved a multi-tenant delivery-note SaaS off legacy Neon Auth. It had been running on Stack Auth (<code>@stackframe/stack</code>) since Neon launched its auth product, and Neon now points everyone to Managed Better Auth. The official &quot;From Stack Auth (legacy)&quot; guide is a good SDK reference: it shows <code>StackServerApp</code> becoming <code>createNeonAuth</code>, <code>useUser</code> becoming <code>useSession</code>, <code>&lt;SignIn /&gt;</code> becoming <code>&lt;AuthView /&gt;</code>. What it does not tell you is what happens to your users, your admin tooling and your uptime.</p>
<p>Three facts shaped the whole migration once I found them. First, a Neon project can only have one auth provider, so you cannot enable Better Auth on a branch to test it while production keeps using Stack. Second, Neon states plainly that existing password users cannot be migrated because the hashing algorithms differ, so every user needs a new password. Third, Better Auth&#39;s admin endpoints (create user, set password, change email, delete) only work from a signed-in session whose user has the Neon role <code>admin</code>, which matters a lot if your app lets organisation admins manage their own users.</p>
<p>A short aside if you are still on Stack and considering the &quot;eject&quot; route instead: claiming your Stack project gives you the full Stack dashboard, and its email templates are addressed by UUID, not by the friendly names the docs suggest. That works, but you are then running auth on a platform Neon no longer develops. I chose to migrate.</p>
<p>In this app, the Prisma <code>User</code> table was already the source of truth for organisation, role and status, and auth only linked to it through a <code>User.authUserId</code> column. If your app is structured the same way, the migration is mostly about re-pointing that one column. Everything below assumes that shape.</p>
<h2>Step 1: Back up, then prove the backup restores</h2>
<p>Do this before you touch any auth setting, because unlinking Stack is not reversible from the Neon side. I made three independent backups and verified each one.</p>
<p>The fastest restore path is a Neon snapshot branch. It is an instant copy-on-write of the whole database, including the legacy <code>neon_auth.users_sync</code> table:</p>
<pre><code class="language-bash"># File: terminal
neon branches create --project-id &quot;$NEON_PROJECT_ID&quot; \
  --name pre-better-auth-2026-09-24 --parent main
</code></pre>
<p>The second backup is an offline dump that survives even if something goes wrong with the Neon project itself. One gotcha here: my local <code>pg_dump</code> was version 16 and the server runs Postgres 17, and <code>pg_dump</code> refuses to dump a newer server. The official Docker image solves that without installing anything:</p>
<pre><code class="language-bash"># File: terminal
docker run --rm --user &quot;$(id -u):$(id -g)&quot; -e PGURL \
  -v ~/backups/app:/backup postgres:17 \
  pg_dump &quot;$PGURL&quot; -Fc --no-owner -f /backup/pre-better-auth.dump
</code></pre>
<p>A backup you have never restored is a hope, not a backup. I restored the dump into a throwaway branch and compared both row counts and an MD5 hash of the table contents against production:</p>
<pre><code class="language-sql">-- File: verify-restore.sql
select md5(string_agg(t::text, &#39;|&#39; order by t.id)) from &quot;User&quot; t;
select md5(string_agg(t::text, &#39;|&#39; order by t.id)) from &quot;DeliveryNote&quot; t;
</code></pre>
<p>Identical hashes on both sides mean the dump is complete. The third backup is a CSV mapping each Prisma user id to its Stack <code>authUserId</code>. If you ever need to roll back, that single file turns the database side of the rollback into one <code>UPDATE</code>. Finally, record the current production deployment URL (<code>vercel ls --prod</code>) and tag the current commit, so the code side of a rollback is <code>vercel rollback &lt;url&gt;</code>.</p>
<p>If you haven&#39;t yet established isolated development and preview database branches on Neon and Vercel, review our <a href="/blog/vercel-neon-nextjs-3-tier-setup">Vercel Neon Setup for Next.js: 3-Tier Enterprise Guide</a> first. Having clean branch separation ensures your spike tests and production rehearsals never risk live customer records.</p>
<h2>Step 2: Rehearse on a spike branch</h2>
<p>Before writing any application code, I checked that every operation the app needs is actually possible, first through the CLI and API and then on a throwaway branch. The Neon CLI (<code>neonctl</code>) has a <code>neon-auth</code> command group that covers most of the configuration. I also checked the endpoints against the OpenAPI spec. This is what I found:</p>
<table>
<thead>
<tr>
<th>Need</th>
<th>Available via CLI/API?</th>
<th>How</th>
</tr>
</thead>
<tbody><tr>
<td>Enable Better Auth on a branch</td>
<td>API only (CLI <code>enable</code> has no provider flag)</td>
<td><code>POST /projects/{id}/branches/{branch}/auth</code></td>
</tr>
<tr>
<td>Disable public sign-up</td>
<td>Yes</td>
<td><code>neon neon-auth config email-password update --disable-sign-up</code></td>
</tr>
<tr>
<td>Use your own SMTP (Brevo in my case)</td>
<td>Yes</td>
<td><code>neon neon-auth config email-provider update --type standard ...</code></td>
</tr>
<tr>
<td>Webhooks for auth emails</td>
<td>Yes</td>
<td><code>neon neon-auth config webhook update ...</code> or <code>PUT .../auth/webhooks</code></td>
</tr>
<tr>
<td>Trusted domains</td>
<td>Yes</td>
<td><code>neon neon-auth domain add &lt;url&gt;</code></td>
</tr>
<tr>
<td>Create/delete user, set role</td>
<td>Yes (no password on create)</td>
<td><code>neon neon-auth user create</code>, <code>user set-role &lt;id&gt; --roles admin</code></td>
</tr>
<tr>
<td>Set a user&#39;s password</td>
<td>No</td>
<td>Better Auth <code>/admin/set-user-password</code>, needs an admin session</td>
</tr>
<tr>
<td>Change a user&#39;s email or name</td>
<td>No</td>
<td>Better Auth <code>/admin/update-user</code>, needs an admin session</td>
</tr>
</tbody></table>
<p>The last two rows are the important ones. Everything you configure once can be scripted, but the runtime operations your admin UI needs have to go through Better Auth&#39;s admin endpoints, and those need a signed-in admin. I cover how to handle that in the admin section below.</p>
<p>On the spike branch I then proved the full chain end to end: enabling Better Auth, creating a service account, creating a user with a password, setting a new password, changing an email, deleting the user, disabling sign-up, sending a reset code through my own SMTP, and completing a reset with that code. Only after every step worked did I write application code.</p>
<h2>&quot;Neon Auth with different auth provider already exists for this project&quot;</h2>
<p>This is the error you will get the first time you try to enable Better Auth on any branch of a project that still has Stack attached. It does not matter that you are on a spike branch: the provider is locked at project level.</p>
<p>The fix is to unlink Stack from the project:</p>
<pre><code class="language-bash"># File: terminal
neon neon-auth disable --project-id &quot;$NEON_PROJECT_ID&quot; --branch main
</code></pre>
<p>Leave out <code>--delete-data</code>; it defaults to false, and your <code>neon_auth.users_sync</code> rows stay in place. What the docs do not warn you about is the side effect. The Stack publishable and server keys that Neon issued are revoked immediately, and your production login breaks at that moment. Right after unlinking, a direct call to the Stack API returned this:</p>
<pre><code class="language-text">INVALID_PUBLISHABLE_CLIENT_KEY: The publishable key is not valid for the project &quot;…&quot;. Does the project and/or the key exist?
</code></pre>
<p>This is why the order of the cutover matters so much, and I come back to it at the end. Plan for this step to be the start of your downtime window, not something you do on a quiet afternoon days before the deploy.</p>
<h2>&quot;The <code>neon_auth</code> schema already exists and cannot be automatically provisioned&quot;</h2>
<p>With Stack unlinked, the next attempt to enable Better Auth fails again, this time because the old Stack sync table still lives in the <code>neon_auth</code> schema and Better Auth wants that schema name for its own tables. The error text suggests dropping it. I renamed it instead, so the data stays available until I am sure I will not need it:</p>
<pre><code class="language-sql">-- File: rename-legacy-schema.sql
ALTER SCHEMA neon_auth RENAME TO neon_auth_stack_legacy;
</code></pre>
<p>Then enable Better Auth through the API. The CLI&#39;s <code>enable</code> command has no way to choose the provider, so a direct request is the reliable path:</p>
<pre><code class="language-bash"># File: terminal
curl -X POST &quot;https://console.neon.tech/api/v2/projects/$NEON_PROJECT_ID/branches/$BRANCH_ID/auth&quot; \
  -H &quot;Authorization: Bearer $NEON_API_KEY&quot; -H &quot;Content-Type: application/json&quot; \
  -d &#39;{&quot;auth_provider&quot;:&quot;better_auth&quot;,&quot;database_name&quot;:&quot;neondb&quot;}&#39;
</code></pre>
<p>The response contains your new <code>base_url</code>. Better Auth now creates its tables (<code>user</code>, <code>account</code>, <code>session</code>, <code>verification</code> and a few more) in your own database under <code>neon_auth</code>, which means you can join against them with plain SQL. If your project was installed through the Vercel Marketplace, the integration also adds <code>NEON_AUTH_BASE_URL</code> to your production environment variables automatically. Check that it matches before you add your own.</p>
<p>I wrapped all of the branch configuration (schema rename, enable, trusted domains, SMTP, service account, disabling sign-up and webhook) into one idempotent shell script. Being able to rerun it is not a luxury, as you will see in the gotchas below.</p>
<h2>Swap the server and client SDK</h2>
<p>The code side is the part the official guide covers well, so I will focus on what I did differently. On the server, one <code>createNeonAuth</code> instance gives you session reads and the API proxy handler:</p>
<pre><code class="language-ts">// File: src/lib/auth/server.ts
import { createNeonAuth } from &quot;@neondatabase/auth/next/server&quot;;

import { requireEnv } from &quot;./env&quot;;

export const auth = createNeonAuth({
  baseUrl: requireEnv(&quot;NEON_AUTH_BASE_URL&quot;),
  cookies: { secret: requireEnv(&quot;NEON_AUTH_COOKIE_SECRET&quot;) },
});
</code></pre>
<p>The cookie secret must be at least 32 characters; <code>openssl rand -base64 32</code> is fine. On the client, <code>createAuthClient()</code> from <code>@neondatabase/auth/next</code> takes no arguments and talks to your own <code>/api/auth</code> route. It already includes the email-OTP plugin, which matters for password reset later.</p>
<p>The proxy route mounts Neon&#39;s handler. I wrapped it so the browser can never reach the admin endpoints through my domain, because only the server should ever call those:</p>
<pre><code class="language-ts">// File: src/app/api/auth/[...path]/route.ts
import { auth } from &quot;@/lib/auth/server&quot;;

const handlers = auth.handler();

type RouteContext = { params: Promise&lt;{ path: string[] }&gt; };
type Handler = (request: Request, context: RouteContext) =&gt; Promise&lt;Response&gt;;

const blockAdminPaths =
  (handler: Handler): Handler =&gt;
  async (request, context) =&gt; {
    const { path } = await context.params;
    if (path[0] === &quot;admin&quot;) {
      return Response.json({ message: &quot;Forbidden&quot; }, { status: 403 });
    }
    return handler(request, context);
  };

export const GET = blockAdminPaths(handlers.GET);
export const POST = blockAdminPaths(handlers.POST);
</code></pre>
<p>The session layer is where keeping your own user table pays off. My existing <code>getCurrentAuthContext</code> and <code>requireAuthContext</code> helpers stayed exactly the same. Only the function that asks &quot;who is signed in?&quot; changed:</p>
<pre><code class="language-ts">// File: src/lib/auth/session.ts
export const getAuthenticatedUser = cache(
  async (): Promise&lt;AuthenticatedUser | null&gt; =&gt; {
    const { data } = await auth.getSession();
    const user = data?.user;
    if (!user) return null;
    return { id: user.id, email: user.email, name: user.name ?? null };
  },
);
</code></pre>
<p>Every layout and server action kept calling <code>requireAuthContext()</code> as before. The layouts already enforce roles and redirect drivers and admins to their own areas, so no route guards had to change. While doing this I also found that the app&#39;s root-level <code>proxy.ts</code> had never run at all: with the app living in <code>src/app</code>, Next.js only picks up <code>src/proxy.ts</code>. I deleted it rather than switch it on halfway through a migration.</p>
<h2>Sign-in and password reset forms</h2>
<p>I replaced Stack&#39;s <code>&lt;SignIn /&gt;</code> with a small form of my own rather than <code>&lt;AuthView /&gt;</code>, because the app is in Slovenian and uses Sonner toasts for all feedback. Better Auth&#39;s client normally returns <code>{ data, error }</code>, and the Neon types say the same. In practice, <code>@neondatabase/auth</code> 0.5.0-beta throws on a failed sign-in, so my first version left the button stuck on its loading label after a wrong password. The fix is to handle both styles:</p>
<pre><code class="language-ts">// File: src/app/prijava/_components/sign-in-form.tsx
try {
  const { error } = await authClient.signIn.email({ email, password });
  if (error) throw error;
} catch (error) {
  toast.error(getAuthErrorMessage(error, &quot;Prijava ni uspela. Poskusite znova.&quot;));
  setIsPending(false);
  return;
}
</code></pre>
<p>The thrown value is a Supabase-style <code>AuthError</code> with a message such as &quot;Invalid email or password&quot;, so my message helper maps both <code>code</code> values and known messages to translated text.</p>
<p>Password reset in Managed Better Auth uses one-time codes by default, not links. The user asks for a code with <code>authClient.forgetPassword.emailOtp({ email })</code>, receives six digits, and submits them with <code>authClient.emailOtp.resetPassword({ email, otp, password })</code>. The code expires after five minutes, and requesting a new code invalidates the previous one. I found that out the practical way: the first code I tried to use had expired and came back as <code>OTP_EXPIRED</code>. Put the five-minute limit in the form and in the email copy, because &quot;my code doesn&#39;t work&quot; will otherwise become a support ticket.</p>
<h2>Admin operations need a service account</h2>
<p>This is the design decision I would most want someone to tell me before a migration like this. My admins create users, reset passwords and delete accounts from the app. With Stack, the server secret key allowed all of that. With Better Auth, those endpoints only accept a signed-in session whose user has the Neon role <code>admin</code>.</p>
<p>The tempting fix is to give your organisation admins that role. Do not do that in a multi-tenant app. The Neon role applies to the whole project, not to one tenant, so any organisation admin could call Neon&#39;s admin API directly with their own session cookie and reset the password of a user in another organisation. I checked the opposite case on the spike branch too: a normal user calling <code>/admin/list-users</code> gets <code>YOU_ARE_NOT_ALLOWED_TO_LIST_USERS</code>, which is exactly what you want for everyone except one identity.</p>
<p>That one identity is a dedicated service account, created once by the setup script and given the admin role with <code>neon neon-auth user set-role &lt;id&gt; --roles admin</code>. A server-only module signs in as it, caches the session cookie per server instance, and exposes the handful of operations the app needs:</p>
<pre><code class="language-ts">// File: src/lib/auth/admin.ts
export const setAuthUserPassword = async (userId: string, newPassword: string) =&gt; {
  await adminFetch(&quot;/admin/set-user-password&quot;, {
    method: &quot;POST&quot;,
    body: { userId, newPassword },
  });
};
</code></pre>
<p>Inside <code>adminFetch</code>, every request carries the cached cookie and an <code>Origin</code> header that matches one of the project&#39;s trusted domains, and a 401 triggers one fresh sign-in and a retry. Your app roles stay in your own database, where your tenancy checks already are. The full reasoning, and the pitfalls around it, deserve their own article, so here I only cover what the migration needs.</p>
<h2>Send auth emails through your own mailer</h2>
<p>Neon sends verification and reset emails from a shared sender by default. You have two ways to make them yours, and I used both. Setting a custom SMTP provider on the branch makes Neon&#39;s default emails come from your own sender address. Subscribing to the <code>send.otp</code> webhook goes further: Neon then skips its own email and calls your endpoint with the code, and you send your own template.</p>
<p>The webhook is signed with a detached Ed25519 JWS. The signature covers the timestamp and the raw request body, so you have to verify against the body exactly as received, before any JSON parsing:</p>
<pre><code class="language-ts">// File: src/lib/auth/webhook.ts
const signingInput =
  `${headerB64}.${base64url(`${timestamp}.${base64url(rawBody)}`)}`;

const isValid = crypto.verify(
  null,
  Buffer.from(signingInput),
  crypto.createPublicKey({ key: jwk, format: &quot;jwk&quot; }),
  Buffer.from(signatureB64, &quot;base64url&quot;),
);
</code></pre>
<p>The public key comes from <code>${NEON_AUTH_BASE_URL}/.well-known/jwks.json</code>, matched by the <code>x-neon-signature-kid</code> header, and I reject timestamps older than five minutes. The route reads <code>event_data.otp_code</code> and <code>event_data.otp_type</code>. For <code>forget-password</code> it sends my reset template with the code and a link to the reset page. Drivers with generated alias addresses have no real inbox, so for them the route returns 200 without sending anything; their admin resets their password instead.</p>
<p>Onboarding emails with temporary passwords are not something Neon sends at all, so those moved from Stack&#39;s templates to the app&#39;s existing Brevo mailer. One small but important detail: my mailer copies an admin address on every outgoing email by default, which is fine for delivery notes but not for temporary passwords. The credentials helper passes empty <code>cc</code> and <code>bcc</code> on purpose.</p>
<h2>Migrate the users</h2>
<p>Because password hashes cannot move, &quot;migrating users&quot; means creating a fresh Better Auth account for each existing user and pointing <code>User.authUserId</code> at it. I wrote a script that is a dry run by default and only writes with <code>--apply</code>, and that I could safely run more than once:</p>
<pre><code class="language-ts">// File: src/scripts/migrate-to-neon-auth.ts
const existing = await findAuthUserByEmail(email);

if (existing &amp;&amp; existing.id === user.authUserId) {
  rows.push({ email, action: &quot;already migrated&quot; });
  continue;
}

// ...create the account if needed, then:
await prisma.user.update({ where: { id: user.id }, data: { authUserId } });
</code></pre>
<p>Users with real email addresses get a long random password that nobody knows. With <code>--send-notices</code>, they also receive an email explaining that sign-in was renewed and that they should set a new password through &quot;forgot password&quot;. Users with generated alias emails get a temporary password written to a local file with mode 600, for their admin to hand over. Users who are inactive get an account but no notice, because the email would invite them to a sign-in the app then rejects.</p>
<p>The script uses the same <code>admin.ts</code> and mailer modules as the app, and those import <code>server-only</code>. Run it with <code>npx tsx --conditions react-server</code>, which resolves <code>server-only</code> to its empty build outside Next.js. You also need <code>server-only</code> installed as a real dependency, because plain Node cannot see the copy Next.js bundles internally.</p>
<p>On the spike branch, the first apply created 13 accounts and relinked one, and the second run reported all 14 as &quot;already migrated&quot;. That second run is the real test: during a cutover you want to be able to rerun anything that fails halfway.</p>
<h2>Cutover order that keeps downtime short</h2>
<p>My real migration had a longer login outage than it needed to, because I unlinked Stack during the rehearsal, before the new code was ready. The keys died immediately and production stayed down until the deploy. Knowing that, this is the order I would use, with every step already rehearsed:</p>
<ol>
<li>Have the new code finished and reviewed on a branch, ready to merge. On Vercel, merging to <code>main</code> deploys, so the merge itself is step 5.</li>
<li>Take fresh backups: a new snapshot branch, a new dump and a new mapping CSV.</li>
<li>Unlink Stack. Downtime starts here.</li>
<li>Rename the <code>neon_auth</code> schema and run the setup script on the production branch.</li>
<li>Add the remaining environment variables, then merge and deploy.</li>
<li>Run the migration script, first as a dry run and then with <code>--apply --send-notices</code>.</li>
</ol>
<p>Steps 3 to 5 take minutes when they are scripted. After the deploy, I verified the live site from the outside: the new sign-in form is served, <code>/api/auth/admin/*</code> returns 403, an unsigned webhook gets 401, a real reset code arrives through the webhook with a 200, and every user row is linked to an auth user. Within minutes of the notices going out, the logs showed a real user requesting a reset code.</p>
<p>Keep the legacy data and the Stack environment variables for a week or two before cleaning up. Then drop <code>neon_auth_stack_legacy</code>, delete the snapshot branches, and remove the old variables.</p>
<h2>FAQ</h2>
<p><strong>Can I keep Stack Auth running while I test Better Auth?</strong>
Not in the same Neon project. The provider is locked per project, and enabling Better Auth on any branch fails while Stack is attached. Rehearse everything you can with the CLI and API first, and treat the unlink as the start of your cutover window.</p>
<p><strong>Do users keep their passwords?</strong>
No. Neon states that the hashing is incompatible, so every user gets a new account and sets a new password. If your own user table is the source of truth, their data, roles and history are unaffected; only the credentials change.</p>
<p><strong>Why not just give my admins the Neon admin role?</strong>
Because it applies to the whole project. In a multi-tenant app, an organisation admin with that role could reset passwords of users in other organisations by calling Neon directly. Give the role to one server-side service account and keep app roles in your database.</p>
<p><strong>Why does my sign-in button get stuck after a wrong password?</strong>
<code>@neondatabase/auth</code> 0.5.0-beta throws on failed sign-in instead of returning <code>{ error }</code>. Wrap every auth client call in try/catch and treat a returned error and a thrown error the same way.</p>
<p><strong>How do I roll back if the cutover fails?</strong>
Roll back the deployment to the one you recorded, and restore <code>authUserId</code> from the mapping CSV or restore the whole branch from the snapshot. Because unlinking revoked the Neon-issued Stack keys, a rollback to Stack also needs fresh keys from a claimed Stack project, so decide in advance whether rollback means going back to Stack or fixing forward.</p>
<h2>Conclusion</h2>
<p>Migrating from Stack Auth to Neon Managed Better Auth is less about swapping SDK calls and more about sequencing. Neon allows one auth provider per project, so there is no side-by-side phase. Unlinking Stack revokes its keys on the spot, and the old <code>neon_auth</code> schema has to be moved out of the way before Better Auth can provision. Password hashes do not migrate, so users are re-created and relinked to your own table. And the admin endpoints need a signed-in admin session, which in a multi-tenant app means a service account rather than handing out a project-wide role.</p>
<p>The approach that made this safe was boring on purpose: verified backups, a spike branch where every capability was proven before any code was written, an idempotent setup script, a migration script that is a dry run by default, and a cutover short enough to fit into a few minutes of scripted steps. If you are about to do the same migration, start with the backup section and do not skip the restore test.</p>
<p>Once you have completed the cutover and relinked your users to the newly provisioned Better Auth schema, you will need the day-to-day production machinery to run the application long-term—including proxying <code>/api/auth</code> while blocking admin routes, handling six-digit reset codes, and routing auth emails through signed webhooks. See <a href="/blog/neon-managed-better-auth-nextjs-vercel">Neon Managed Better Auth in Next.js on Vercel: A Production Setup Guide</a> for the complete multi-tenant production architecture.</p>
<p>Let me know in the comments if you have questions, and subscribe for more practical development guides.</p>
<p>Thanks, Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/migrate-stack-auth-to-neon-better-auth</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/migrate-stack-auth-to-neon-better-auth</guid>
            <category><![CDATA[Next.js]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;&lt;em&gt;By Matija. Last updated: 25 September 2026. Tested with Next.js 16.3.6, &lt;code&gt;@neondatabase/auth&lt;/code&gt; 0.5.0-beta, neonctl 6.0.0, Prisma 7 and Postgres 17.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;I recently revisited an internal web application built for a client after they reported an urgent operational issue: they were suddenly unable to invite or onboard new team members. When the app was originally architected, it relied on Stack Auth—the turnkey authentication provider Neon officially backed at launch. However, as Better Auth gained massive adoption across the TypeScript ecosystem (culminating in Vercel&amp;#39;s backing), Neon announced the sunsetting of Stack Auth in favor of Neon Managed Better Auth. With legacy features degrading and unmaintained dependencies threatening onboarding, upgrading wasn&amp;#39;t optional. But there was a catch: Neon enforces exactly one auth provider per project, meaning you cannot run Stack Auth and Better Auth side-by-side during a transition. This guide shares the exact, production-tested steps I took to execute that hard cutover on Next.js, covering the unspoken gotchas—from non-transferable password hashes and schema clashes to admin session workarounds and idempotent user relinking.&lt;/p&gt;
&lt;h2&gt;Why the official migration guide is not enough&lt;/h2&gt;
&lt;p&gt;I recently moved a multi-tenant delivery-note SaaS off legacy Neon Auth. It had been running on Stack Auth (&lt;code&gt;@stackframe/stack&lt;/code&gt;) since Neon launched its auth product, and Neon now points everyone to Managed Better Auth. The official &amp;quot;From Stack Auth (legacy)&amp;quot; guide is a good SDK reference: it shows &lt;code&gt;StackServerApp&lt;/code&gt; becoming &lt;code&gt;createNeonAuth&lt;/code&gt;, &lt;code&gt;useUser&lt;/code&gt; becoming &lt;code&gt;useSession&lt;/code&gt;, &lt;code&gt;&amp;lt;SignIn /&amp;gt;&lt;/code&gt; becoming &lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt;. What it does not tell you is what happens to your users, your admin tooling and your uptime.&lt;/p&gt;
&lt;p&gt;Three facts shaped the whole migration once I found them. First, a Neon project can only have one auth provider, so you cannot enable Better Auth on a branch to test it while production keeps using Stack. Second, Neon states plainly that existing password users cannot be migrated because the hashing algorithms differ, so every user needs a new password. Third, Better Auth&amp;#39;s admin endpoints (create user, set password, change email, delete) only work from a signed-in session whose user has the Neon role &lt;code&gt;admin&lt;/code&gt;, which matters a lot if your app lets organisation admins manage their own users.&lt;/p&gt;
&lt;p&gt;A short aside if you are still on Stack and considering the &amp;quot;eject&amp;quot; route instead: claiming your Stack project gives you the full Stack dashboard, and its email templates are addressed by UUID, not by the friendly names the docs suggest. That works, but you are then running auth on a platform Neon no longer develops. I chose to migrate.&lt;/p&gt;
&lt;p&gt;In this app, the Prisma &lt;code&gt;User&lt;/code&gt; table was already the source of truth for organisation, role and status, and auth only linked to it through a &lt;code&gt;User.authUserId&lt;/code&gt; column. If your app is structured the same way, the migration is mostly about re-pointing that one column. Everything below assumes that shape.&lt;/p&gt;
&lt;h2&gt;Step 1: Back up, then prove the backup restores&lt;/h2&gt;
&lt;p&gt;Do this before you touch any auth setting, because unlinking Stack is not reversible from the Neon side. I made three independent backups and verified each one.&lt;/p&gt;
&lt;p&gt;The fastest restore path is a Neon snapshot branch. It is an instant copy-on-write of the whole database, including the legacy &lt;code&gt;neon_auth.users_sync&lt;/code&gt; table:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# File: terminal
neon branches create --project-id &amp;quot;$NEON_PROJECT_ID&amp;quot; \
  --name pre-better-auth-2026-09-24 --parent main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The second backup is an offline dump that survives even if something goes wrong with the Neon project itself. One gotcha here: my local &lt;code&gt;pg_dump&lt;/code&gt; was version 16 and the server runs Postgres 17, and &lt;code&gt;pg_dump&lt;/code&gt; refuses to dump a newer server. The official Docker image solves that without installing anything:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# File: terminal
docker run --rm --user &amp;quot;$(id -u):$(id -g)&amp;quot; -e PGURL \
  -v ~/backups/app:/backup postgres:17 \
  pg_dump &amp;quot;$PGURL&amp;quot; -Fc --no-owner -f /backup/pre-better-auth.dump
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A backup you have never restored is a hope, not a backup. I restored the dump into a throwaway branch and compared both row counts and an MD5 hash of the table contents against production:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- File: verify-restore.sql
select md5(string_agg(t::text, &amp;#39;|&amp;#39; order by t.id)) from &amp;quot;User&amp;quot; t;
select md5(string_agg(t::text, &amp;#39;|&amp;#39; order by t.id)) from &amp;quot;DeliveryNote&amp;quot; t;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Identical hashes on both sides mean the dump is complete. The third backup is a CSV mapping each Prisma user id to its Stack &lt;code&gt;authUserId&lt;/code&gt;. If you ever need to roll back, that single file turns the database side of the rollback into one &lt;code&gt;UPDATE&lt;/code&gt;. Finally, record the current production deployment URL (&lt;code&gt;vercel ls --prod&lt;/code&gt;) and tag the current commit, so the code side of a rollback is &lt;code&gt;vercel rollback &amp;lt;url&amp;gt;&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If you haven&amp;#39;t yet established isolated development and preview database branches on Neon and Vercel, review our &lt;a href=&quot;/blog/vercel-neon-nextjs-3-tier-setup&quot;&gt;Vercel Neon Setup for Next.js: 3-Tier Enterprise Guide&lt;/a&gt; first. Having clean branch separation ensures your spike tests and production rehearsals never risk live customer records.&lt;/p&gt;
&lt;h2&gt;Step 2: Rehearse on a spike branch&lt;/h2&gt;
&lt;p&gt;Before writing any application code, I checked that every operation the app needs is actually possible, first through the CLI and API and then on a throwaway branch. The Neon CLI (&lt;code&gt;neonctl&lt;/code&gt;) has a &lt;code&gt;neon-auth&lt;/code&gt; command group that covers most of the configuration. I also checked the endpoints against the OpenAPI spec. This is what I found:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Need&lt;/th&gt;
&lt;th&gt;Available via CLI/API?&lt;/th&gt;
&lt;th&gt;How&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Enable Better Auth on a branch&lt;/td&gt;
&lt;td&gt;API only (CLI &lt;code&gt;enable&lt;/code&gt; has no provider flag)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;POST /projects/{id}/branches/{branch}/auth&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Disable public sign-up&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth config email-password update --disable-sign-up&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Use your own SMTP (Brevo in my case)&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth config email-provider update --type standard ...&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Webhooks for auth emails&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth config webhook update ...&lt;/code&gt; or &lt;code&gt;PUT .../auth/webhooks&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Trusted domains&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth domain add &amp;lt;url&amp;gt;&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Create/delete user, set role&lt;/td&gt;
&lt;td&gt;Yes (no password on create)&lt;/td&gt;
&lt;td&gt;&lt;code&gt;neon neon-auth user create&lt;/code&gt;, &lt;code&gt;user set-role &amp;lt;id&amp;gt; --roles admin&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Set a user&amp;#39;s password&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Better Auth &lt;code&gt;/admin/set-user-password&lt;/code&gt;, needs an admin session&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Change a user&amp;#39;s email or name&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Better Auth &lt;code&gt;/admin/update-user&lt;/code&gt;, needs an admin session&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;The last two rows are the important ones. Everything you configure once can be scripted, but the runtime operations your admin UI needs have to go through Better Auth&amp;#39;s admin endpoints, and those need a signed-in admin. I cover how to handle that in the admin section below.&lt;/p&gt;
&lt;p&gt;On the spike branch I then proved the full chain end to end: enabling Better Auth, creating a service account, creating a user with a password, setting a new password, changing an email, deleting the user, disabling sign-up, sending a reset code through my own SMTP, and completing a reset with that code. Only after every step worked did I write application code.&lt;/p&gt;
&lt;h2&gt;&amp;quot;Neon Auth with different auth provider already exists for this project&amp;quot;&lt;/h2&gt;
&lt;p&gt;This is the error you will get the first time you try to enable Better Auth on any branch of a project that still has Stack attached. It does not matter that you are on a spike branch: the provider is locked at project level.&lt;/p&gt;
&lt;p&gt;The fix is to unlink Stack from the project:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# File: terminal
neon neon-auth disable --project-id &amp;quot;$NEON_PROJECT_ID&amp;quot; --branch main
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Leave out &lt;code&gt;--delete-data&lt;/code&gt;; it defaults to false, and your &lt;code&gt;neon_auth.users_sync&lt;/code&gt; rows stay in place. What the docs do not warn you about is the side effect. The Stack publishable and server keys that Neon issued are revoked immediately, and your production login breaks at that moment. Right after unlinking, a direct call to the Stack API returned this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;INVALID_PUBLISHABLE_CLIENT_KEY: The publishable key is not valid for the project &amp;quot;…&amp;quot;. Does the project and/or the key exist?
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is why the order of the cutover matters so much, and I come back to it at the end. Plan for this step to be the start of your downtime window, not something you do on a quiet afternoon days before the deploy.&lt;/p&gt;
&lt;h2&gt;&amp;quot;The &lt;code&gt;neon_auth&lt;/code&gt; schema already exists and cannot be automatically provisioned&amp;quot;&lt;/h2&gt;
&lt;p&gt;With Stack unlinked, the next attempt to enable Better Auth fails again, this time because the old Stack sync table still lives in the &lt;code&gt;neon_auth&lt;/code&gt; schema and Better Auth wants that schema name for its own tables. The error text suggests dropping it. I renamed it instead, so the data stays available until I am sure I will not need it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- File: rename-legacy-schema.sql
ALTER SCHEMA neon_auth RENAME TO neon_auth_stack_legacy;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then enable Better Auth through the API. The CLI&amp;#39;s &lt;code&gt;enable&lt;/code&gt; command has no way to choose the provider, so a direct request is the reliable path:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;# File: terminal
curl -X POST &amp;quot;https://console.neon.tech/api/v2/projects/$NEON_PROJECT_ID/branches/$BRANCH_ID/auth&amp;quot; \
  -H &amp;quot;Authorization: Bearer $NEON_API_KEY&amp;quot; -H &amp;quot;Content-Type: application/json&amp;quot; \
  -d &amp;#39;{&amp;quot;auth_provider&amp;quot;:&amp;quot;better_auth&amp;quot;,&amp;quot;database_name&amp;quot;:&amp;quot;neondb&amp;quot;}&amp;#39;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The response contains your new &lt;code&gt;base_url&lt;/code&gt;. Better Auth now creates its tables (&lt;code&gt;user&lt;/code&gt;, &lt;code&gt;account&lt;/code&gt;, &lt;code&gt;session&lt;/code&gt;, &lt;code&gt;verification&lt;/code&gt; and a few more) in your own database under &lt;code&gt;neon_auth&lt;/code&gt;, which means you can join against them with plain SQL. If your project was installed through the Vercel Marketplace, the integration also adds &lt;code&gt;NEON_AUTH_BASE_URL&lt;/code&gt; to your production environment variables automatically. Check that it matches before you add your own.&lt;/p&gt;
&lt;p&gt;I wrapped all of the branch configuration (schema rename, enable, trusted domains, SMTP, service account, disabling sign-up and webhook) into one idempotent shell script. Being able to rerun it is not a luxury, as you will see in the gotchas below.&lt;/p&gt;
&lt;h2&gt;Swap the server and client SDK&lt;/h2&gt;
&lt;p&gt;The code side is the part the official guide covers well, so I will focus on what I did differently. On the server, one &lt;code&gt;createNeonAuth&lt;/code&gt; instance gives you session reads and the API proxy handler:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/server.ts
import { createNeonAuth } from &amp;quot;@neondatabase/auth/next/server&amp;quot;;

import { requireEnv } from &amp;quot;./env&amp;quot;;

export const auth = createNeonAuth({
  baseUrl: requireEnv(&amp;quot;NEON_AUTH_BASE_URL&amp;quot;),
  cookies: { secret: requireEnv(&amp;quot;NEON_AUTH_COOKIE_SECRET&amp;quot;) },
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The cookie secret must be at least 32 characters; &lt;code&gt;openssl rand -base64 32&lt;/code&gt; is fine. On the client, &lt;code&gt;createAuthClient()&lt;/code&gt; from &lt;code&gt;@neondatabase/auth/next&lt;/code&gt; takes no arguments and talks to your own &lt;code&gt;/api/auth&lt;/code&gt; route. It already includes the email-OTP plugin, which matters for password reset later.&lt;/p&gt;
&lt;p&gt;The proxy route mounts Neon&amp;#39;s handler. I wrapped it so the browser can never reach the admin endpoints through my domain, because only the server should ever call those:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/app/api/auth/[...path]/route.ts
import { auth } from &amp;quot;@/lib/auth/server&amp;quot;;

const handlers = auth.handler();

type RouteContext = { params: Promise&amp;lt;{ path: string[] }&amp;gt; };
type Handler = (request: Request, context: RouteContext) =&amp;gt; Promise&amp;lt;Response&amp;gt;;

const blockAdminPaths =
  (handler: Handler): Handler =&amp;gt;
  async (request, context) =&amp;gt; {
    const { path } = await context.params;
    if (path[0] === &amp;quot;admin&amp;quot;) {
      return Response.json({ message: &amp;quot;Forbidden&amp;quot; }, { status: 403 });
    }
    return handler(request, context);
  };

export const GET = blockAdminPaths(handlers.GET);
export const POST = blockAdminPaths(handlers.POST);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The session layer is where keeping your own user table pays off. My existing &lt;code&gt;getCurrentAuthContext&lt;/code&gt; and &lt;code&gt;requireAuthContext&lt;/code&gt; helpers stayed exactly the same. Only the function that asks &amp;quot;who is signed in?&amp;quot; changed:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/session.ts
export const getAuthenticatedUser = cache(
  async (): Promise&amp;lt;AuthenticatedUser | null&amp;gt; =&amp;gt; {
    const { data } = await auth.getSession();
    const user = data?.user;
    if (!user) return null;
    return { id: user.id, email: user.email, name: user.name ?? null };
  },
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Every layout and server action kept calling &lt;code&gt;requireAuthContext()&lt;/code&gt; as before. The layouts already enforce roles and redirect drivers and admins to their own areas, so no route guards had to change. While doing this I also found that the app&amp;#39;s root-level &lt;code&gt;proxy.ts&lt;/code&gt; had never run at all: with the app living in &lt;code&gt;src/app&lt;/code&gt;, Next.js only picks up &lt;code&gt;src/proxy.ts&lt;/code&gt;. I deleted it rather than switch it on halfway through a migration.&lt;/p&gt;
&lt;h2&gt;Sign-in and password reset forms&lt;/h2&gt;
&lt;p&gt;I replaced Stack&amp;#39;s &lt;code&gt;&amp;lt;SignIn /&amp;gt;&lt;/code&gt; with a small form of my own rather than &lt;code&gt;&amp;lt;AuthView /&amp;gt;&lt;/code&gt;, because the app is in Slovenian and uses Sonner toasts for all feedback. Better Auth&amp;#39;s client normally returns &lt;code&gt;{ data, error }&lt;/code&gt;, and the Neon types say the same. In practice, &lt;code&gt;@neondatabase/auth&lt;/code&gt; 0.5.0-beta throws on a failed sign-in, so my first version left the button stuck on its loading label after a wrong password. The fix is to handle both styles:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/app/prijava/_components/sign-in-form.tsx
try {
  const { error } = await authClient.signIn.email({ email, password });
  if (error) throw error;
} catch (error) {
  toast.error(getAuthErrorMessage(error, &amp;quot;Prijava ni uspela. Poskusite znova.&amp;quot;));
  setIsPending(false);
  return;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The thrown value is a Supabase-style &lt;code&gt;AuthError&lt;/code&gt; with a message such as &amp;quot;Invalid email or password&amp;quot;, so my message helper maps both &lt;code&gt;code&lt;/code&gt; values and known messages to translated text.&lt;/p&gt;
&lt;p&gt;Password reset in Managed Better Auth uses one-time codes by default, not links. The user asks for a code with &lt;code&gt;authClient.forgetPassword.emailOtp({ email })&lt;/code&gt;, receives six digits, and submits them with &lt;code&gt;authClient.emailOtp.resetPassword({ email, otp, password })&lt;/code&gt;. The code expires after five minutes, and requesting a new code invalidates the previous one. I found that out the practical way: the first code I tried to use had expired and came back as &lt;code&gt;OTP_EXPIRED&lt;/code&gt;. Put the five-minute limit in the form and in the email copy, because &amp;quot;my code doesn&amp;#39;t work&amp;quot; will otherwise become a support ticket.&lt;/p&gt;
&lt;h2&gt;Admin operations need a service account&lt;/h2&gt;
&lt;p&gt;This is the design decision I would most want someone to tell me before a migration like this. My admins create users, reset passwords and delete accounts from the app. With Stack, the server secret key allowed all of that. With Better Auth, those endpoints only accept a signed-in session whose user has the Neon role &lt;code&gt;admin&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;The tempting fix is to give your organisation admins that role. Do not do that in a multi-tenant app. The Neon role applies to the whole project, not to one tenant, so any organisation admin could call Neon&amp;#39;s admin API directly with their own session cookie and reset the password of a user in another organisation. I checked the opposite case on the spike branch too: a normal user calling &lt;code&gt;/admin/list-users&lt;/code&gt; gets &lt;code&gt;YOU_ARE_NOT_ALLOWED_TO_LIST_USERS&lt;/code&gt;, which is exactly what you want for everyone except one identity.&lt;/p&gt;
&lt;p&gt;That one identity is a dedicated service account, created once by the setup script and given the admin role with &lt;code&gt;neon neon-auth user set-role &amp;lt;id&amp;gt; --roles admin&lt;/code&gt;. A server-only module signs in as it, caches the session cookie per server instance, and exposes the handful of operations the app needs:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/admin.ts
export const setAuthUserPassword = async (userId: string, newPassword: string) =&amp;gt; {
  await adminFetch(&amp;quot;/admin/set-user-password&amp;quot;, {
    method: &amp;quot;POST&amp;quot;,
    body: { userId, newPassword },
  });
};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Inside &lt;code&gt;adminFetch&lt;/code&gt;, every request carries the cached cookie and an &lt;code&gt;Origin&lt;/code&gt; header that matches one of the project&amp;#39;s trusted domains, and a 401 triggers one fresh sign-in and a retry. Your app roles stay in your own database, where your tenancy checks already are. The full reasoning, and the pitfalls around it, deserve their own article, so here I only cover what the migration needs.&lt;/p&gt;
&lt;h2&gt;Send auth emails through your own mailer&lt;/h2&gt;
&lt;p&gt;Neon sends verification and reset emails from a shared sender by default. You have two ways to make them yours, and I used both. Setting a custom SMTP provider on the branch makes Neon&amp;#39;s default emails come from your own sender address. Subscribing to the &lt;code&gt;send.otp&lt;/code&gt; webhook goes further: Neon then skips its own email and calls your endpoint with the code, and you send your own template.&lt;/p&gt;
&lt;p&gt;The webhook is signed with a detached Ed25519 JWS. The signature covers the timestamp and the raw request body, so you have to verify against the body exactly as received, before any JSON parsing:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/lib/auth/webhook.ts
const signingInput =
  `${headerB64}.${base64url(`${timestamp}.${base64url(rawBody)}`)}`;

const isValid = crypto.verify(
  null,
  Buffer.from(signingInput),
  crypto.createPublicKey({ key: jwk, format: &amp;quot;jwk&amp;quot; }),
  Buffer.from(signatureB64, &amp;quot;base64url&amp;quot;),
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The public key comes from &lt;code&gt;${NEON_AUTH_BASE_URL}/.well-known/jwks.json&lt;/code&gt;, matched by the &lt;code&gt;x-neon-signature-kid&lt;/code&gt; header, and I reject timestamps older than five minutes. The route reads &lt;code&gt;event_data.otp_code&lt;/code&gt; and &lt;code&gt;event_data.otp_type&lt;/code&gt;. For &lt;code&gt;forget-password&lt;/code&gt; it sends my reset template with the code and a link to the reset page. Drivers with generated alias addresses have no real inbox, so for them the route returns 200 without sending anything; their admin resets their password instead.&lt;/p&gt;
&lt;p&gt;Onboarding emails with temporary passwords are not something Neon sends at all, so those moved from Stack&amp;#39;s templates to the app&amp;#39;s existing Brevo mailer. One small but important detail: my mailer copies an admin address on every outgoing email by default, which is fine for delivery notes but not for temporary passwords. The credentials helper passes empty &lt;code&gt;cc&lt;/code&gt; and &lt;code&gt;bcc&lt;/code&gt; on purpose.&lt;/p&gt;
&lt;h2&gt;Migrate the users&lt;/h2&gt;
&lt;p&gt;Because password hashes cannot move, &amp;quot;migrating users&amp;quot; means creating a fresh Better Auth account for each existing user and pointing &lt;code&gt;User.authUserId&lt;/code&gt; at it. I wrote a script that is a dry run by default and only writes with &lt;code&gt;--apply&lt;/code&gt;, and that I could safely run more than once:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ts&quot;&gt;// File: src/scripts/migrate-to-neon-auth.ts
const existing = await findAuthUserByEmail(email);

if (existing &amp;amp;&amp;amp; existing.id === user.authUserId) {
  rows.push({ email, action: &amp;quot;already migrated&amp;quot; });
  continue;
}

// ...create the account if needed, then:
await prisma.user.update({ where: { id: user.id }, data: { authUserId } });
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Users with real email addresses get a long random password that nobody knows. With &lt;code&gt;--send-notices&lt;/code&gt;, they also receive an email explaining that sign-in was renewed and that they should set a new password through &amp;quot;forgot password&amp;quot;. Users with generated alias emails get a temporary password written to a local file with mode 600, for their admin to hand over. Users who are inactive get an account but no notice, because the email would invite them to a sign-in the app then rejects.&lt;/p&gt;
&lt;p&gt;The script uses the same &lt;code&gt;admin.ts&lt;/code&gt; and mailer modules as the app, and those import &lt;code&gt;server-only&lt;/code&gt;. Run it with &lt;code&gt;npx tsx --conditions react-server&lt;/code&gt;, which resolves &lt;code&gt;server-only&lt;/code&gt; to its empty build outside Next.js. You also need &lt;code&gt;server-only&lt;/code&gt; installed as a real dependency, because plain Node cannot see the copy Next.js bundles internally.&lt;/p&gt;
&lt;p&gt;On the spike branch, the first apply created 13 accounts and relinked one, and the second run reported all 14 as &amp;quot;already migrated&amp;quot;. That second run is the real test: during a cutover you want to be able to rerun anything that fails halfway.&lt;/p&gt;
&lt;h2&gt;Cutover order that keeps downtime short&lt;/h2&gt;
&lt;p&gt;My real migration had a longer login outage than it needed to, because I unlinked Stack during the rehearsal, before the new code was ready. The keys died immediately and production stayed down until the deploy. Knowing that, this is the order I would use, with every step already rehearsed:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Have the new code finished and reviewed on a branch, ready to merge. On Vercel, merging to &lt;code&gt;main&lt;/code&gt; deploys, so the merge itself is step 5.&lt;/li&gt;
&lt;li&gt;Take fresh backups: a new snapshot branch, a new dump and a new mapping CSV.&lt;/li&gt;
&lt;li&gt;Unlink Stack. Downtime starts here.&lt;/li&gt;
&lt;li&gt;Rename the &lt;code&gt;neon_auth&lt;/code&gt; schema and run the setup script on the production branch.&lt;/li&gt;
&lt;li&gt;Add the remaining environment variables, then merge and deploy.&lt;/li&gt;
&lt;li&gt;Run the migration script, first as a dry run and then with &lt;code&gt;--apply --send-notices&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Steps 3 to 5 take minutes when they are scripted. After the deploy, I verified the live site from the outside: the new sign-in form is served, &lt;code&gt;/api/auth/admin/*&lt;/code&gt; returns 403, an unsigned webhook gets 401, a real reset code arrives through the webhook with a 200, and every user row is linked to an auth user. Within minutes of the notices going out, the logs showed a real user requesting a reset code.&lt;/p&gt;
&lt;p&gt;Keep the legacy data and the Stack environment variables for a week or two before cleaning up. Then drop &lt;code&gt;neon_auth_stack_legacy&lt;/code&gt;, delete the snapshot branches, and remove the old variables.&lt;/p&gt;
&lt;h2&gt;FAQ&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Can I keep Stack Auth running while I test Better Auth?&lt;/strong&gt;
Not in the same Neon project. The provider is locked per project, and enabling Better Auth on any branch fails while Stack is attached. Rehearse everything you can with the CLI and API first, and treat the unlink as the start of your cutover window.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Do users keep their passwords?&lt;/strong&gt;
No. Neon states that the hashing is incompatible, so every user gets a new account and sets a new password. If your own user table is the source of truth, their data, roles and history are unaffected; only the credentials change.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why not just give my admins the Neon admin role?&lt;/strong&gt;
Because it applies to the whole project. In a multi-tenant app, an organisation admin with that role could reset passwords of users in other organisations by calling Neon directly. Give the role to one server-side service account and keep app roles in your database.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Why does my sign-in button get stuck after a wrong password?&lt;/strong&gt;
&lt;code&gt;@neondatabase/auth&lt;/code&gt; 0.5.0-beta throws on failed sign-in instead of returning &lt;code&gt;{ error }&lt;/code&gt;. Wrap every auth client call in try/catch and treat a returned error and a thrown error the same way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;How do I roll back if the cutover fails?&lt;/strong&gt;
Roll back the deployment to the one you recorded, and restore &lt;code&gt;authUserId&lt;/code&gt; from the mapping CSV or restore the whole branch from the snapshot. Because unlinking revoked the Neon-issued Stack keys, a rollback to Stack also needs fresh keys from a claimed Stack project, so decide in advance whether rollback means going back to Stack or fixing forward.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Migrating from Stack Auth to Neon Managed Better Auth is less about swapping SDK calls and more about sequencing. Neon allows one auth provider per project, so there is no side-by-side phase. Unlinking Stack revokes its keys on the spot, and the old &lt;code&gt;neon_auth&lt;/code&gt; schema has to be moved out of the way before Better Auth can provision. Password hashes do not migrate, so users are re-created and relinked to your own table. And the admin endpoints need a signed-in admin session, which in a multi-tenant app means a service account rather than handing out a project-wide role.&lt;/p&gt;
&lt;p&gt;The approach that made this safe was boring on purpose: verified backups, a spike branch where every capability was proven before any code was written, an idempotent setup script, a migration script that is a dry run by default, and a cutover short enough to fit into a few minutes of scripted steps. If you are about to do the same migration, start with the backup section and do not skip the restore test.&lt;/p&gt;
&lt;p&gt;Once you have completed the cutover and relinked your users to the newly provisioned Better Auth schema, you will need the day-to-day production machinery to run the application long-term—including proxying &lt;code&gt;/api/auth&lt;/code&gt; while blocking admin routes, handling six-digit reset codes, and routing auth emails through signed webhooks. See &lt;a href=&quot;/blog/neon-managed-better-auth-nextjs-vercel&quot;&gt;Neon Managed Better Auth in Next.js on Vercel: A Production Setup Guide&lt;/a&gt; for the complete multi-tenant production architecture.&lt;/p&gt;
&lt;p&gt;Let me know in the comments if you have questions, and subscribe for more practical development guides.&lt;/p&gt;
&lt;p&gt;Thanks, Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/migrate-stack-auth-to-neon-better-auth"/>
        </item>
        <item>
            <title><![CDATA[MCP Authentication: Why Remote MCP Servers Need OAuth]]></title>
            <description><![CDATA[<p>While I haven&#39;t written extensively about the Model Context Protocol (MCP) in standalone pieces, I&#39;ve spent the past year embedding custom MCP servers into Next.js and Payload CMS across client production environments (such as our <a href="/blog/build-mcp-server-nextjs">Next.js MCP Server Guide</a>). Recently, I tackled a project requiring a lightweight, standalone backend using Hono and needed to expose remote MCP access to it.</p>
<p>The initial intuition for most developers—myself included—is to wrap a few tool definitions in a route, throw a static API key or bearer token check in front, and call it secure.</p>
<p>But the moment you connect a remote MCP server to modern AI hosts like Claude.ai or ChatGPT, that mental model shatters: neither client prompts for a static key. Instead, they probe the endpoint unauthenticated, expecting RFC 9728 OAuth discovery headers. Here is what I learned about how remote MCP authorization actually functions, why static keys fail with AI clients, and how to wire standard OAuth discovery and CORS exposure in Hono.</p>
<hr>
<h2>What It Is</h2>
<p>Remote MCP authentication is an automated, standards-based discovery and authorization handshake between an AI agent and your API, governed primarily by RFC 8414 and RFC 9728.</p>
<p>When you connect a modern AI client like Claude Desktop or ChatGPT to a remote MCP endpoint over Streamable HTTP, the client does not expect the human operator to manually paste secret keys into a form. Instead, the agent initiates an unauthenticated probe. Your server is expected to reject this probe with a standard <code>401 Unauthorized</code> challenge that contains a <code>resource_metadata</code> URI. The client follows this link, discovers your authorization server endpoints, dynamically registers itself as an OAuth application (RFC 7591), and directs the user through an authorization code flow with PKCE before ever exchanging a single MCP protocol frame.</p>
<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    actor User as User / Operator
    participant Client as AI Client (Claude / ChatGPT)
    participant MCP as Remote MCP Endpoint (/api/mcp)
    participant Auth as Authorization Server

    Client-&gt;&gt;MCP: 1. Unauthenticated Probe (GET /api/mcp)
    MCP--&gt;&gt;Client: 2. 401 Unauthorized + WWW-Authenticate: resource_metadata=&quot;...&quot;
    Client-&gt;&gt;Auth: 3. Discover Endpoints (GET /.well-known/oauth-protected-resource)
    Auth--&gt;&gt;Client: 4. Returns Auth &amp; Token URLs
    Client-&gt;&gt;Auth: 5. Dynamic Client Registration (RFC 7591)
    Auth--&gt;&gt;Client: 6. Issues client_id
    Client-&gt;&gt;User: 7. Open Browser Consent Screen (PKCE)
    User-&gt;&gt;Auth: 8. Authorizes Permissions
    Auth--&gt;&gt;Client: 9. Returns Authorization Code + iss
    Client-&gt;&gt;Auth: 10. Exchange Code for Access Token
    Auth--&gt;&gt;Client: 11. Bearer Token (User-Scoped)
    Client-&gt;&gt;MCP: 12. Authorized MCP Request (Authorization: Bearer &lt;token&gt;)
    MCP--&gt;&gt;Client: 13. Streamable HTTP / MCP Session Established
</code></pre>
<hr>
<h2>The Mental Model: The Valet and the Hotel Concierge</h2>
<p>Think of a static API key like giving a delivery driver your master building key: it works, but it gives unconditional access, cannot be easily scoped per user session, and requires manual out-of-band setup.</p>
<p>The MCP OAuth discovery pattern works more like a hotel concierge checking in a valet. When the valet (the AI client) arrives at the garage gate (<code>/api/mcp</code>), the guard does not say &quot;go away&quot;; the guard hands them a card pointing to the concierge desk (<code>/.well-known/oauth-protected-resource</code>). The valet walks over to the desk, registers their company name dynamically, gets temporary visitor credentials, and asks you (the owner) to sign a slip approving access. Only after you sign does the valet return to the gate with a validated badge. The gatekeeper checks the badge, confirms which room it belongs to, and unlocks only that room&#39;s parking bay.</p>
<pre><code class="language-mermaid">flowchart TD
    subgraph StaticKey[&quot;Static API Key (Delivery Master Key)&quot;]
        direction TB
        K1[&quot;Client holds master secret&quot;] --&gt; K2[&quot;Unconditional access to entire system&quot;]
        K2 --&gt; K3[&quot;Zero session scoping &amp; high blast radius&quot;]
        K3 --&gt; K4[&quot;Requires manual, out-of-band key pasting&quot;]
    end

    subgraph OAuthValet[&quot;OAuth Discovery (Valet &amp; Concierge)&quot;]
        direction TB
        V1[&quot;Valet arrives unauthenticated at gate (/api/mcp)&quot;] --&gt; V2[&quot;Gatekeeper hands concierge card (401 + resource_metadata)&quot;]
        V2 --&gt; V3[&quot;Valet registers at concierge desk (RFC 7591 Dynamic Registration)&quot;]
        V3 --&gt; V4[&quot;Guest signs authorization slip (Browser PKCE Consent)&quot;]
        V4 --&gt; V5[&quot;Valet receives room-scoped temporary badge (Bearer Token)&quot;]
        V5 --&gt; V6[&quot;Gatekeeper validates badge and unlocks only assigned bay&quot;]
    end
</code></pre>
<hr>
<h2>When To Use It</h2>
<p>You should implement the full OAuth 2.0 discovery contract whenever your MCP server runs on a public domain and serves external agents such as Claude.ai, ChatGPT Custom Actions, or multi-tenant web clients.</p>
<h3>Public AI Agent Integrations (Claude &amp; ChatGPT)</h3>
<p>When integrating with cloud-hosted AI hosts like Claude.ai or ChatGPT, OAuth discovery is the only interoperable authentication path. These platforms do not prompt end-users to enter static database credentials into text fields. Instead, their web clients expect standard RFC discovery headers so they can safely initiate an OAuth popup and retrieve a scoped token directly on behalf of the user.</p>
<h3>Multi-Tenant SaaS with Scoped User Data</h3>
<p>In multi-tenant SaaS environments where tools manipulate private user data—like an image hosting service where uploads must be tagged to the authenticated user&#39;s gallery—OAuth is mandatory. It eliminates the need for users to manually generate and copy database secret keys into third-party chat interfaces. Because the flow terminates in an authorization code grant tied to your primary authentication system (such as Better Auth), every downstream tool invocation automatically inherits the authenticated user&#39;s identity.</p>
<h3>Protocol Handshake Nuances vs Local Stdio</h3>
<p>If you are building on Next.js or looking for a full implementation of dynamic client registration, Upstash Redis token storage, and custom HTML consent screens for Claude Web and CLI, read our companion guide <a href="/blog/oauth-mcp-server-claude">OAuth for MCP Server: Complete Guide to Protecting Claude</a>. While that walkthrough handles Redis session persistence, this guide focuses on the protocol handshake nuances—RFC 9728 resource metadata, Streamable HTTP challenges, and Hono CORS exposure—that remote endpoints require when serving both Claude and ChatGPT.</p>
<p>For more on the architectural risks of static tokens and how multi-user authorization differs across AI clients, see <a href="/blog/mcp-server-integration-claude-vs-openai">Building Secure Multi-User MCP Servers: Claude vs OpenAI&#39;s Authentication Gap</a>.</p>
<hr>
<h2>When NOT To Use It</h2>
<p>Do not implement this flow if your MCP server is strictly local and runs over <code>stdio</code> inside a desktop environment like Cursor or Claude Desktop on your personal laptop.</p>
<p>In local process-spawned integrations, the client and the server share the same process boundary or operating system user. Adding OAuth discovery here introduces unnecessary network round-trips, database tables, and browser redirects for zero security gain. Similarly, if your MCP server is intended solely for internal server-to-server cron jobs or automated CI/CD runners, a permanent personal API key or a static master token passed directly in the <code>Authorization</code> header is significantly simpler to maintain and debug.</p>
<hr>
<h2>Gotchas &amp; Common Mistakes</h2>
<h3>1. The Missing <code>resource_metadata</code> Challenge Header</h3>
<p>The most common failure happens on the very first HTTP request. When an unauthorized client hits your MCP route, returning a simple JSON <code>{ &quot;error&quot;: &quot;Unauthorized&quot; }</code> with a 401 status code causes Claude or ChatGPT to fail immediately with a generic connection error.</p>
<p>AI clients do not assume OAuth is supported unless your <code>401 Unauthorized</code> response explicitly broadcasts where to find the Protected Resource Metadata per RFC 9728. In Hono, you must supply the <code>WWW-Authenticate</code> header containing the exact metadata URL.</p>
<pre><code class="language-typescript">// apps/api/src/mcp/routes.ts
if (!identity &amp;&amp; !config.publicMode) {
  const resourceMetadataUrl = `${config.publicBaseUrl}/.well-known/oauth-protected-resource/api/mcp`;
  const challenge = `Bearer error=&quot;invalid_token&quot;, error_description=&quot;Unauthorized&quot;, resource_metadata=&quot;${resourceMetadataUrl}&quot;`;

  return c.json({ error: &#39;Unauthorized&#39; }, 401, {
    &#39;WWW-Authenticate&#39;: challenge,
  });
}
</code></pre>
<p>If that header or the <code>resource_metadata</code> parameter is missing, the client has no way to locate your authorization server and terminates the handshake.</p>
<h3>2. Failing to Expose CORS Headers</h3>
<p>Even if your server responds with the proper <code>WWW-Authenticate</code> header, web-based clients running in the browser will drop it if your CORS configuration does not explicitly expose it.</p>
<p>Standard browser security prevents client-side scripts from reading response headers unless they are safelisted in <code>Access-Control-Expose-Headers</code>. When setting up your Hono middleware, you must expose both the authentication challenge and MCP protocol headers.</p>
<pre><code class="language-typescript">// apps/api/src/index.ts
app.use(&#39;*&#39;, cors({
  origin: (origin) =&gt; origin || &#39;*&#39;,
  allowHeaders: [&#39;Content-Type&#39;, &#39;Authorization&#39;, &#39;Range&#39;, &#39;Mcp-Session-Id&#39;, &#39;Mcp-Protocol-Version&#39;],
  exposeHeaders: [&#39;Mcp-Session-Id&#39;, &#39;WWW-Authenticate&#39;, &#39;Last-Event-Id&#39;, &#39;Mcp-Protocol-Version&#39;],
  credentials: true,
}));
</code></pre>
<p>Omitting <code>WWW-Authenticate</code> from <code>exposeHeaders</code> leaves web clients blind to the discovery URL.</p>
<h3>3. Missing the RFC 9207 <code>iss</code> Parameter on Redirects</h3>
<p>Once the user approves the authorization prompt in their browser, your server redirects back to the client&#39;s <code>redirect_uri</code> with an authorization <code>code</code>. Modern MCP clients enforce RFC 9207 to prevent authorization code injection attacks.</p>
<p>RFC 9207 requires that the authorization server append an <code>iss</code> (issuer) query parameter to the redirect URL matching the issuer URL declared in your metadata. If your authentication library redirects without this parameter, clients like Claude will reject the code exchange during the final step.</p>
<pre><code class="language-typescript">// apps/api/src/index.ts
app.use(&#39;/api/auth/mcp/authorize&#39;, async (c, next) =&gt; {
  await next();
  const location = c.res.headers.get(&#39;Location&#39;);
  if (c.res.status &gt;= 300 &amp;&amp; c.res.status &lt; 400 &amp;&amp; location &amp;&amp; !location.startsWith(&#39;/&#39;)) {
    const issuer = config.publicBaseUrl.replace(/\/$/, &#39;&#39;);
    const redirectUrl = new URL(location);
    if (!redirectUrl.searchParams.has(&#39;iss&#39;)) {
      redirectUrl.searchParams.set(&#39;iss&#39;, issuer);
      c.res.headers.set(&#39;Location&#39;, redirectUrl.href);
    }
  }
});
</code></pre>
<p>Capturing the redirect response and appending the verified issuer parameter ensures strict compliance with client security verifiers.</p>
<hr>
<h2>Conclusion</h2>
<p>Building a production-ready remote MCP server requires treating authentication as an automated protocol conversation rather than a static header check. When an AI agent connects to your backend, it relies on RFC 9728 protected resource discovery, RFC 8414 metadata, dynamic registration, and RFC 9207 redirect binding to establish trust autonomously.</p>
<p>Reach for full OAuth discovery when your MCP tools operate on user-scoped data in cloud environments, and stick to simple personal tokens or <code>stdio</code> when running local desktop tools. </p>
<p>If you have questions or ran into a different gotcha, drop a comment below. And if you found this useful, subscribe for more.</p>
<p>Thanks,
Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/why-remote-mcp-servers-need-more-than-api-key</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/why-remote-mcp-servers-need-more-than-api-key</guid>
            <category><![CDATA[AI]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;While I haven&amp;#39;t written extensively about the Model Context Protocol (MCP) in standalone pieces, I&amp;#39;ve spent the past year embedding custom MCP servers into Next.js and Payload CMS across client production environments (such as our &lt;a href=&quot;/blog/build-mcp-server-nextjs&quot;&gt;Next.js MCP Server Guide&lt;/a&gt;). Recently, I tackled a project requiring a lightweight, standalone backend using Hono and needed to expose remote MCP access to it.&lt;/p&gt;
&lt;p&gt;The initial intuition for most developers—myself included—is to wrap a few tool definitions in a route, throw a static API key or bearer token check in front, and call it secure.&lt;/p&gt;
&lt;p&gt;But the moment you connect a remote MCP server to modern AI hosts like Claude.ai or ChatGPT, that mental model shatters: neither client prompts for a static key. Instead, they probe the endpoint unauthenticated, expecting RFC 9728 OAuth discovery headers. Here is what I learned about how remote MCP authorization actually functions, why static keys fail with AI clients, and how to wire standard OAuth discovery and CORS exposure in Hono.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;What It Is&lt;/h2&gt;
&lt;p&gt;Remote MCP authentication is an automated, standards-based discovery and authorization handshake between an AI agent and your API, governed primarily by RFC 8414 and RFC 9728.&lt;/p&gt;
&lt;p&gt;When you connect a modern AI client like Claude Desktop or ChatGPT to a remote MCP endpoint over Streamable HTTP, the client does not expect the human operator to manually paste secret keys into a form. Instead, the agent initiates an unauthenticated probe. Your server is expected to reject this probe with a standard &lt;code&gt;401 Unauthorized&lt;/code&gt; challenge that contains a &lt;code&gt;resource_metadata&lt;/code&gt; URI. The client follows this link, discovers your authorization server endpoints, dynamically registers itself as an OAuth application (RFC 7591), and directs the user through an authorization code flow with PKCE before ever exchanging a single MCP protocol frame.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
    autonumber
    actor User as User / Operator
    participant Client as AI Client (Claude / ChatGPT)
    participant MCP as Remote MCP Endpoint (/api/mcp)
    participant Auth as Authorization Server

    Client-&amp;gt;&amp;gt;MCP: 1. Unauthenticated Probe (GET /api/mcp)
    MCP--&amp;gt;&amp;gt;Client: 2. 401 Unauthorized + WWW-Authenticate: resource_metadata=&amp;quot;...&amp;quot;
    Client-&amp;gt;&amp;gt;Auth: 3. Discover Endpoints (GET /.well-known/oauth-protected-resource)
    Auth--&amp;gt;&amp;gt;Client: 4. Returns Auth &amp;amp; Token URLs
    Client-&amp;gt;&amp;gt;Auth: 5. Dynamic Client Registration (RFC 7591)
    Auth--&amp;gt;&amp;gt;Client: 6. Issues client_id
    Client-&amp;gt;&amp;gt;User: 7. Open Browser Consent Screen (PKCE)
    User-&amp;gt;&amp;gt;Auth: 8. Authorizes Permissions
    Auth--&amp;gt;&amp;gt;Client: 9. Returns Authorization Code + iss
    Client-&amp;gt;&amp;gt;Auth: 10. Exchange Code for Access Token
    Auth--&amp;gt;&amp;gt;Client: 11. Bearer Token (User-Scoped)
    Client-&amp;gt;&amp;gt;MCP: 12. Authorized MCP Request (Authorization: Bearer &amp;lt;token&amp;gt;)
    MCP--&amp;gt;&amp;gt;Client: 13. Streamable HTTP / MCP Session Established
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h2&gt;The Mental Model: The Valet and the Hotel Concierge&lt;/h2&gt;
&lt;p&gt;Think of a static API key like giving a delivery driver your master building key: it works, but it gives unconditional access, cannot be easily scoped per user session, and requires manual out-of-band setup.&lt;/p&gt;
&lt;p&gt;The MCP OAuth discovery pattern works more like a hotel concierge checking in a valet. When the valet (the AI client) arrives at the garage gate (&lt;code&gt;/api/mcp&lt;/code&gt;), the guard does not say &amp;quot;go away&amp;quot;; the guard hands them a card pointing to the concierge desk (&lt;code&gt;/.well-known/oauth-protected-resource&lt;/code&gt;). The valet walks over to the desk, registers their company name dynamically, gets temporary visitor credentials, and asks you (the owner) to sign a slip approving access. Only after you sign does the valet return to the gate with a validated badge. The gatekeeper checks the badge, confirms which room it belongs to, and unlocks only that room&amp;#39;s parking bay.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart TD
    subgraph StaticKey[&amp;quot;Static API Key (Delivery Master Key)&amp;quot;]
        direction TB
        K1[&amp;quot;Client holds master secret&amp;quot;] --&amp;gt; K2[&amp;quot;Unconditional access to entire system&amp;quot;]
        K2 --&amp;gt; K3[&amp;quot;Zero session scoping &amp;amp; high blast radius&amp;quot;]
        K3 --&amp;gt; K4[&amp;quot;Requires manual, out-of-band key pasting&amp;quot;]
    end

    subgraph OAuthValet[&amp;quot;OAuth Discovery (Valet &amp;amp; Concierge)&amp;quot;]
        direction TB
        V1[&amp;quot;Valet arrives unauthenticated at gate (/api/mcp)&amp;quot;] --&amp;gt; V2[&amp;quot;Gatekeeper hands concierge card (401 + resource_metadata)&amp;quot;]
        V2 --&amp;gt; V3[&amp;quot;Valet registers at concierge desk (RFC 7591 Dynamic Registration)&amp;quot;]
        V3 --&amp;gt; V4[&amp;quot;Guest signs authorization slip (Browser PKCE Consent)&amp;quot;]
        V4 --&amp;gt; V5[&amp;quot;Valet receives room-scoped temporary badge (Bearer Token)&amp;quot;]
        V5 --&amp;gt; V6[&amp;quot;Gatekeeper validates badge and unlocks only assigned bay&amp;quot;]
    end
&lt;/code&gt;&lt;/pre&gt;
&lt;hr&gt;
&lt;h2&gt;When To Use It&lt;/h2&gt;
&lt;p&gt;You should implement the full OAuth 2.0 discovery contract whenever your MCP server runs on a public domain and serves external agents such as Claude.ai, ChatGPT Custom Actions, or multi-tenant web clients.&lt;/p&gt;
&lt;h3&gt;Public AI Agent Integrations (Claude &amp;amp; ChatGPT)&lt;/h3&gt;
&lt;p&gt;When integrating with cloud-hosted AI hosts like Claude.ai or ChatGPT, OAuth discovery is the only interoperable authentication path. These platforms do not prompt end-users to enter static database credentials into text fields. Instead, their web clients expect standard RFC discovery headers so they can safely initiate an OAuth popup and retrieve a scoped token directly on behalf of the user.&lt;/p&gt;
&lt;h3&gt;Multi-Tenant SaaS with Scoped User Data&lt;/h3&gt;
&lt;p&gt;In multi-tenant SaaS environments where tools manipulate private user data—like an image hosting service where uploads must be tagged to the authenticated user&amp;#39;s gallery—OAuth is mandatory. It eliminates the need for users to manually generate and copy database secret keys into third-party chat interfaces. Because the flow terminates in an authorization code grant tied to your primary authentication system (such as Better Auth), every downstream tool invocation automatically inherits the authenticated user&amp;#39;s identity.&lt;/p&gt;
&lt;h3&gt;Protocol Handshake Nuances vs Local Stdio&lt;/h3&gt;
&lt;p&gt;If you are building on Next.js or looking for a full implementation of dynamic client registration, Upstash Redis token storage, and custom HTML consent screens for Claude Web and CLI, read our companion guide &lt;a href=&quot;/blog/oauth-mcp-server-claude&quot;&gt;OAuth for MCP Server: Complete Guide to Protecting Claude&lt;/a&gt;. While that walkthrough handles Redis session persistence, this guide focuses on the protocol handshake nuances—RFC 9728 resource metadata, Streamable HTTP challenges, and Hono CORS exposure—that remote endpoints require when serving both Claude and ChatGPT.&lt;/p&gt;
&lt;p&gt;For more on the architectural risks of static tokens and how multi-user authorization differs across AI clients, see &lt;a href=&quot;/blog/mcp-server-integration-claude-vs-openai&quot;&gt;Building Secure Multi-User MCP Servers: Claude vs OpenAI&amp;#39;s Authentication Gap&lt;/a&gt;.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;When NOT To Use It&lt;/h2&gt;
&lt;p&gt;Do not implement this flow if your MCP server is strictly local and runs over &lt;code&gt;stdio&lt;/code&gt; inside a desktop environment like Cursor or Claude Desktop on your personal laptop.&lt;/p&gt;
&lt;p&gt;In local process-spawned integrations, the client and the server share the same process boundary or operating system user. Adding OAuth discovery here introduces unnecessary network round-trips, database tables, and browser redirects for zero security gain. Similarly, if your MCP server is intended solely for internal server-to-server cron jobs or automated CI/CD runners, a permanent personal API key or a static master token passed directly in the &lt;code&gt;Authorization&lt;/code&gt; header is significantly simpler to maintain and debug.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Gotchas &amp;amp; Common Mistakes&lt;/h2&gt;
&lt;h3&gt;1. The Missing &lt;code&gt;resource_metadata&lt;/code&gt; Challenge Header&lt;/h3&gt;
&lt;p&gt;The most common failure happens on the very first HTTP request. When an unauthorized client hits your MCP route, returning a simple JSON &lt;code&gt;{ &amp;quot;error&amp;quot;: &amp;quot;Unauthorized&amp;quot; }&lt;/code&gt; with a 401 status code causes Claude or ChatGPT to fail immediately with a generic connection error.&lt;/p&gt;
&lt;p&gt;AI clients do not assume OAuth is supported unless your &lt;code&gt;401 Unauthorized&lt;/code&gt; response explicitly broadcasts where to find the Protected Resource Metadata per RFC 9728. In Hono, you must supply the &lt;code&gt;WWW-Authenticate&lt;/code&gt; header containing the exact metadata URL.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// apps/api/src/mcp/routes.ts
if (!identity &amp;amp;&amp;amp; !config.publicMode) {
  const resourceMetadataUrl = `${config.publicBaseUrl}/.well-known/oauth-protected-resource/api/mcp`;
  const challenge = `Bearer error=&amp;quot;invalid_token&amp;quot;, error_description=&amp;quot;Unauthorized&amp;quot;, resource_metadata=&amp;quot;${resourceMetadataUrl}&amp;quot;`;

  return c.json({ error: &amp;#39;Unauthorized&amp;#39; }, 401, {
    &amp;#39;WWW-Authenticate&amp;#39;: challenge,
  });
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If that header or the &lt;code&gt;resource_metadata&lt;/code&gt; parameter is missing, the client has no way to locate your authorization server and terminates the handshake.&lt;/p&gt;
&lt;h3&gt;2. Failing to Expose CORS Headers&lt;/h3&gt;
&lt;p&gt;Even if your server responds with the proper &lt;code&gt;WWW-Authenticate&lt;/code&gt; header, web-based clients running in the browser will drop it if your CORS configuration does not explicitly expose it.&lt;/p&gt;
&lt;p&gt;Standard browser security prevents client-side scripts from reading response headers unless they are safelisted in &lt;code&gt;Access-Control-Expose-Headers&lt;/code&gt;. When setting up your Hono middleware, you must expose both the authentication challenge and MCP protocol headers.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// apps/api/src/index.ts
app.use(&amp;#39;*&amp;#39;, cors({
  origin: (origin) =&amp;gt; origin || &amp;#39;*&amp;#39;,
  allowHeaders: [&amp;#39;Content-Type&amp;#39;, &amp;#39;Authorization&amp;#39;, &amp;#39;Range&amp;#39;, &amp;#39;Mcp-Session-Id&amp;#39;, &amp;#39;Mcp-Protocol-Version&amp;#39;],
  exposeHeaders: [&amp;#39;Mcp-Session-Id&amp;#39;, &amp;#39;WWW-Authenticate&amp;#39;, &amp;#39;Last-Event-Id&amp;#39;, &amp;#39;Mcp-Protocol-Version&amp;#39;],
  credentials: true,
}));
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Omitting &lt;code&gt;WWW-Authenticate&lt;/code&gt; from &lt;code&gt;exposeHeaders&lt;/code&gt; leaves web clients blind to the discovery URL.&lt;/p&gt;
&lt;h3&gt;3. Missing the RFC 9207 &lt;code&gt;iss&lt;/code&gt; Parameter on Redirects&lt;/h3&gt;
&lt;p&gt;Once the user approves the authorization prompt in their browser, your server redirects back to the client&amp;#39;s &lt;code&gt;redirect_uri&lt;/code&gt; with an authorization &lt;code&gt;code&lt;/code&gt;. Modern MCP clients enforce RFC 9207 to prevent authorization code injection attacks.&lt;/p&gt;
&lt;p&gt;RFC 9207 requires that the authorization server append an &lt;code&gt;iss&lt;/code&gt; (issuer) query parameter to the redirect URL matching the issuer URL declared in your metadata. If your authentication library redirects without this parameter, clients like Claude will reject the code exchange during the final step.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// apps/api/src/index.ts
app.use(&amp;#39;/api/auth/mcp/authorize&amp;#39;, async (c, next) =&amp;gt; {
  await next();
  const location = c.res.headers.get(&amp;#39;Location&amp;#39;);
  if (c.res.status &amp;gt;= 300 &amp;amp;&amp;amp; c.res.status &amp;lt; 400 &amp;amp;&amp;amp; location &amp;amp;&amp;amp; !location.startsWith(&amp;#39;/&amp;#39;)) {
    const issuer = config.publicBaseUrl.replace(/\/$/, &amp;#39;&amp;#39;);
    const redirectUrl = new URL(location);
    if (!redirectUrl.searchParams.has(&amp;#39;iss&amp;#39;)) {
      redirectUrl.searchParams.set(&amp;#39;iss&amp;#39;, issuer);
      c.res.headers.set(&amp;#39;Location&amp;#39;, redirectUrl.href);
    }
  }
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Capturing the redirect response and appending the verified issuer parameter ensures strict compliance with client security verifiers.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Building a production-ready remote MCP server requires treating authentication as an automated protocol conversation rather than a static header check. When an AI agent connects to your backend, it relies on RFC 9728 protected resource discovery, RFC 8414 metadata, dynamic registration, and RFC 9207 redirect binding to establish trust autonomously.&lt;/p&gt;
&lt;p&gt;Reach for full OAuth discovery when your MCP tools operate on user-scoped data in cloud environments, and stick to simple personal tokens or &lt;code&gt;stdio&lt;/code&gt; when running local desktop tools. &lt;/p&gt;
&lt;p&gt;If you have questions or ran into a different gotcha, drop a comment below. And if you found this useful, subscribe for more.&lt;/p&gt;
&lt;p&gt;Thanks,
Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/why-remote-mcp-servers-need-more-than-api-key"/>
        </item>
        <item>
            <title><![CDATA[Radix to Base UI Migration Guide: Why Codemods Fail]]></title>
            <description><![CDATA[<p>I recently spun up a new project with shadcn and was genuinely surprised to see the notice announcing Base UI as the new default primitive library. Like many developers, the vast majority of my client projects over the last couple of years have been running on Radix UI. Naturally, my first instinct was to look into porting an existing project over. I found several community codemods and upgrade scripts promising automated one-click translation, but the moment I tested them on a real codebase, the reality set in: documentation codemods work fine on pristine starter templates, but they fail completely when faced with real-world tailored components. This guide covers what the Radix to Base UI shift in shadcn actually entails, why automated codemods fall short on customized primitives, and how to execute a safe, progressive upgrade.</p>
<h3>What It Is</h3>
<p>When shadcn announced Base UI as the default component library, the immediate reaction across the ecosystem was to look for a migration script. But shadcn is not an npm package you import as an immutable dependency; it is code copied directly into your repository. You own the component files in your project. You add variants, change class names, wire custom handlers, and inject project-specific helpers.</p>
<p>Because of this architecture, a traditional AST codemod cannot reliably transform your code. A codemod works well on pristine templates, but it fails the moment it encounters human customizations. Instead of shipping a brittle script, shadcn introduced two mechanisms: multi-base support in the CLI for initializing or reinstalling styled primitives, and a dedicated AI migration skill that reads both implementations, compares the diffs against pristine golden pairs, and carries your customizations forward progressively.</p>
<h3>The Mental Model: Tailoring a Bespoke Suit</h3>
<p>Think of your shadcn component directory like a collection of tailored suits rather than off-the-rack clothing. Radix provided the initial fabric and pattern. Over months of building your application, you hemmed the pants, adjusted the sleeves, and added custom pockets. </p>
<p>A traditional codemod acts like an automated cutting machine programmed strictly for the original factory pattern. If you run it over a tailored suit, it cuts straight through your custom seams and ruins the garment. To change the underlying fabric to Base UI without destroying the tailoring, you must measure your specific alterations, understand how the new material behaves, and apply the adjustments seam by seam.</p>
<p>In code, this difference is immediately visible at the boundary between primitive wrappers and consumer call sites. In Radix, polymorphism is driven by the <code>asChild</code> prop:</p>
<pre><code class="language-tsx">// src/components/ui/button.tsx (Radix)
const Comp = asChild ? Slot : &quot;button&quot;
return &lt;Comp className={cn(buttonVariants({ variant, size }))} {...props} /&gt;
</code></pre>
<p>In Base UI, that entire mechanism is replaced by the <code>render</code> prop:</p>
<pre><code class="language-tsx">// src/components/ui/button.tsx (Base UI)
return (
  &lt;ButtonPrimitive
    render={render}
    className={cn(buttonVariants({ variant, size }))}
    {...props}
  /&gt;
)
</code></pre>
<p>Because <code>asChild</code> expects a single React element passed as a child while <code>render</code> accepts an element or a render function directly on the prop, changing the primitive under the hood ripples out to every call site in your application that relied on the previous convention.</p>
<h3>When To Use It</h3>
<p>Reaching for Base UI or switching your project base makes sense in very specific situations.</p>
<p>If you are bootstrapping a new project or building a greenfield feature set where you want modern primitive features like built-in field validation states, native transition hooks, or unstyled positioning that separates the viewport from the popup box, Base UI is the right default. </p>
<p>It is also appropriate if you are maintaining an existing project and decide to execute a deliberate, progressive component migration using the official skill. In that scenario, you migrate foundational leaf primitives first, such as buttons and labels, and verify that your application typechecks and renders correctly after each step.</p>
<p>Before undertaking a primitive upgrade across your UI layer, make sure you actually need to own the underlying behavior. If you are weighing whether to adopt headless primitives like Radix and Base UI or keep hand-rolling interaction logic, read <a href="/blog/headless-ui-primitives-when-to-own-ui-behavior">Headless UI Primitives: When to Own UI Behavior Today</a>. It outlines a pragmatic framework for identifying invisible interaction risks—such as focus traps, keyboard navigation, and ARIA state—before committing engineering time to component architecture.</p>
<h3>When NOT To Use It</h3>
<p>You should avoid migrating to Base UI if your production application is already stable, thoroughly tested, and running on Radix primitives without issue. </p>
<p>Radix UI is not deprecated. It remains officially supported by shadcn, and its primitives have been battle-tested across millions of production interfaces. If you have an established app with dozens of complex dialogs, navigation menus, and form controls, migrating simply because the default changed adds risk with very little tangible benefit to your end users.</p>
<p>Equally important, never attempt to migrate by deleting your <code>components/ui</code> folder and running an unconditional CLI re-initialization. Doing so wipes out all custom variants, resets accessibility adjustments, and immediately introduces breaking type mismatches across every page in your repository.</p>
<h3>Gotchas and Common Mistakes</h3>
<p>These come from migrating a real Next.js app with <code>shadcn apply --preset</code>. Most were not caught by the TypeScript compiler.</p>
<h4>A wrong <code>aliases.utils</code> creates bare <code>&quot;cn&quot;</code> imports</h4>
<p>The CLI writes <code>cn</code> imports based on <code>aliases.utils</code> in <code>components.json</code>. In this repo the alias pointed at <code>@/lib/utils</code>, but <code>cn</code> actually lived in <code>@/lib/helpers/utils</code>. The CLI could not find it, so it generated <code>from &quot;cn&quot;</code> (the bare npm package) imports in 51 files, added a <code>cn</code> dependency, and created a new <code>src/lib/utils.ts</code>:</p>
<pre><code class="language-typescript">// src/lib/utils.ts (created by the CLI)
export { cn } from &quot;cn&quot;
</code></pre>
<p>It did not overwrite an existing file here, but nothing guarantees that if your <code>utils.ts</code> already holds real helpers. Set the alias to the true location before running <code>apply</code>:</p>
<pre><code class="language-json">&quot;aliases&quot;: {
  &quot;utils&quot;: &quot;@/lib/helpers/utils&quot;
}
</code></pre>
<p>If it already happened, rewrite the <code>from &quot;cn&quot;</code> imports to your real path, delete the stray file, and remove the <code>cn</code> package. Either way, read your git diff before you commit.</p>
<h4>Switching the base goes through <code>style</code></h4>
<p>A top-level <code>&quot;base&quot;: &quot;base&quot;</code> key made <code>components.json</code> invalid. What worked was setting <code>style</code> to <code>base-nova</code>, after which <code>shadcn info</code> reported <code>base: base</code>. Then <code>shadcn apply --preset &lt;code&gt;</code> rewrote the style again (to <code>base-mira</code> in our case).</p>
<pre><code class="language-json">&quot;style&quot;: &quot;base-nova&quot;
</code></pre>
<h4>A preset changes more than the base</h4>
<p>Applying a preset is not only a Radix-to-Base-UI swap. In this repo the same commit also changed the icon library from lucide to phosphor, <code>baseColor</code> from neutral to zinc, <code>react-day-picker</code> from 9.14 to 10.0.2, and <code>shadcn</code> to 4.21, and it added <code>@base-ui/react</code>. Expect icon imports and calendar props to change along with the primitives, and review those diffs separately.</p>
<h4><code>&quot;use client&quot;</code> failures only show up in a real build</h4>
<p>The regenerated <code>breadcrumb.tsx</code> uses <code>useRender</code> and shipped without a <code>&quot;use client&quot;</code> directive. Rendered from a server page, it crashed prerendering with <code>createContext is not a function</code>. The opposite mistake also bites: adding <code>&quot;use client&quot;</code> to <code>button.tsx</code> broke every <code>buttonVariants()</code> call made from a server component, because the export becomes a client reference.</p>
<pre><code class="language-tsx">// breadcrumb.tsx: wrappers built on useRender need it
&quot;use client&quot;

import { useRender } from &quot;@base-ui/react/use-render&quot;
</code></pre>
<p>The rule that worked: add the directive to <code>useRender</code> wrappers (badge, breadcrumb, button-group, item), and never to files whose exports, like <code>buttonVariants</code>, are called on the server. <code>tsc</code> passed in both broken states. The failures only appeared in a Vercel build.</p>
<h4>Select needs <code>items</code></h4>
<p>Base UI&#39;s Select maps values to labels through an <code>items</code> prop. Without it, the trigger displays the raw value instead of the label. <code>onValueChange</code> also receives <code>string | null</code>, so your handlers need to deal with <code>null</code>.</p>
<pre><code class="language-tsx">&lt;Select
  value={currentLocale}
  items={languages.map((l) =&gt; ({ label: l.code.toUpperCase(), value: l.code }))}
  onValueChange={(value) =&gt; value !== null &amp;&amp; handleLanguageChange(value)}
&gt;
</code></pre>
<h4>Other runtime-only breaks</h4>
<p>These compiled fine or failed only at runtime:</p>
<ul>
<li><code>data-[state=open]</code> selectors on collapsible and accordion triggers become <code>data-[panel-open]</code> (<code>group-data-[panel-open]:rotate-180</code> in our chevrons).</li>
<li><code>Accordion type=&quot;single&quot; collapsible</code> is gone. Remove those props.</li>
<li><code>form.tsx</code> was not regenerated, so it still imported Radix <code>Slot</code> and <code>Label</code>. <code>FormControl</code> needed a rewrite around <code>React.cloneElement</code>.</li>
<li>When <code>render</code> is not a native button (for example <code>render={&lt;Link href=&quot;/contact&quot; /&gt;}</code>), add <code>nativeButton={false}</code>. This does not apply to <code>HoverCardTrigger</code>.</li>
</ul>
<pre><code class="language-tsx">&lt;Button render={&lt;Link href=&quot;/contact&quot; /&gt;} nativeButton={false}&gt;
  Contact
&lt;/Button&gt;
</code></pre>
<h4>Menus and overlays split into parts</h4>
<p>Radix handles collisions, positioning, and content in a single <code>Content</code> component. Base UI splits this into <code>Portal</code>, <code>Positioner</code>, and <code>Popup</code>. If you swap wrappers without accounting for how your app passes alignment offsets or portal containers, dropdowns can compile but render detached from their triggers.</p>
<h4>Converting <code>asChild</code> call sites</h4>
<p>We converted 61 <code>asChild</code> call sites to <code>render</code> with a small script built on the TypeScript compiler API. It handled the single-child case (<code>&lt;Button asChild&gt;&lt;Link /&gt;&lt;/Button&gt;</code>) mechanically. Only a conditional-child case in <code>cart-sheet.tsx</code> needed manual work. This fits the article&#39;s theme: scripts work when the shape is regular, and the irregular cases are yours to fix.</p>
<h3>A Migration Checklist</h3>
<ol>
<li>Create a branch and back up <code>src/components/ui</code>.</li>
<li>Find your real customizations with <code>git log -- src/components/ui</code>. In our case only <code>breadcrumb.tsx</code> had local edits (accessibility commits), and reading the log was faster than diffing every component.</li>
<li>Fix <code>aliases.utils</code> in <code>components.json</code> so it points at the file that exports <code>cn</code>.</li>
<li>Set the base through <code>style</code> (for example <code>base-nova</code>).</li>
<li>Run <code>shadcn apply --preset &lt;code&gt;</code> and review the full diff, including the icon library, base color, and dependency changes.</li>
<li>Repair any bare <code>&quot;cn&quot;</code> imports, delete the stray <code>utils.ts</code>, and remove the <code>cn</code> package.</li>
<li>Convert <code>asChild</code> to <code>render</code>, adding <code>nativeButton={false}</code> where the target is not a button.</li>
<li>Fix Select <code>items</code>, Accordion props, ToggleGroup props, and <code>data-state</code> selectors.</li>
<li>Add <code>&quot;use client&quot;</code> to <code>useRender</code> wrappers only.</li>
<li>Run <code>npx tsc --noEmit</code>, then deploy a preview. Typechecking alone missed the <code>use client</code> failures.</li>
</ol>
<h3>Conclusion</h3>
<p>The transition from Radix UI to Base UI in shadcn represents a fundamental shift in how modern headless components are structured, but it does not mean your existing codebase needs an emergency rewrite. You own your code, which makes automated codemods impractical. Reach for Base UI when building new projects or when a specific primitive feature solves an active problem, and leave your stable Radix foundations alone if your application is already shipping reliably.</p>
<p>If you do migrate, the cost depends on how much you have customized. A small, mostly stock <code>components/ui</code> (ours had one customized file) took about an afternoon. A heavily customized one is where the real cost sits, because every local edit has to be found and carried forward by hand.</p>
<p>If you have questions or ran into a different gotcha, drop a comment below. And if you found this useful, subscribe for more.</p>
<p>Thanks,
Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/radix-to-base-ui-in-shadcn</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/radix-to-base-ui-in-shadcn</guid>
            <category><![CDATA[React]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;I recently spun up a new project with shadcn and was genuinely surprised to see the notice announcing Base UI as the new default primitive library. Like many developers, the vast majority of my client projects over the last couple of years have been running on Radix UI. Naturally, my first instinct was to look into porting an existing project over. I found several community codemods and upgrade scripts promising automated one-click translation, but the moment I tested them on a real codebase, the reality set in: documentation codemods work fine on pristine starter templates, but they fail completely when faced with real-world tailored components. This guide covers what the Radix to Base UI shift in shadcn actually entails, why automated codemods fall short on customized primitives, and how to execute a safe, progressive upgrade.&lt;/p&gt;
&lt;h3&gt;What It Is&lt;/h3&gt;
&lt;p&gt;When shadcn announced Base UI as the default component library, the immediate reaction across the ecosystem was to look for a migration script. But shadcn is not an npm package you import as an immutable dependency; it is code copied directly into your repository. You own the component files in your project. You add variants, change class names, wire custom handlers, and inject project-specific helpers.&lt;/p&gt;
&lt;p&gt;Because of this architecture, a traditional AST codemod cannot reliably transform your code. A codemod works well on pristine templates, but it fails the moment it encounters human customizations. Instead of shipping a brittle script, shadcn introduced two mechanisms: multi-base support in the CLI for initializing or reinstalling styled primitives, and a dedicated AI migration skill that reads both implementations, compares the diffs against pristine golden pairs, and carries your customizations forward progressively.&lt;/p&gt;
&lt;h3&gt;The Mental Model: Tailoring a Bespoke Suit&lt;/h3&gt;
&lt;p&gt;Think of your shadcn component directory like a collection of tailored suits rather than off-the-rack clothing. Radix provided the initial fabric and pattern. Over months of building your application, you hemmed the pants, adjusted the sleeves, and added custom pockets. &lt;/p&gt;
&lt;p&gt;A traditional codemod acts like an automated cutting machine programmed strictly for the original factory pattern. If you run it over a tailored suit, it cuts straight through your custom seams and ruins the garment. To change the underlying fabric to Base UI without destroying the tailoring, you must measure your specific alterations, understand how the new material behaves, and apply the adjustments seam by seam.&lt;/p&gt;
&lt;p&gt;In code, this difference is immediately visible at the boundary between primitive wrappers and consumer call sites. In Radix, polymorphism is driven by the &lt;code&gt;asChild&lt;/code&gt; prop:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;// src/components/ui/button.tsx (Radix)
const Comp = asChild ? Slot : &amp;quot;button&amp;quot;
return &amp;lt;Comp className={cn(buttonVariants({ variant, size }))} {...props} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In Base UI, that entire mechanism is replaced by the &lt;code&gt;render&lt;/code&gt; prop:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;// src/components/ui/button.tsx (Base UI)
return (
  &amp;lt;ButtonPrimitive
    render={render}
    className={cn(buttonVariants({ variant, size }))}
    {...props}
  /&amp;gt;
)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Because &lt;code&gt;asChild&lt;/code&gt; expects a single React element passed as a child while &lt;code&gt;render&lt;/code&gt; accepts an element or a render function directly on the prop, changing the primitive under the hood ripples out to every call site in your application that relied on the previous convention.&lt;/p&gt;
&lt;h3&gt;When To Use It&lt;/h3&gt;
&lt;p&gt;Reaching for Base UI or switching your project base makes sense in very specific situations.&lt;/p&gt;
&lt;p&gt;If you are bootstrapping a new project or building a greenfield feature set where you want modern primitive features like built-in field validation states, native transition hooks, or unstyled positioning that separates the viewport from the popup box, Base UI is the right default. &lt;/p&gt;
&lt;p&gt;It is also appropriate if you are maintaining an existing project and decide to execute a deliberate, progressive component migration using the official skill. In that scenario, you migrate foundational leaf primitives first, such as buttons and labels, and verify that your application typechecks and renders correctly after each step.&lt;/p&gt;
&lt;p&gt;Before undertaking a primitive upgrade across your UI layer, make sure you actually need to own the underlying behavior. If you are weighing whether to adopt headless primitives like Radix and Base UI or keep hand-rolling interaction logic, read &lt;a href=&quot;/blog/headless-ui-primitives-when-to-own-ui-behavior&quot;&gt;Headless UI Primitives: When to Own UI Behavior Today&lt;/a&gt;. It outlines a pragmatic framework for identifying invisible interaction risks—such as focus traps, keyboard navigation, and ARIA state—before committing engineering time to component architecture.&lt;/p&gt;
&lt;h3&gt;When NOT To Use It&lt;/h3&gt;
&lt;p&gt;You should avoid migrating to Base UI if your production application is already stable, thoroughly tested, and running on Radix primitives without issue. &lt;/p&gt;
&lt;p&gt;Radix UI is not deprecated. It remains officially supported by shadcn, and its primitives have been battle-tested across millions of production interfaces. If you have an established app with dozens of complex dialogs, navigation menus, and form controls, migrating simply because the default changed adds risk with very little tangible benefit to your end users.&lt;/p&gt;
&lt;p&gt;Equally important, never attempt to migrate by deleting your &lt;code&gt;components/ui&lt;/code&gt; folder and running an unconditional CLI re-initialization. Doing so wipes out all custom variants, resets accessibility adjustments, and immediately introduces breaking type mismatches across every page in your repository.&lt;/p&gt;
&lt;h3&gt;Gotchas and Common Mistakes&lt;/h3&gt;
&lt;p&gt;These come from migrating a real Next.js app with &lt;code&gt;shadcn apply --preset&lt;/code&gt;. Most were not caught by the TypeScript compiler.&lt;/p&gt;
&lt;h4&gt;A wrong &lt;code&gt;aliases.utils&lt;/code&gt; creates bare &lt;code&gt;&amp;quot;cn&amp;quot;&lt;/code&gt; imports&lt;/h4&gt;
&lt;p&gt;The CLI writes &lt;code&gt;cn&lt;/code&gt; imports based on &lt;code&gt;aliases.utils&lt;/code&gt; in &lt;code&gt;components.json&lt;/code&gt;. In this repo the alias pointed at &lt;code&gt;@/lib/utils&lt;/code&gt;, but &lt;code&gt;cn&lt;/code&gt; actually lived in &lt;code&gt;@/lib/helpers/utils&lt;/code&gt;. The CLI could not find it, so it generated &lt;code&gt;from &amp;quot;cn&amp;quot;&lt;/code&gt; (the bare npm package) imports in 51 files, added a &lt;code&gt;cn&lt;/code&gt; dependency, and created a new &lt;code&gt;src/lib/utils.ts&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// src/lib/utils.ts (created by the CLI)
export { cn } from &amp;quot;cn&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It did not overwrite an existing file here, but nothing guarantees that if your &lt;code&gt;utils.ts&lt;/code&gt; already holds real helpers. Set the alias to the true location before running &lt;code&gt;apply&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;&amp;quot;aliases&amp;quot;: {
  &amp;quot;utils&amp;quot;: &amp;quot;@/lib/helpers/utils&amp;quot;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If it already happened, rewrite the &lt;code&gt;from &amp;quot;cn&amp;quot;&lt;/code&gt; imports to your real path, delete the stray file, and remove the &lt;code&gt;cn&lt;/code&gt; package. Either way, read your git diff before you commit.&lt;/p&gt;
&lt;h4&gt;Switching the base goes through &lt;code&gt;style&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;A top-level &lt;code&gt;&amp;quot;base&amp;quot;: &amp;quot;base&amp;quot;&lt;/code&gt; key made &lt;code&gt;components.json&lt;/code&gt; invalid. What worked was setting &lt;code&gt;style&lt;/code&gt; to &lt;code&gt;base-nova&lt;/code&gt;, after which &lt;code&gt;shadcn info&lt;/code&gt; reported &lt;code&gt;base: base&lt;/code&gt;. Then &lt;code&gt;shadcn apply --preset &amp;lt;code&amp;gt;&lt;/code&gt; rewrote the style again (to &lt;code&gt;base-mira&lt;/code&gt; in our case).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;&amp;quot;style&amp;quot;: &amp;quot;base-nova&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;A preset changes more than the base&lt;/h4&gt;
&lt;p&gt;Applying a preset is not only a Radix-to-Base-UI swap. In this repo the same commit also changed the icon library from lucide to phosphor, &lt;code&gt;baseColor&lt;/code&gt; from neutral to zinc, &lt;code&gt;react-day-picker&lt;/code&gt; from 9.14 to 10.0.2, and &lt;code&gt;shadcn&lt;/code&gt; to 4.21, and it added &lt;code&gt;@base-ui/react&lt;/code&gt;. Expect icon imports and calendar props to change along with the primitives, and review those diffs separately.&lt;/p&gt;
&lt;h4&gt;&lt;code&gt;&amp;quot;use client&amp;quot;&lt;/code&gt; failures only show up in a real build&lt;/h4&gt;
&lt;p&gt;The regenerated &lt;code&gt;breadcrumb.tsx&lt;/code&gt; uses &lt;code&gt;useRender&lt;/code&gt; and shipped without a &lt;code&gt;&amp;quot;use client&amp;quot;&lt;/code&gt; directive. Rendered from a server page, it crashed prerendering with &lt;code&gt;createContext is not a function&lt;/code&gt;. The opposite mistake also bites: adding &lt;code&gt;&amp;quot;use client&amp;quot;&lt;/code&gt; to &lt;code&gt;button.tsx&lt;/code&gt; broke every &lt;code&gt;buttonVariants()&lt;/code&gt; call made from a server component, because the export becomes a client reference.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;// breadcrumb.tsx: wrappers built on useRender need it
&amp;quot;use client&amp;quot;

import { useRender } from &amp;quot;@base-ui/react/use-render&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The rule that worked: add the directive to &lt;code&gt;useRender&lt;/code&gt; wrappers (badge, breadcrumb, button-group, item), and never to files whose exports, like &lt;code&gt;buttonVariants&lt;/code&gt;, are called on the server. &lt;code&gt;tsc&lt;/code&gt; passed in both broken states. The failures only appeared in a Vercel build.&lt;/p&gt;
&lt;h4&gt;Select needs &lt;code&gt;items&lt;/code&gt;&lt;/h4&gt;
&lt;p&gt;Base UI&amp;#39;s Select maps values to labels through an &lt;code&gt;items&lt;/code&gt; prop. Without it, the trigger displays the raw value instead of the label. &lt;code&gt;onValueChange&lt;/code&gt; also receives &lt;code&gt;string | null&lt;/code&gt;, so your handlers need to deal with &lt;code&gt;null&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;&amp;lt;Select
  value={currentLocale}
  items={languages.map((l) =&amp;gt; ({ label: l.code.toUpperCase(), value: l.code }))}
  onValueChange={(value) =&amp;gt; value !== null &amp;amp;&amp;amp; handleLanguageChange(value)}
&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Other runtime-only breaks&lt;/h4&gt;
&lt;p&gt;These compiled fine or failed only at runtime:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;data-[state=open]&lt;/code&gt; selectors on collapsible and accordion triggers become &lt;code&gt;data-[panel-open]&lt;/code&gt; (&lt;code&gt;group-data-[panel-open]:rotate-180&lt;/code&gt; in our chevrons).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Accordion type=&amp;quot;single&amp;quot; collapsible&lt;/code&gt; is gone. Remove those props.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;form.tsx&lt;/code&gt; was not regenerated, so it still imported Radix &lt;code&gt;Slot&lt;/code&gt; and &lt;code&gt;Label&lt;/code&gt;. &lt;code&gt;FormControl&lt;/code&gt; needed a rewrite around &lt;code&gt;React.cloneElement&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;When &lt;code&gt;render&lt;/code&gt; is not a native button (for example &lt;code&gt;render={&amp;lt;Link href=&amp;quot;/contact&amp;quot; /&amp;gt;}&lt;/code&gt;), add &lt;code&gt;nativeButton={false}&lt;/code&gt;. This does not apply to &lt;code&gt;HoverCardTrigger&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code class=&quot;language-tsx&quot;&gt;&amp;lt;Button render={&amp;lt;Link href=&amp;quot;/contact&amp;quot; /&amp;gt;} nativeButton={false}&amp;gt;
  Contact
&amp;lt;/Button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;h4&gt;Menus and overlays split into parts&lt;/h4&gt;
&lt;p&gt;Radix handles collisions, positioning, and content in a single &lt;code&gt;Content&lt;/code&gt; component. Base UI splits this into &lt;code&gt;Portal&lt;/code&gt;, &lt;code&gt;Positioner&lt;/code&gt;, and &lt;code&gt;Popup&lt;/code&gt;. If you swap wrappers without accounting for how your app passes alignment offsets or portal containers, dropdowns can compile but render detached from their triggers.&lt;/p&gt;
&lt;h4&gt;Converting &lt;code&gt;asChild&lt;/code&gt; call sites&lt;/h4&gt;
&lt;p&gt;We converted 61 &lt;code&gt;asChild&lt;/code&gt; call sites to &lt;code&gt;render&lt;/code&gt; with a small script built on the TypeScript compiler API. It handled the single-child case (&lt;code&gt;&amp;lt;Button asChild&amp;gt;&amp;lt;Link /&amp;gt;&amp;lt;/Button&amp;gt;&lt;/code&gt;) mechanically. Only a conditional-child case in &lt;code&gt;cart-sheet.tsx&lt;/code&gt; needed manual work. This fits the article&amp;#39;s theme: scripts work when the shape is regular, and the irregular cases are yours to fix.&lt;/p&gt;
&lt;h3&gt;A Migration Checklist&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Create a branch and back up &lt;code&gt;src/components/ui&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Find your real customizations with &lt;code&gt;git log -- src/components/ui&lt;/code&gt;. In our case only &lt;code&gt;breadcrumb.tsx&lt;/code&gt; had local edits (accessibility commits), and reading the log was faster than diffing every component.&lt;/li&gt;
&lt;li&gt;Fix &lt;code&gt;aliases.utils&lt;/code&gt; in &lt;code&gt;components.json&lt;/code&gt; so it points at the file that exports &lt;code&gt;cn&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Set the base through &lt;code&gt;style&lt;/code&gt; (for example &lt;code&gt;base-nova&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;shadcn apply --preset &amp;lt;code&amp;gt;&lt;/code&gt; and review the full diff, including the icon library, base color, and dependency changes.&lt;/li&gt;
&lt;li&gt;Repair any bare &lt;code&gt;&amp;quot;cn&amp;quot;&lt;/code&gt; imports, delete the stray &lt;code&gt;utils.ts&lt;/code&gt;, and remove the &lt;code&gt;cn&lt;/code&gt; package.&lt;/li&gt;
&lt;li&gt;Convert &lt;code&gt;asChild&lt;/code&gt; to &lt;code&gt;render&lt;/code&gt;, adding &lt;code&gt;nativeButton={false}&lt;/code&gt; where the target is not a button.&lt;/li&gt;
&lt;li&gt;Fix Select &lt;code&gt;items&lt;/code&gt;, Accordion props, ToggleGroup props, and &lt;code&gt;data-state&lt;/code&gt; selectors.&lt;/li&gt;
&lt;li&gt;Add &lt;code&gt;&amp;quot;use client&amp;quot;&lt;/code&gt; to &lt;code&gt;useRender&lt;/code&gt; wrappers only.&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;npx tsc --noEmit&lt;/code&gt;, then deploy a preview. Typechecking alone missed the &lt;code&gt;use client&lt;/code&gt; failures.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Conclusion&lt;/h3&gt;
&lt;p&gt;The transition from Radix UI to Base UI in shadcn represents a fundamental shift in how modern headless components are structured, but it does not mean your existing codebase needs an emergency rewrite. You own your code, which makes automated codemods impractical. Reach for Base UI when building new projects or when a specific primitive feature solves an active problem, and leave your stable Radix foundations alone if your application is already shipping reliably.&lt;/p&gt;
&lt;p&gt;If you do migrate, the cost depends on how much you have customized. A small, mostly stock &lt;code&gt;components/ui&lt;/code&gt; (ours had one customized file) took about an afternoon. A heavily customized one is where the real cost sits, because every local edit has to be found and carried forward by hand.&lt;/p&gt;
&lt;p&gt;If you have questions or ran into a different gotcha, drop a comment below. And if you found this useful, subscribe for more.&lt;/p&gt;
&lt;p&gt;Thanks,
Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/radix-to-base-ui-in-shadcn"/>
        </item>
        <item>
            <title><![CDATA[How to Build an In-Article Editorial Annotation Layer in Next.js with Vanilla JavaScript and CSS]]></title>
            <description><![CDATA[<p>Last week, I was reviewing a newly published technical article on our site when I noticed a couple of sentences that needed restructuring and an updated code snippet. The standard routine for this is frustratingly clunky. You copy the excerpt, tab over to Linear, GitHub, or Notion, paste the quote, write your suggestion, and switch back to continue reading. If you want to dictate a quick thought using macOS or iOS speech-to-text, context switching completely derails your momentum.</p>
<p>I wanted an editorial experience that felt as immediate as reading: highlight any paragraph or sentence directly on the live page, have a sleek card appear right above the text with the cursor already focused in a text area, and dictate a voice note that saves directly to our headless CMS alongside the exact quote and heading anchor.</p>
<p>Most tutorials would reach for heavy UI primitive libraries like Popper, Floating UI, or full modal packages for this. But pulling in hundreds of kilobytes of dependencies when <a href="/blog/headless-ui-primitives-when-to-own-ui-behavior">evaluating headless UI primitives and choosing when to own UI behavior</a> shows that zero-dependency native browser APIs are often cleaner and lighter. In this guide, I will show you how to build a production-ready, zero-dependency editorial annotation layer in Next.js using native browser APIs and vanilla CSS.</p>
<hr>
<h2>1. Scoping the Article Container and Protecting Public Readers</h2>
<p>Before attaching any DOM listeners, we need to solve two fundamental requirements. First, regular readers should never experience extra JavaScript execution or layout shifts. Second, text selection events must be scoped strictly to the article body prose, ignoring navigation headers, sidebars, and footers.</p>
<p>We start by marking the article container in our page template with a custom data attribute and mounting a client-side layer that checks our session cookie on mount.</p>
<pre><code class="language-typescript">// File: src/components/blog/editorial/EditorialFeedbackLayer.tsx
&#39;use client&#39;

import React, { useState, useEffect, useRef } from &#39;react&#39;

interface EditorialFeedbackLayerProps {
  postId: string
  postSlug: string
  postTitle: string
}

export function EditorialFeedbackLayer({
  postId,
  postSlug,
  postTitle,
}: EditorialFeedbackLayerProps) {
  const [isAdmin, setIsAdmin] = useState&lt;boolean | null&gt;(null)

  useEffect(() =&gt; {
    let isMounted = true

    async function checkSession() {
      try {
        const res = await fetch(&#39;/api/editorial/session&#39;)
        const data = await res.json()
        if (isMounted) {
          setIsAdmin(Boolean(data.authenticated &amp;&amp; data.isAdmin))
        }
      } catch {
        if (isMounted) {
          setIsAdmin(false)
        }
      }
    }

    checkSession()
    return () =&gt; {
      isMounted = false
    }
  }, [])

  if (!isAdmin) {
    return null
  }

  return (
    &lt;div className=&quot;editorial-feedback-root&quot; data-editorial-active=&quot;true&quot;&gt;
      {/* Editorial UI components render here */}
    &lt;/div&gt;
  )
}
</code></pre>
<p>This component performs a quick, lightweight authorization check against an endpoint that reads our admin session cookie, similar to how we protect internal routes in our <a href="/blog/nextjs-internationalization-architecture-guide">Next.js internationalization architecture</a> and edge middleware layers. If the visitor is not an authenticated editor, the component immediately returns null. No event listeners are attached, no extra markup enters the DOM, and public page performance remains untouched. In the article layout, we simply place <code>data-editorial-article=&quot;true&quot;</code> on the <code>&lt;article&gt;</code> tag so our selection listener knows its boundary.</p>
<p>Now that we have secured the perimeter and established our target container, we can listen for native text selections and extract contextual references.</p>
<hr>
<h2>2. Capturing Native Selections and Traversing Heading Anchors</h2>
<p>When an editor highlights a sentence, storing the raw text alone is not enough. You also need to know which section of the article it belongs to, and what surrounding paragraph context enveloped it. </p>
<p>To accomplish this without third-party libraries, we listen to the native <code>selectionchange</code> event on the document. When a selection occurs within our article container, we traverse the DOM backward to find the nearest preceding heading.</p>
<pre><code class="language-typescript">// File: src/components/blog/editorial/EditorialFeedbackLayer.tsx
function findPrecedingHeading(node: Node | null): string {
  let current: Node | null = node

  while (current &amp;&amp; current !== document.body) {
    let prev: Node | null = current.previousSibling
    while (prev) {
      if (prev.nodeType === Node.ELEMENT_NODE) {
        const el = prev as HTMLElement
        if (/^H[1-4]$/i.test(el.tagName)) {
          return el.innerText.trim()
        }
        const nestedHeading = el.querySelector(&#39;h1, h2, h3, h4&#39;)
        if (nestedHeading) {
          return (nestedHeading as HTMLElement).innerText.trim()
        }
      }
      prev = prev.previousSibling
    }
    current = current.parentNode
  }
  return &#39;&#39;
}
</code></pre>
<p>This helper starts at the selection node and climbs up the DOM tree, examining preceding siblings at each level. If a sibling or its child matches an <code>h1</code>, <code>h2</code>, <code>h3</code>, or <code>h4</code> tag, it extracts that title. This gives us an automatic section anchor, so when our editorial team reviews notes later, we know immediately whether the note applies to the introduction, a code walkthrough section, or the conclusion.</p>
<p>Next, we wire this helper into our selection listener with a debounce to prevent jitter during mouse dragging.</p>
<pre><code class="language-typescript">// File: src/components/blog/editorial/EditorialFeedbackLayer.tsx
export interface SelectionState {
  text: string
  context: string
  anchorHeading: string
  x: number
  y: number
  positionAbove: boolean
}

// Inside EditorialFeedbackLayer component:
const [activeSelection, setActiveSelection] = useState&lt;SelectionState | null&gt;(null)
const selectionTimeoutRef = useRef&lt;NodeJS.Timeout | null&gt;(null)

useEffect(() =&gt; {
  if (!isAdmin) return

  const handleSelectionChange = () =&gt; {
    if (selectionTimeoutRef.current) {
      clearTimeout(selectionTimeoutRef.current)
    }

    selectionTimeoutRef.current = setTimeout(() =&gt; {
      const selection = window.getSelection()
      if (!selection || selection.isCollapsed) {
        setActiveSelection(null)
        return
      }

      const text = selection.toString().trim()
      if (text.length &lt; 2 || selection.rangeCount === 0) {
        setActiveSelection(null)
        return
      }

      const range = selection.getRangeAt(0)
      const articleContainer = document.querySelector(&#39;[data-editorial-article]&#39;)

      if (!articleContainer || !articleContainer.contains(range.commonAncestorContainer)) {
        setActiveSelection(null)
        return
      }

      const rect = range.getBoundingClientRect()
      if (rect.width === 0 &amp;&amp; rect.height === 0) {
        setActiveSelection(null)
        return
      }

      const anchorHeading = findPrecedingHeading(range.startContainer)
      const parentElem = (
        range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE
          ? range.commonAncestorContainer
          : range.commonAncestorContainer.parentElement
      ) as HTMLElement | null

      const context = parentElem ? parentElem.innerText.slice(0, 300) : text

      const x = rect.left + rect.width / 2 + window.scrollX
      const positionAbove = rect.top &gt;= 140
      const y = positionAbove ? rect.top + window.scrollY : rect.bottom + window.scrollY

      setActiveSelection({
        text,
        context,
        anchorHeading,
        x,
        y,
        positionAbove,
      })
    }, 120)
  }

  document.addEventListener(&#39;selectionchange&#39;, handleSelectionChange)
  return () =&gt; {
    document.removeEventListener(&#39;selectionchange&#39;, handleSelectionChange)
    if (selectionTimeoutRef.current) {
      clearTimeout(selectionTimeoutRef.current)
    }
  }
}, [isAdmin])
</code></pre>
<p>In this block, <code>window.getSelection()</code> retrieves the highlighted text and its <code>Range</code>. We verify that the common ancestor container of the selection lives inside our article boundary. If it does, we extract the selected prose, sample up to 300 characters of the parent paragraph for context, and capture the bounding client rectangle.</p>
<p>Once we have the rectangle coordinates, we must calculate where to position our floating interface without allowing it to collide with viewport boundaries.</p>
<hr>
<h2>3. Viewport Geometry and Collision Clamping</h2>
<p>Floating popovers often break when text is highlighted near the edge of a screen or at the very top of a viewport. Without an external library handling collision detection, we can implement precise coordinate math in vanilla JavaScript.</p>
<p>We calculate the horizontal center of the selection, add the current page scroll offset, and clamp the value so the card never clips past the edge of the viewport.</p>
<pre><code class="language-typescript">// File: src/components/blog/editorial/EditorialAnnotationCard.tsx
interface CardPositionProps {
  x: number
  y: number
  positionAbove: boolean
  cardWidth?: number
}

export function computeCardCoordinates({
  x,
  y,
  positionAbove,
  cardWidth = 380,
}: CardPositionProps) {
  const padding = 16
  const screenWidth = typeof window !== &#39;undefined&#39; ? window.innerWidth : 1024
  
  // Center card over selection, but clamp within viewport boundaries
  const rawLeft = x - cardWidth / 2
  const clampedLeft = Math.max(padding, Math.min(rawLeft, screenWidth - cardWidth - padding))

  // Determine vertical offset based on whether popover renders above or below
  const verticalOffset = positionAbove ? -12 : 12

  return {
    left: `${clampedLeft}px`,
    top: `${y + verticalOffset}px`,
    transform: positionAbove ? &#39;translateY(-100%)&#39; : &#39;translateY(0)&#39;,
  }
}
</code></pre>
<p>This math solves three common positioning bugs in a few lines of code. Subtracting half the card width centers the popover above the selected text. Clamping the left coordinate between sixteen pixels and the remaining screen width guarantees that the card never overflows off the left or right edges on mobile screens or split windows. Finally, if the selection is within 140 pixels of the top edge of the browser viewport, our flag flips vertical translation so the card opens downward rather than off the top of the screen.</p>
<p>With our positioning math in place, we can construct the actual annotation card optimized for rapid voice dictation.</p>
<hr>
<h2>4. Building the Voice-Ready Annotation Card with Vanilla CSS</h2>
<p>When you highlight text to dictate a thought, you should not have to click an extra input to start speaking. The card should appear, immediately focus a native textarea, display the quoted passage, and allow you to hit your keyboard dictation shortcut or type your feedback right away.</p>
<p>By building the annotation card as an isolated vertical slice with no external dependencies, we follow the pattern of <a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">shipping reusable vertical slices</a> that can be embedded into any article or documentation layout without leaking styles or bundle weight.</p>
<p>Here is the implementation of our annotation card, styled with pure vanilla CSS and subtle frosted glassmorphism.</p>
<pre><code class="language-typescript">// File: src/components/blog/editorial/EditorialAnnotationCard.tsx
&#39;use client&#39;

import React, { useState, useEffect, useRef } from &#39;react&#39;
import { SelectionState } from &#39;./EditorialFeedbackLayer&#39;

interface EditorialAnnotationCardProps {
  postId: string
  postSlug: string
  postTitle: string
  selection: SelectionState
  onClose: () =&gt; void
  onSaved: () =&gt; void
}

const CATEGORIES = [
  { value: &#39;editorial-note&#39;, label: &#39;Note&#39; },
  { value: &#39;rewrite&#39;, label: &#39;Rewrite&#39; },
  { value: &#39;fact-check&#39;, label: &#39;Fact-Check&#39; },
  { value: &#39;typo&#39;, label: &#39;Typo&#39; },
] as const

export function EditorialAnnotationCard({
  postId,
  postSlug,
  postTitle,
  selection,
  onClose,
  onSaved,
}: EditorialAnnotationCardProps) {
  const [notes, setNotes] = useState(&#39;&#39;)
  const [category, setCategory] = useState&lt;string&gt;(&#39;rewrite&#39;)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const textareaRef = useRef&lt;HTMLTextAreaElement&gt;(null)
  const cardRef = useRef&lt;HTMLDivElement&gt;(null)

  useEffect(() =&gt; {
    if (textareaRef.current) {
      textareaRef.current.focus()
    }
  }, [])

  const handleSubmit = async () =&gt; {
    if (!notes.trim() || isSubmitting) return
    setIsSubmitting(true)

    try {
      const res = await fetch(&#39;/api/editorial/feedback&#39;, {
        method: &#39;POST&#39;,
        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },
        body: JSON.stringify({
          postId,
          postSlug,
          postTitle,
          selectedText: selection.text,
          context: selection.context,
          anchorHeading: selection.anchorHeading,
          notes: notes.trim(),
          category,
        }),
      })

      if (res.ok) {
        onSaved()
        onClose()
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent&lt;HTMLTextAreaElement&gt;) =&gt; {
    if ((e.metaKey || e.ctrlKey) &amp;&amp; e.key === &#39;Enter&#39;) {
      e.preventDefault()
      handleSubmit()
    } else if (e.key === &#39;Escape&#39;) {
      onClose()
    }
  }

  return (
    &lt;div
      ref={cardRef}
      style={{
        position: &#39;absolute&#39;,
        width: &#39;380px&#39;,
        maxWidth: &#39;calc(100vw - 32px)&#39;,
        zIndex: 9999,
        background: &#39;rgba(18, 18, 22, 0.94)&#39;,
        backdropFilter: &#39;blur(16px)&#39;,
        WebkitBackdropFilter: &#39;blur(16px)&#39;,
        border: &#39;1px solid rgba(255, 255, 255, 0.12)&#39;,
        borderRadius: &#39;12px&#39;,
        boxShadow: &#39;0 20px 48px rgba(0, 0, 0, 0.5)&#39;,
        padding: &#39;14px&#39;,
        color: &#39;#f4f4f5&#39;,
        fontFamily: &#39;inherit&#39;,
      }}
    &gt;
      &lt;div style={{ fontSize: &#39;11px&#39;, color: &#39;#a1a1aa&#39;, marginBottom: &#39;8px&#39;, fontStyle: &#39;italic&#39; }}&gt;
        &amp;ldquo;{selection.text.slice(0, 90)}{selection.text.length &gt; 90 ? &#39;...&#39; : &#39;&#39;}&amp;rdquo;
      &lt;/div&gt;

      &lt;div style={{ display: &#39;flex&#39;, gap: &#39;6px&#39;, marginBottom: &#39;10px&#39; }}&gt;
        {CATEGORIES.map((cat) =&gt; (
          &lt;button
            key={cat.value}
            type=&quot;button&quot;
            onClick={() =&gt; setCategory(cat.value)}
            style={{
              fontSize: &#39;11px&#39;,
              padding: &#39;3px 8px&#39;,
              borderRadius: &#39;6px&#39;,
              border: &#39;none&#39;,
              cursor: &#39;pointer&#39;,
              background: category === cat.value ? &#39;#3b82f6&#39; : &#39;rgba(255, 255, 255, 0.08)&#39;,
              color: category === cat.value ? &#39;#ffffff&#39; : &#39;#d4d4d8&#39;,
            }}
          &gt;
            {cat.label}
          &lt;/button&gt;
        ))}
      &lt;/div&gt;

      &lt;textarea
        ref={textareaRef}
        value={notes}
        onChange={(e) =&gt; setNotes(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder=&quot;Dictate or type editorial feedback... (Cmd+Enter to save)&quot;
        rows={3}
        style={{
          width: &#39;100%&#39;,
          boxSizing: &#39;border-box&#39;,
          background: &#39;rgba(0, 0, 0, 0.4)&#39;,
          border: &#39;1px solid rgba(255, 255, 255, 0.1)&#39;,
          borderRadius: &#39;8px&#39;,
          color: &#39;#ffffff&#39;,
          padding: &#39;8px 10px&#39;,
          fontSize: &#39;13px&#39;,
          resize: &#39;vertical&#39;,
          outline: &#39;none&#39;,
        }}
      /&gt;

      &lt;div style={{ display: &#39;flex&#39;, justifyContent: &#39;flex-end&#39;, gap: &#39;8px&#39;, marginTop: &#39;10px&#39; }}&gt;
        &lt;button
          type=&quot;button&quot;
          onClick={onClose}
          style={{
            background: &#39;transparent&#39;,
            border: &#39;none&#39;,
            color: &#39;#a1a1aa&#39;,
            fontSize: &#39;12px&#39;,
            cursor: &#39;pointer&#39;,
          }}
        &gt;
          Cancel
        &lt;/button&gt;
        &lt;button
          type=&quot;button&quot;
          onClick={handleSubmit}
          disabled={isSubmitting || !notes.trim()}
          style={{
            background: &#39;#2563eb&#39;,
            border: &#39;none&#39;,
            borderRadius: &#39;6px&#39;,
            color: &#39;#ffffff&#39;,
            padding: &#39;6px 14px&#39;,
            fontSize: &#39;12px&#39;,
            fontWeight: 500,
            cursor: isSubmitting ? &#39;not-allowed&#39; : &#39;pointer&#39;,
            opacity: isSubmitting || !notes.trim() ? 0.6 : 1,
          }}
        &gt;
          {isSubmitting ? &#39;Saving...&#39; : &#39;Save Feedback&#39;}
        &lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  )
}
</code></pre>
<p>This card is built using standard inline styles and native HTML elements. On mount, <code>textareaRef.current.focus()</code> immediately captures system focus so pressing the microphone key on your device begins speech dictation right away. We also include a keyboard listener for Command or Control plus Enter to submit without reaching for the mouse, and Escape to dismiss.</p>
<p>The final step is receiving this payload on our server and persisting it to our CMS.</p>
<hr>
<h2>5. Persisting Annotations to the Headless CMS</h2>
<p>When our frontend submits the payload, our Next.js Route Handler needs to verify the admin session and create an annotation document. In our setup, we store editorial feedback as a dedicated schema in Sanity, linking it directly to the target post document.</p>
<pre><code class="language-typescript">// File: src/app/api/editorial/feedback/route.ts
import { NextResponse } from &#39;next/server&#39;
import { getPayload } from &#39;payload&#39;
import configPromise from &#39;@payload-config&#39;
import { freshClient } from &#39;@/lib/sanity/client&#39;

export async function POST(request: Request) {
  try {
    const payload = await getPayload({ config: configPromise })
    const { user } = await payload.auth({ headers: request.headers })

    if (!user) {
      return NextResponse.json(
        { error: &#39;Unauthorized. Admin credentials required.&#39; },
        { status: 401 }
      )
    }

    const body = await request.json()
    const {
      postId,
      postSlug,
      postTitle,
      selectedText,
      context,
      anchorHeading,
      notes,
      category,
    } = body

    if (!postSlug || !selectedText || !notes) {
      return NextResponse.json(
        { error: &#39;Missing required feedback fields.&#39; },
        { status: 400 }
      )
    }

    const doc = await freshClient.create({
      _type: &#39;articleFeedback&#39;,
      post: postId ? { _type: &#39;reference&#39;, _ref: postId } : undefined,
      articleSlug: postSlug,
      articleTitle: postTitle || postSlug,
      selectedText,
      context: context || selectedText,
      anchorHeading: anchorHeading || &#39;&#39;,
      notes,
      category: category || &#39;editorial-note&#39;,
      status: &#39;open&#39;,
      authorEmail: user.email || &#39;admin&#39;,
      createdAt: new Date().toISOString(),
    })

    return NextResponse.json({ success: true, feedback: doc })
  } catch (error) {
    return NextResponse.json(
      { error: &#39;Failed to record editorial feedback.&#39; },
      { status: 500 }
    )
  }
}
</code></pre>
<p>The route handler checks our session headers using our authentication layer. Once confirmed, it writes an <code>articleFeedback</code> document to Sanity with <code>status: &#39;open&#39;</code>. The document captures the exact quoted text, the surrounding paragraph context, the preceding heading title, the author&#39;s email, and the dictated note. </p>
<p>Because this is a structured document in our CMS, our developers or AI agents can query open feedback using a simple CLI script (<code>pnpm content feedback &lt;slug&gt;</code>), review changes alongside our <a href="/blog/payload-admin-ui-components-glossary-v3-6">custom Payload admin interfaces</a>, and trigger <a href="/blog/auto-sync-cms-openai-vector-store">automated CMS vector syncs</a> once content revisions are approved.</p>
<hr>
<h2>Conclusion</h2>
<p>Editorial feedback is often slow and fragmented because the tools we use to read live articles are completely separated from the tools we use to request changes. By listening to native DOM text selections and reading sibling headings in an AST traversal, we built an on-page editorial layer that captures voice notes right where the reading happens.</p>
<p>We avoided large third-party UI libraries entirely. Pure vanilla JavaScript handles the selection boundary detection, parent paragraph context sniffs, and screen clamping math, while standard vanilla CSS delivers a responsive, frosted-glass interface that stays out of the way of regular visitors.</p>
<p>With this foundation in place, you can adapt the backend persistence to whatever CMS or database your application uses, giving your editorial team a frictionless, voice-friendly review workflow.</p>
<p>Thanks,<br>Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/build-in-article-editorial-annotation-layer-nextjs</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/build-in-article-editorial-annotation-layer-nextjs</guid>
            <category><![CDATA[Next.js]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 20:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;Last week, I was reviewing a newly published technical article on our site when I noticed a couple of sentences that needed restructuring and an updated code snippet. The standard routine for this is frustratingly clunky. You copy the excerpt, tab over to Linear, GitHub, or Notion, paste the quote, write your suggestion, and switch back to continue reading. If you want to dictate a quick thought using macOS or iOS speech-to-text, context switching completely derails your momentum.&lt;/p&gt;
&lt;p&gt;I wanted an editorial experience that felt as immediate as reading: highlight any paragraph or sentence directly on the live page, have a sleek card appear right above the text with the cursor already focused in a text area, and dictate a voice note that saves directly to our headless CMS alongside the exact quote and heading anchor.&lt;/p&gt;
&lt;p&gt;Most tutorials would reach for heavy UI primitive libraries like Popper, Floating UI, or full modal packages for this. But pulling in hundreds of kilobytes of dependencies when &lt;a href=&quot;/blog/headless-ui-primitives-when-to-own-ui-behavior&quot;&gt;evaluating headless UI primitives and choosing when to own UI behavior&lt;/a&gt; shows that zero-dependency native browser APIs are often cleaner and lighter. In this guide, I will show you how to build a production-ready, zero-dependency editorial annotation layer in Next.js using native browser APIs and vanilla CSS.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;1. Scoping the Article Container and Protecting Public Readers&lt;/h2&gt;
&lt;p&gt;Before attaching any DOM listeners, we need to solve two fundamental requirements. First, regular readers should never experience extra JavaScript execution or layout shifts. Second, text selection events must be scoped strictly to the article body prose, ignoring navigation headers, sidebars, and footers.&lt;/p&gt;
&lt;p&gt;We start by marking the article container in our page template with a custom data attribute and mounting a client-side layer that checks our session cookie on mount.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/blog/editorial/EditorialFeedbackLayer.tsx
&amp;#39;use client&amp;#39;

import React, { useState, useEffect, useRef } from &amp;#39;react&amp;#39;

interface EditorialFeedbackLayerProps {
  postId: string
  postSlug: string
  postTitle: string
}

export function EditorialFeedbackLayer({
  postId,
  postSlug,
  postTitle,
}: EditorialFeedbackLayerProps) {
  const [isAdmin, setIsAdmin] = useState&amp;lt;boolean | null&amp;gt;(null)

  useEffect(() =&amp;gt; {
    let isMounted = true

    async function checkSession() {
      try {
        const res = await fetch(&amp;#39;/api/editorial/session&amp;#39;)
        const data = await res.json()
        if (isMounted) {
          setIsAdmin(Boolean(data.authenticated &amp;amp;&amp;amp; data.isAdmin))
        }
      } catch {
        if (isMounted) {
          setIsAdmin(false)
        }
      }
    }

    checkSession()
    return () =&amp;gt; {
      isMounted = false
    }
  }, [])

  if (!isAdmin) {
    return null
  }

  return (
    &amp;lt;div className=&amp;quot;editorial-feedback-root&amp;quot; data-editorial-active=&amp;quot;true&amp;quot;&amp;gt;
      {/* Editorial UI components render here */}
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This component performs a quick, lightweight authorization check against an endpoint that reads our admin session cookie, similar to how we protect internal routes in our &lt;a href=&quot;/blog/nextjs-internationalization-architecture-guide&quot;&gt;Next.js internationalization architecture&lt;/a&gt; and edge middleware layers. If the visitor is not an authenticated editor, the component immediately returns null. No event listeners are attached, no extra markup enters the DOM, and public page performance remains untouched. In the article layout, we simply place &lt;code&gt;data-editorial-article=&amp;quot;true&amp;quot;&lt;/code&gt; on the &lt;code&gt;&amp;lt;article&amp;gt;&lt;/code&gt; tag so our selection listener knows its boundary.&lt;/p&gt;
&lt;p&gt;Now that we have secured the perimeter and established our target container, we can listen for native text selections and extract contextual references.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;2. Capturing Native Selections and Traversing Heading Anchors&lt;/h2&gt;
&lt;p&gt;When an editor highlights a sentence, storing the raw text alone is not enough. You also need to know which section of the article it belongs to, and what surrounding paragraph context enveloped it. &lt;/p&gt;
&lt;p&gt;To accomplish this without third-party libraries, we listen to the native &lt;code&gt;selectionchange&lt;/code&gt; event on the document. When a selection occurs within our article container, we traverse the DOM backward to find the nearest preceding heading.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/blog/editorial/EditorialFeedbackLayer.tsx
function findPrecedingHeading(node: Node | null): string {
  let current: Node | null = node

  while (current &amp;amp;&amp;amp; current !== document.body) {
    let prev: Node | null = current.previousSibling
    while (prev) {
      if (prev.nodeType === Node.ELEMENT_NODE) {
        const el = prev as HTMLElement
        if (/^H[1-4]$/i.test(el.tagName)) {
          return el.innerText.trim()
        }
        const nestedHeading = el.querySelector(&amp;#39;h1, h2, h3, h4&amp;#39;)
        if (nestedHeading) {
          return (nestedHeading as HTMLElement).innerText.trim()
        }
      }
      prev = prev.previousSibling
    }
    current = current.parentNode
  }
  return &amp;#39;&amp;#39;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This helper starts at the selection node and climbs up the DOM tree, examining preceding siblings at each level. If a sibling or its child matches an &lt;code&gt;h1&lt;/code&gt;, &lt;code&gt;h2&lt;/code&gt;, &lt;code&gt;h3&lt;/code&gt;, or &lt;code&gt;h4&lt;/code&gt; tag, it extracts that title. This gives us an automatic section anchor, so when our editorial team reviews notes later, we know immediately whether the note applies to the introduction, a code walkthrough section, or the conclusion.&lt;/p&gt;
&lt;p&gt;Next, we wire this helper into our selection listener with a debounce to prevent jitter during mouse dragging.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/blog/editorial/EditorialFeedbackLayer.tsx
export interface SelectionState {
  text: string
  context: string
  anchorHeading: string
  x: number
  y: number
  positionAbove: boolean
}

// Inside EditorialFeedbackLayer component:
const [activeSelection, setActiveSelection] = useState&amp;lt;SelectionState | null&amp;gt;(null)
const selectionTimeoutRef = useRef&amp;lt;NodeJS.Timeout | null&amp;gt;(null)

useEffect(() =&amp;gt; {
  if (!isAdmin) return

  const handleSelectionChange = () =&amp;gt; {
    if (selectionTimeoutRef.current) {
      clearTimeout(selectionTimeoutRef.current)
    }

    selectionTimeoutRef.current = setTimeout(() =&amp;gt; {
      const selection = window.getSelection()
      if (!selection || selection.isCollapsed) {
        setActiveSelection(null)
        return
      }

      const text = selection.toString().trim()
      if (text.length &amp;lt; 2 || selection.rangeCount === 0) {
        setActiveSelection(null)
        return
      }

      const range = selection.getRangeAt(0)
      const articleContainer = document.querySelector(&amp;#39;[data-editorial-article]&amp;#39;)

      if (!articleContainer || !articleContainer.contains(range.commonAncestorContainer)) {
        setActiveSelection(null)
        return
      }

      const rect = range.getBoundingClientRect()
      if (rect.width === 0 &amp;amp;&amp;amp; rect.height === 0) {
        setActiveSelection(null)
        return
      }

      const anchorHeading = findPrecedingHeading(range.startContainer)
      const parentElem = (
        range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE
          ? range.commonAncestorContainer
          : range.commonAncestorContainer.parentElement
      ) as HTMLElement | null

      const context = parentElem ? parentElem.innerText.slice(0, 300) : text

      const x = rect.left + rect.width / 2 + window.scrollX
      const positionAbove = rect.top &amp;gt;= 140
      const y = positionAbove ? rect.top + window.scrollY : rect.bottom + window.scrollY

      setActiveSelection({
        text,
        context,
        anchorHeading,
        x,
        y,
        positionAbove,
      })
    }, 120)
  }

  document.addEventListener(&amp;#39;selectionchange&amp;#39;, handleSelectionChange)
  return () =&amp;gt; {
    document.removeEventListener(&amp;#39;selectionchange&amp;#39;, handleSelectionChange)
    if (selectionTimeoutRef.current) {
      clearTimeout(selectionTimeoutRef.current)
    }
  }
}, [isAdmin])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this block, &lt;code&gt;window.getSelection()&lt;/code&gt; retrieves the highlighted text and its &lt;code&gt;Range&lt;/code&gt;. We verify that the common ancestor container of the selection lives inside our article boundary. If it does, we extract the selected prose, sample up to 300 characters of the parent paragraph for context, and capture the bounding client rectangle.&lt;/p&gt;
&lt;p&gt;Once we have the rectangle coordinates, we must calculate where to position our floating interface without allowing it to collide with viewport boundaries.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;3. Viewport Geometry and Collision Clamping&lt;/h2&gt;
&lt;p&gt;Floating popovers often break when text is highlighted near the edge of a screen or at the very top of a viewport. Without an external library handling collision detection, we can implement precise coordinate math in vanilla JavaScript.&lt;/p&gt;
&lt;p&gt;We calculate the horizontal center of the selection, add the current page scroll offset, and clamp the value so the card never clips past the edge of the viewport.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/blog/editorial/EditorialAnnotationCard.tsx
interface CardPositionProps {
  x: number
  y: number
  positionAbove: boolean
  cardWidth?: number
}

export function computeCardCoordinates({
  x,
  y,
  positionAbove,
  cardWidth = 380,
}: CardPositionProps) {
  const padding = 16
  const screenWidth = typeof window !== &amp;#39;undefined&amp;#39; ? window.innerWidth : 1024
  
  // Center card over selection, but clamp within viewport boundaries
  const rawLeft = x - cardWidth / 2
  const clampedLeft = Math.max(padding, Math.min(rawLeft, screenWidth - cardWidth - padding))

  // Determine vertical offset based on whether popover renders above or below
  const verticalOffset = positionAbove ? -12 : 12

  return {
    left: `${clampedLeft}px`,
    top: `${y + verticalOffset}px`,
    transform: positionAbove ? &amp;#39;translateY(-100%)&amp;#39; : &amp;#39;translateY(0)&amp;#39;,
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This math solves three common positioning bugs in a few lines of code. Subtracting half the card width centers the popover above the selected text. Clamping the left coordinate between sixteen pixels and the remaining screen width guarantees that the card never overflows off the left or right edges on mobile screens or split windows. Finally, if the selection is within 140 pixels of the top edge of the browser viewport, our flag flips vertical translation so the card opens downward rather than off the top of the screen.&lt;/p&gt;
&lt;p&gt;With our positioning math in place, we can construct the actual annotation card optimized for rapid voice dictation.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;4. Building the Voice-Ready Annotation Card with Vanilla CSS&lt;/h2&gt;
&lt;p&gt;When you highlight text to dictate a thought, you should not have to click an extra input to start speaking. The card should appear, immediately focus a native textarea, display the quoted passage, and allow you to hit your keyboard dictation shortcut or type your feedback right away.&lt;/p&gt;
&lt;p&gt;By building the annotation card as an isolated vertical slice with no external dependencies, we follow the pattern of &lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;shipping reusable vertical slices&lt;/a&gt; that can be embedded into any article or documentation layout without leaking styles or bundle weight.&lt;/p&gt;
&lt;p&gt;Here is the implementation of our annotation card, styled with pure vanilla CSS and subtle frosted glassmorphism.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/components/blog/editorial/EditorialAnnotationCard.tsx
&amp;#39;use client&amp;#39;

import React, { useState, useEffect, useRef } from &amp;#39;react&amp;#39;
import { SelectionState } from &amp;#39;./EditorialFeedbackLayer&amp;#39;

interface EditorialAnnotationCardProps {
  postId: string
  postSlug: string
  postTitle: string
  selection: SelectionState
  onClose: () =&amp;gt; void
  onSaved: () =&amp;gt; void
}

const CATEGORIES = [
  { value: &amp;#39;editorial-note&amp;#39;, label: &amp;#39;Note&amp;#39; },
  { value: &amp;#39;rewrite&amp;#39;, label: &amp;#39;Rewrite&amp;#39; },
  { value: &amp;#39;fact-check&amp;#39;, label: &amp;#39;Fact-Check&amp;#39; },
  { value: &amp;#39;typo&amp;#39;, label: &amp;#39;Typo&amp;#39; },
] as const

export function EditorialAnnotationCard({
  postId,
  postSlug,
  postTitle,
  selection,
  onClose,
  onSaved,
}: EditorialAnnotationCardProps) {
  const [notes, setNotes] = useState(&amp;#39;&amp;#39;)
  const [category, setCategory] = useState&amp;lt;string&amp;gt;(&amp;#39;rewrite&amp;#39;)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const textareaRef = useRef&amp;lt;HTMLTextAreaElement&amp;gt;(null)
  const cardRef = useRef&amp;lt;HTMLDivElement&amp;gt;(null)

  useEffect(() =&amp;gt; {
    if (textareaRef.current) {
      textareaRef.current.focus()
    }
  }, [])

  const handleSubmit = async () =&amp;gt; {
    if (!notes.trim() || isSubmitting) return
    setIsSubmitting(true)

    try {
      const res = await fetch(&amp;#39;/api/editorial/feedback&amp;#39;, {
        method: &amp;#39;POST&amp;#39;,
        headers: { &amp;#39;Content-Type&amp;#39;: &amp;#39;application/json&amp;#39; },
        body: JSON.stringify({
          postId,
          postSlug,
          postTitle,
          selectedText: selection.text,
          context: selection.context,
          anchorHeading: selection.anchorHeading,
          notes: notes.trim(),
          category,
        }),
      })

      if (res.ok) {
        onSaved()
        onClose()
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleKeyDown = (e: React.KeyboardEvent&amp;lt;HTMLTextAreaElement&amp;gt;) =&amp;gt; {
    if ((e.metaKey || e.ctrlKey) &amp;amp;&amp;amp; e.key === &amp;#39;Enter&amp;#39;) {
      e.preventDefault()
      handleSubmit()
    } else if (e.key === &amp;#39;Escape&amp;#39;) {
      onClose()
    }
  }

  return (
    &amp;lt;div
      ref={cardRef}
      style={{
        position: &amp;#39;absolute&amp;#39;,
        width: &amp;#39;380px&amp;#39;,
        maxWidth: &amp;#39;calc(100vw - 32px)&amp;#39;,
        zIndex: 9999,
        background: &amp;#39;rgba(18, 18, 22, 0.94)&amp;#39;,
        backdropFilter: &amp;#39;blur(16px)&amp;#39;,
        WebkitBackdropFilter: &amp;#39;blur(16px)&amp;#39;,
        border: &amp;#39;1px solid rgba(255, 255, 255, 0.12)&amp;#39;,
        borderRadius: &amp;#39;12px&amp;#39;,
        boxShadow: &amp;#39;0 20px 48px rgba(0, 0, 0, 0.5)&amp;#39;,
        padding: &amp;#39;14px&amp;#39;,
        color: &amp;#39;#f4f4f5&amp;#39;,
        fontFamily: &amp;#39;inherit&amp;#39;,
      }}
    &amp;gt;
      &amp;lt;div style={{ fontSize: &amp;#39;11px&amp;#39;, color: &amp;#39;#a1a1aa&amp;#39;, marginBottom: &amp;#39;8px&amp;#39;, fontStyle: &amp;#39;italic&amp;#39; }}&amp;gt;
        &amp;amp;ldquo;{selection.text.slice(0, 90)}{selection.text.length &amp;gt; 90 ? &amp;#39;...&amp;#39; : &amp;#39;&amp;#39;}&amp;amp;rdquo;
      &amp;lt;/div&amp;gt;

      &amp;lt;div style={{ display: &amp;#39;flex&amp;#39;, gap: &amp;#39;6px&amp;#39;, marginBottom: &amp;#39;10px&amp;#39; }}&amp;gt;
        {CATEGORIES.map((cat) =&amp;gt; (
          &amp;lt;button
            key={cat.value}
            type=&amp;quot;button&amp;quot;
            onClick={() =&amp;gt; setCategory(cat.value)}
            style={{
              fontSize: &amp;#39;11px&amp;#39;,
              padding: &amp;#39;3px 8px&amp;#39;,
              borderRadius: &amp;#39;6px&amp;#39;,
              border: &amp;#39;none&amp;#39;,
              cursor: &amp;#39;pointer&amp;#39;,
              background: category === cat.value ? &amp;#39;#3b82f6&amp;#39; : &amp;#39;rgba(255, 255, 255, 0.08)&amp;#39;,
              color: category === cat.value ? &amp;#39;#ffffff&amp;#39; : &amp;#39;#d4d4d8&amp;#39;,
            }}
          &amp;gt;
            {cat.label}
          &amp;lt;/button&amp;gt;
        ))}
      &amp;lt;/div&amp;gt;

      &amp;lt;textarea
        ref={textareaRef}
        value={notes}
        onChange={(e) =&amp;gt; setNotes(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder=&amp;quot;Dictate or type editorial feedback... (Cmd+Enter to save)&amp;quot;
        rows={3}
        style={{
          width: &amp;#39;100%&amp;#39;,
          boxSizing: &amp;#39;border-box&amp;#39;,
          background: &amp;#39;rgba(0, 0, 0, 0.4)&amp;#39;,
          border: &amp;#39;1px solid rgba(255, 255, 255, 0.1)&amp;#39;,
          borderRadius: &amp;#39;8px&amp;#39;,
          color: &amp;#39;#ffffff&amp;#39;,
          padding: &amp;#39;8px 10px&amp;#39;,
          fontSize: &amp;#39;13px&amp;#39;,
          resize: &amp;#39;vertical&amp;#39;,
          outline: &amp;#39;none&amp;#39;,
        }}
      /&amp;gt;

      &amp;lt;div style={{ display: &amp;#39;flex&amp;#39;, justifyContent: &amp;#39;flex-end&amp;#39;, gap: &amp;#39;8px&amp;#39;, marginTop: &amp;#39;10px&amp;#39; }}&amp;gt;
        &amp;lt;button
          type=&amp;quot;button&amp;quot;
          onClick={onClose}
          style={{
            background: &amp;#39;transparent&amp;#39;,
            border: &amp;#39;none&amp;#39;,
            color: &amp;#39;#a1a1aa&amp;#39;,
            fontSize: &amp;#39;12px&amp;#39;,
            cursor: &amp;#39;pointer&amp;#39;,
          }}
        &amp;gt;
          Cancel
        &amp;lt;/button&amp;gt;
        &amp;lt;button
          type=&amp;quot;button&amp;quot;
          onClick={handleSubmit}
          disabled={isSubmitting || !notes.trim()}
          style={{
            background: &amp;#39;#2563eb&amp;#39;,
            border: &amp;#39;none&amp;#39;,
            borderRadius: &amp;#39;6px&amp;#39;,
            color: &amp;#39;#ffffff&amp;#39;,
            padding: &amp;#39;6px 14px&amp;#39;,
            fontSize: &amp;#39;12px&amp;#39;,
            fontWeight: 500,
            cursor: isSubmitting ? &amp;#39;not-allowed&amp;#39; : &amp;#39;pointer&amp;#39;,
            opacity: isSubmitting || !notes.trim() ? 0.6 : 1,
          }}
        &amp;gt;
          {isSubmitting ? &amp;#39;Saving...&amp;#39; : &amp;#39;Save Feedback&amp;#39;}
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This card is built using standard inline styles and native HTML elements. On mount, &lt;code&gt;textareaRef.current.focus()&lt;/code&gt; immediately captures system focus so pressing the microphone key on your device begins speech dictation right away. We also include a keyboard listener for Command or Control plus Enter to submit without reaching for the mouse, and Escape to dismiss.&lt;/p&gt;
&lt;p&gt;The final step is receiving this payload on our server and persisting it to our CMS.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;5. Persisting Annotations to the Headless CMS&lt;/h2&gt;
&lt;p&gt;When our frontend submits the payload, our Next.js Route Handler needs to verify the admin session and create an annotation document. In our setup, we store editorial feedback as a dedicated schema in Sanity, linking it directly to the target post document.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/app/api/editorial/feedback/route.ts
import { NextResponse } from &amp;#39;next/server&amp;#39;
import { getPayload } from &amp;#39;payload&amp;#39;
import configPromise from &amp;#39;@payload-config&amp;#39;
import { freshClient } from &amp;#39;@/lib/sanity/client&amp;#39;

export async function POST(request: Request) {
  try {
    const payload = await getPayload({ config: configPromise })
    const { user } = await payload.auth({ headers: request.headers })

    if (!user) {
      return NextResponse.json(
        { error: &amp;#39;Unauthorized. Admin credentials required.&amp;#39; },
        { status: 401 }
      )
    }

    const body = await request.json()
    const {
      postId,
      postSlug,
      postTitle,
      selectedText,
      context,
      anchorHeading,
      notes,
      category,
    } = body

    if (!postSlug || !selectedText || !notes) {
      return NextResponse.json(
        { error: &amp;#39;Missing required feedback fields.&amp;#39; },
        { status: 400 }
      )
    }

    const doc = await freshClient.create({
      _type: &amp;#39;articleFeedback&amp;#39;,
      post: postId ? { _type: &amp;#39;reference&amp;#39;, _ref: postId } : undefined,
      articleSlug: postSlug,
      articleTitle: postTitle || postSlug,
      selectedText,
      context: context || selectedText,
      anchorHeading: anchorHeading || &amp;#39;&amp;#39;,
      notes,
      category: category || &amp;#39;editorial-note&amp;#39;,
      status: &amp;#39;open&amp;#39;,
      authorEmail: user.email || &amp;#39;admin&amp;#39;,
      createdAt: new Date().toISOString(),
    })

    return NextResponse.json({ success: true, feedback: doc })
  } catch (error) {
    return NextResponse.json(
      { error: &amp;#39;Failed to record editorial feedback.&amp;#39; },
      { status: 500 }
    )
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The route handler checks our session headers using our authentication layer. Once confirmed, it writes an &lt;code&gt;articleFeedback&lt;/code&gt; document to Sanity with &lt;code&gt;status: &amp;#39;open&amp;#39;&lt;/code&gt;. The document captures the exact quoted text, the surrounding paragraph context, the preceding heading title, the author&amp;#39;s email, and the dictated note. &lt;/p&gt;
&lt;p&gt;Because this is a structured document in our CMS, our developers or AI agents can query open feedback using a simple CLI script (&lt;code&gt;pnpm content feedback &amp;lt;slug&amp;gt;&lt;/code&gt;), review changes alongside our &lt;a href=&quot;/blog/payload-admin-ui-components-glossary-v3-6&quot;&gt;custom Payload admin interfaces&lt;/a&gt;, and trigger &lt;a href=&quot;/blog/auto-sync-cms-openai-vector-store&quot;&gt;automated CMS vector syncs&lt;/a&gt; once content revisions are approved.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Editorial feedback is often slow and fragmented because the tools we use to read live articles are completely separated from the tools we use to request changes. By listening to native DOM text selections and reading sibling headings in an AST traversal, we built an on-page editorial layer that captures voice notes right where the reading happens.&lt;/p&gt;
&lt;p&gt;We avoided large third-party UI libraries entirely. Pure vanilla JavaScript handles the selection boundary detection, parent paragraph context sniffs, and screen clamping math, while standard vanilla CSS delivers a responsive, frosted-glass interface that stays out of the way of regular visitors.&lt;/p&gt;
&lt;p&gt;With this foundation in place, you can adapt the backend persistence to whatever CMS or database your application uses, giving your editorial team a frictionless, voice-friendly review workflow.&lt;/p&gt;
&lt;p&gt;Thanks,&lt;br&gt;Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/build-in-article-editorial-annotation-layer-nextjs"/>
        </item>
        <item>
            <title><![CDATA[Critical WordPress Core Vulnerability: What Website Owners Need to Know About CVE-2026-87902]]></title>
            <description><![CDATA[<p>If your company website runs on WordPress, there is another security update you should check immediately.</p>
<p>This time, it is not a plugin. While recent alerts focused on third-party extensions—such as the <a href="/blog/wordpress-gravity-forms-vulnerability-cve-2026-84434">critical Gravity Forms vulnerability (CVE-2026-84434)</a>—this release addresses a flaw in the platform itself.</p>
<p>It honestly feels like we just analyzed a critical WordPress security alert yesterday—and looking at the calendar, it practically was. WordPress has been on a roll lately, and certainly not in a good way: two critical vulnerabilities surfacing in the span of just a couple of days.</p>
<p>On September 22, 2026, WordPress released version 7.1.2 to patch a critical vulnerability in WordPress Core itself.</p>
<p>The vulnerability, tracked as CVE-2026-87902, allows an unauthenticated attacker to manipulate how WordPress resolves page templates. Under the right conditions, this can make WordPress load a PHP file from outside the active theme directory.</p>
<p>That can potentially lead to remote code execution and complete compromise of the website.</p>
<p>No WordPress account is required.</p>
<p>No administrator needs to click anything.</p>
<p>There are important conditions that must be present for successful exploitation, so this does not mean every WordPress website is immediately exploitable.</p>
<p>But WordPress itself classifies the vulnerability as critical and recommends updating sites immediately.</p>
<h2>What is CVE-2026-87902?</h2>
<p>The vulnerability exists in WordPress&#39;s page-template resolution process.</p>
<p>WordPress uses templates to determine how different types of pages should be rendered. The vulnerability makes it possible for an attacker to manipulate this process so WordPress includes a readable local PHP file located outside the directories of the active theme.</p>
<p>This is known as a path traversal and local file inclusion vulnerability.</p>
<p>On its own, loading another local file does not necessarily mean an attacker can execute arbitrary code.</p>
<p>The dangerous part comes when a suitable PHP file exists elsewhere on the server.</p>
<p>Under certain server configurations, an attacker could use that file to move from local file inclusion to remote code execution.</p>
<p>At that point, the impact can become much more serious.</p>
<p>An attacker who achieves remote code execution may be able to execute commands on the server, modify the website, access data or establish persistent access.</p>
<p>That is why the issue has received a critical severity rating.</p>
<h2>Is every WordPress website vulnerable?</h2>
<p>No.</p>
<p>This distinction matters.</p>
<p>The vulnerable behaviour exists in WordPress Core, but successful exploitation depends on additional conditions being present.</p>
<p>The active parent or child theme needs to contain a top-level directory beginning with <code>page-</code>, such as:</p>
<p><code>page-templates</code></p>
<p>The server must also contain a readable PHP file that can be usefully exploited when WordPress includes it.</p>
<p>The official security advisory identifies Twenty Twelve and Twenty Fourteen as examples of WordPress themes with the relevant directory structure.</p>
<p>It also names popular third-party themes including Neve, Hestia and Sydney.</p>
<p>That does not mean every website using one of these themes can automatically be compromised.</p>
<p>The server configuration and available PHP files matter too.</p>
<p>The important distinction is between being affected by the vulnerable WordPress code and having an environment in which that vulnerability can successfully be turned into remote code execution.</p>
<p>Unless you know your theme and server configuration well enough to establish that your site cannot meet those conditions, updating WordPress is the sensible response.</p>
<h2>Which WordPress versions are affected?</h2>
<p>The vulnerability reaches much further back than the latest release.</p>
<p>WordPress 7.1.0 and 7.1.1 are affected, but WordPress has also released security fixes for older branches all the way back to WordPress 4.7.</p>
<p>For example:</p>
<ul>
<li>WordPress 7.1 was patched in 7.1.2</li>
<li>WordPress 7.0 was patched in 7.0.6</li>
<li>WordPress 6.9 was patched in 6.9.9</li>
<li>WordPress 6.8 was patched in 6.8.10</li>
<li>WordPress 6.7 was patched in 6.7.9</li>
<li>WordPress 6.6 was patched in 6.6.9</li>
<li>WordPress 6.5 was patched in 6.5.12</li>
<li>WordPress 6.4 was patched in 6.4.12</li>
</ul>
<p>Security releases were also made available for older branches down to WordPress 4.7.37.</p>
<p>This is particularly relevant for company websites.</p>
<p>A business may have had its WordPress site built five or ten years ago and still be running an older branch.</p>
<p>The website can appear perfectly functional from the outside while the software underneath it continues to age.</p>
<h2>What should you do?</h2>
<p>If your company website runs on WordPress, the immediate action is straightforward:</p>
<p><strong>Update WordPress to the patched version for your branch and verify that the update completed successfully.</strong></p>
<p>If somebody else manages your website, send them the CVE number and ask them to confirm that the site has been patched.</p>
<p>You can ask:</p>
<blockquote>
<p>Is our website affected by CVE-2026-87902, and can you confirm that WordPress has been updated to the patched release for our branch?</p>
</blockquote>
<p>You should also check whether automatic WordPress security updates are enabled.</p>
<p>Automatic updates can significantly reduce the window between a security release becoming available and the fix reaching your website.</p>
<p>But &quot;automatic updates are enabled&quot; should not become the end of the conversation.</p>
<p>Someone still needs to know whether updates completed successfully and whether the website continues to work afterwards.</p>
<h2>Updating software is only half the job</h2>
<p>The response to a security vulnerability is often presented as:</p>
<p>&quot;Just update WordPress.&quot;</p>
<p>Technically, that is the immediate fix.</p>
<p>Operationally, there is more to it.</p>
<p>A business website might contain:</p>
<ul>
<li>WordPress Core</li>
<li>a custom or third-party theme</li>
<li>form plugins</li>
<li>SEO plugins</li>
<li>analytics integrations</li>
<li>caching plugins</li>
<li>e-commerce functionality</li>
<li>custom PHP</li>
<li>JavaScript dependencies</li>
<li>external APIs</li>
<li>hosting infrastructure</li>
</ul>
<p>An update to one component can affect another.</p>
<p>That means a good maintenance process needs to do more than install updates.</p>
<p>It should also verify that critical parts of the website still work.</p>
<p>Can customers submit the contact form?</p>
<p>Can people complete a purchase?</p>
<p>Are marketing integrations still receiving leads?</p>
<p>Are redirects working?</p>
<p>Are important pages rendering correctly?</p>
<p>Can administrators still manage the content they need?</p>
<p>The more important the website is to the business, the less acceptable it becomes to rely on someone occasionally logging into WordPress and clicking &quot;Update.&quot;</p>
<h2>Who actually owns your company website?</h2>
<p>That is the more interesting question behind vulnerabilities like this.</p>
<p>A lot of companies have a website.</p>
<p>Far fewer have clearly defined ownership of the software running that website.</p>
<p>Perhaps an agency built it three years ago.</p>
<p>Perhaps an internal marketing team edits the content.</p>
<p>Perhaps a freelancer occasionally makes changes.</p>
<p>Perhaps the hosting company performs automatic backups.</p>
<p>Each party is involved with the website, but that does not necessarily mean anyone is actively responsible for monitoring its software dependencies and security advisories. (This ownership vacuum is often the <a href="/blog/hidden-cost-multiple-wordpress-sites">hidden operational cost of running WordPress sites</a>, where routine patching turns into an uncoordinated scramble across disconnected teams.)</p>
<p>Then a critical vulnerability appears.</p>
<p>Who sees it?</p>
<p>Who determines whether the site is affected?</p>
<p>Who installs the update?</p>
<p>Who checks whether the update succeeded?</p>
<p>Who verifies that the website still works?</p>
<p>Who investigates if the vulnerable version had been publicly exposed?</p>
<p>If the answer to those questions is unclear, that is a larger problem than any individual CVE.</p>
<h2>A website is a software system</h2>
<p>We still often talk about websites as if they were finished marketing assets.</p>
<p>You redesign the website.</p>
<p>You launch it.</p>
<p>The project is complete.</p>
<p>From a technical perspective, that is not really what happens.</p>
<p>A modern website is a running software system.</p>
<p>Its dependencies continue changing after launch.</p>
<p>Security researchers continue finding vulnerabilities.</p>
<p>Browsers change.</p>
<p>APIs change.</p>
<p>Programming languages reach end of life.</p>
<p>Plugins release updates.</p>
<p>CMS platforms release updates.</p>
<p>Hosting environments change.</p>
<p>The website might look almost identical for five years while almost everything underneath it requires ongoing maintenance.</p>
<p>CVE-2026-87902 is a particularly useful example because the vulnerability is not buried inside an obscure third-party WordPress plugin.</p>
<p>It is in WordPress Core itself.</p>
<p>The correct conclusion is not that WordPress is uniquely insecure.</p>
<p>All actively developed software can contain vulnerabilities.</p>
<p>The important question is whether your architecture and maintenance process allow you to respond when those vulnerabilities are discovered.</p>
<h2>This is also an architecture decision</h2>
<p>The technology used to build a website determines part of its long-term operational model.</p>
<p>WordPress makes it exceptionally easy to add functionality through plugins.</p>
<p>That can be a major advantage.</p>
<p>It also means that many WordPress installations accumulate a substantial collection of independently maintained components over time.</p>
<p>Each one becomes another dependency that needs to be understood, monitored and updated.</p>
<p>Other architectures move that responsibility elsewhere.</p>
<p>For example, as I discuss in my comparison of <a href="/blog/payload-cms-vs-wordpress-mental-model-shift">Payload CMS vs WordPress mental models</a>, moving from a plugin-and-theme hierarchy to an application-first stack allows more functionality to live directly within the application codebase rather than being assembled from third-party plugins.</p>
<p>That does not remove the security responsibility.</p>
<p>Payload, Next.js, Node.js, libraries and infrastructure all have vulnerabilities and security updates of their own.</p>
<p>What changes is how those dependencies are managed.</p>
<p>They become part of a development workflow where dependency versions can be tracked in code, changes can be reviewed, automated tests can run before deployment, and application behaviour can be verified as part of the release process.</p>
<p>Neither approach eliminates maintenance.</p>
<p>The question is whether the maintenance model fits the organisation operating the website. For teams that decide a plugin-heavy setup no longer matches their operational capacity, my <a href="/blog/wordpress-to-payload-migration-guide">WordPress to Payload migration guide</a> outlines how to transition content models and media into an owned code architecture without risking SEO.</p>
<h2>The takeaway</h2>
<p>If your company runs WordPress, update your site.</p>
<p>WordPress 7.1.2 fixes CVE-2026-87902 for the current branch, and patched releases have been made available for supported older branches going back to WordPress 4.7.</p>
<p>But after the update is complete, ask a second question:</p>
<p><strong>Who in our organisation actually owns the ongoing maintenance and security of this website?</strong></p>
<p>A website does not stop being software when the design is finished.</p>
<p>Launching it is the beginning of its operational life, not the end.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/wordpress-core-vulnerability-cve-2026-87902</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/wordpress-core-vulnerability-cve-2026-87902</guid>
            <category><![CDATA[Payload]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 08:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;If your company website runs on WordPress, there is another security update you should check immediately.&lt;/p&gt;
&lt;p&gt;This time, it is not a plugin. While recent alerts focused on third-party extensions—such as the &lt;a href=&quot;/blog/wordpress-gravity-forms-vulnerability-cve-2026-84434&quot;&gt;critical Gravity Forms vulnerability (CVE-2026-84434)&lt;/a&gt;—this release addresses a flaw in the platform itself.&lt;/p&gt;
&lt;p&gt;It honestly feels like we just analyzed a critical WordPress security alert yesterday—and looking at the calendar, it practically was. WordPress has been on a roll lately, and certainly not in a good way: two critical vulnerabilities surfacing in the span of just a couple of days.&lt;/p&gt;
&lt;p&gt;On September 22, 2026, WordPress released version 7.1.2 to patch a critical vulnerability in WordPress Core itself.&lt;/p&gt;
&lt;p&gt;The vulnerability, tracked as CVE-2026-87902, allows an unauthenticated attacker to manipulate how WordPress resolves page templates. Under the right conditions, this can make WordPress load a PHP file from outside the active theme directory.&lt;/p&gt;
&lt;p&gt;That can potentially lead to remote code execution and complete compromise of the website.&lt;/p&gt;
&lt;p&gt;No WordPress account is required.&lt;/p&gt;
&lt;p&gt;No administrator needs to click anything.&lt;/p&gt;
&lt;p&gt;There are important conditions that must be present for successful exploitation, so this does not mean every WordPress website is immediately exploitable.&lt;/p&gt;
&lt;p&gt;But WordPress itself classifies the vulnerability as critical and recommends updating sites immediately.&lt;/p&gt;
&lt;h2&gt;What is CVE-2026-87902?&lt;/h2&gt;
&lt;p&gt;The vulnerability exists in WordPress&amp;#39;s page-template resolution process.&lt;/p&gt;
&lt;p&gt;WordPress uses templates to determine how different types of pages should be rendered. The vulnerability makes it possible for an attacker to manipulate this process so WordPress includes a readable local PHP file located outside the directories of the active theme.&lt;/p&gt;
&lt;p&gt;This is known as a path traversal and local file inclusion vulnerability.&lt;/p&gt;
&lt;p&gt;On its own, loading another local file does not necessarily mean an attacker can execute arbitrary code.&lt;/p&gt;
&lt;p&gt;The dangerous part comes when a suitable PHP file exists elsewhere on the server.&lt;/p&gt;
&lt;p&gt;Under certain server configurations, an attacker could use that file to move from local file inclusion to remote code execution.&lt;/p&gt;
&lt;p&gt;At that point, the impact can become much more serious.&lt;/p&gt;
&lt;p&gt;An attacker who achieves remote code execution may be able to execute commands on the server, modify the website, access data or establish persistent access.&lt;/p&gt;
&lt;p&gt;That is why the issue has received a critical severity rating.&lt;/p&gt;
&lt;h2&gt;Is every WordPress website vulnerable?&lt;/h2&gt;
&lt;p&gt;No.&lt;/p&gt;
&lt;p&gt;This distinction matters.&lt;/p&gt;
&lt;p&gt;The vulnerable behaviour exists in WordPress Core, but successful exploitation depends on additional conditions being present.&lt;/p&gt;
&lt;p&gt;The active parent or child theme needs to contain a top-level directory beginning with &lt;code&gt;page-&lt;/code&gt;, such as:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;page-templates&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;The server must also contain a readable PHP file that can be usefully exploited when WordPress includes it.&lt;/p&gt;
&lt;p&gt;The official security advisory identifies Twenty Twelve and Twenty Fourteen as examples of WordPress themes with the relevant directory structure.&lt;/p&gt;
&lt;p&gt;It also names popular third-party themes including Neve, Hestia and Sydney.&lt;/p&gt;
&lt;p&gt;That does not mean every website using one of these themes can automatically be compromised.&lt;/p&gt;
&lt;p&gt;The server configuration and available PHP files matter too.&lt;/p&gt;
&lt;p&gt;The important distinction is between being affected by the vulnerable WordPress code and having an environment in which that vulnerability can successfully be turned into remote code execution.&lt;/p&gt;
&lt;p&gt;Unless you know your theme and server configuration well enough to establish that your site cannot meet those conditions, updating WordPress is the sensible response.&lt;/p&gt;
&lt;h2&gt;Which WordPress versions are affected?&lt;/h2&gt;
&lt;p&gt;The vulnerability reaches much further back than the latest release.&lt;/p&gt;
&lt;p&gt;WordPress 7.1.0 and 7.1.1 are affected, but WordPress has also released security fixes for older branches all the way back to WordPress 4.7.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;WordPress 7.1 was patched in 7.1.2&lt;/li&gt;
&lt;li&gt;WordPress 7.0 was patched in 7.0.6&lt;/li&gt;
&lt;li&gt;WordPress 6.9 was patched in 6.9.9&lt;/li&gt;
&lt;li&gt;WordPress 6.8 was patched in 6.8.10&lt;/li&gt;
&lt;li&gt;WordPress 6.7 was patched in 6.7.9&lt;/li&gt;
&lt;li&gt;WordPress 6.6 was patched in 6.6.9&lt;/li&gt;
&lt;li&gt;WordPress 6.5 was patched in 6.5.12&lt;/li&gt;
&lt;li&gt;WordPress 6.4 was patched in 6.4.12&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Security releases were also made available for older branches down to WordPress 4.7.37.&lt;/p&gt;
&lt;p&gt;This is particularly relevant for company websites.&lt;/p&gt;
&lt;p&gt;A business may have had its WordPress site built five or ten years ago and still be running an older branch.&lt;/p&gt;
&lt;p&gt;The website can appear perfectly functional from the outside while the software underneath it continues to age.&lt;/p&gt;
&lt;h2&gt;What should you do?&lt;/h2&gt;
&lt;p&gt;If your company website runs on WordPress, the immediate action is straightforward:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Update WordPress to the patched version for your branch and verify that the update completed successfully.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If somebody else manages your website, send them the CVE number and ask them to confirm that the site has been patched.&lt;/p&gt;
&lt;p&gt;You can ask:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Is our website affected by CVE-2026-87902, and can you confirm that WordPress has been updated to the patched release for our branch?&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;You should also check whether automatic WordPress security updates are enabled.&lt;/p&gt;
&lt;p&gt;Automatic updates can significantly reduce the window between a security release becoming available and the fix reaching your website.&lt;/p&gt;
&lt;p&gt;But &amp;quot;automatic updates are enabled&amp;quot; should not become the end of the conversation.&lt;/p&gt;
&lt;p&gt;Someone still needs to know whether updates completed successfully and whether the website continues to work afterwards.&lt;/p&gt;
&lt;h2&gt;Updating software is only half the job&lt;/h2&gt;
&lt;p&gt;The response to a security vulnerability is often presented as:&lt;/p&gt;
&lt;p&gt;&amp;quot;Just update WordPress.&amp;quot;&lt;/p&gt;
&lt;p&gt;Technically, that is the immediate fix.&lt;/p&gt;
&lt;p&gt;Operationally, there is more to it.&lt;/p&gt;
&lt;p&gt;A business website might contain:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;WordPress Core&lt;/li&gt;
&lt;li&gt;a custom or third-party theme&lt;/li&gt;
&lt;li&gt;form plugins&lt;/li&gt;
&lt;li&gt;SEO plugins&lt;/li&gt;
&lt;li&gt;analytics integrations&lt;/li&gt;
&lt;li&gt;caching plugins&lt;/li&gt;
&lt;li&gt;e-commerce functionality&lt;/li&gt;
&lt;li&gt;custom PHP&lt;/li&gt;
&lt;li&gt;JavaScript dependencies&lt;/li&gt;
&lt;li&gt;external APIs&lt;/li&gt;
&lt;li&gt;hosting infrastructure&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;An update to one component can affect another.&lt;/p&gt;
&lt;p&gt;That means a good maintenance process needs to do more than install updates.&lt;/p&gt;
&lt;p&gt;It should also verify that critical parts of the website still work.&lt;/p&gt;
&lt;p&gt;Can customers submit the contact form?&lt;/p&gt;
&lt;p&gt;Can people complete a purchase?&lt;/p&gt;
&lt;p&gt;Are marketing integrations still receiving leads?&lt;/p&gt;
&lt;p&gt;Are redirects working?&lt;/p&gt;
&lt;p&gt;Are important pages rendering correctly?&lt;/p&gt;
&lt;p&gt;Can administrators still manage the content they need?&lt;/p&gt;
&lt;p&gt;The more important the website is to the business, the less acceptable it becomes to rely on someone occasionally logging into WordPress and clicking &amp;quot;Update.&amp;quot;&lt;/p&gt;
&lt;h2&gt;Who actually owns your company website?&lt;/h2&gt;
&lt;p&gt;That is the more interesting question behind vulnerabilities like this.&lt;/p&gt;
&lt;p&gt;A lot of companies have a website.&lt;/p&gt;
&lt;p&gt;Far fewer have clearly defined ownership of the software running that website.&lt;/p&gt;
&lt;p&gt;Perhaps an agency built it three years ago.&lt;/p&gt;
&lt;p&gt;Perhaps an internal marketing team edits the content.&lt;/p&gt;
&lt;p&gt;Perhaps a freelancer occasionally makes changes.&lt;/p&gt;
&lt;p&gt;Perhaps the hosting company performs automatic backups.&lt;/p&gt;
&lt;p&gt;Each party is involved with the website, but that does not necessarily mean anyone is actively responsible for monitoring its software dependencies and security advisories. (This ownership vacuum is often the &lt;a href=&quot;/blog/hidden-cost-multiple-wordpress-sites&quot;&gt;hidden operational cost of running WordPress sites&lt;/a&gt;, where routine patching turns into an uncoordinated scramble across disconnected teams.)&lt;/p&gt;
&lt;p&gt;Then a critical vulnerability appears.&lt;/p&gt;
&lt;p&gt;Who sees it?&lt;/p&gt;
&lt;p&gt;Who determines whether the site is affected?&lt;/p&gt;
&lt;p&gt;Who installs the update?&lt;/p&gt;
&lt;p&gt;Who checks whether the update succeeded?&lt;/p&gt;
&lt;p&gt;Who verifies that the website still works?&lt;/p&gt;
&lt;p&gt;Who investigates if the vulnerable version had been publicly exposed?&lt;/p&gt;
&lt;p&gt;If the answer to those questions is unclear, that is a larger problem than any individual CVE.&lt;/p&gt;
&lt;h2&gt;A website is a software system&lt;/h2&gt;
&lt;p&gt;We still often talk about websites as if they were finished marketing assets.&lt;/p&gt;
&lt;p&gt;You redesign the website.&lt;/p&gt;
&lt;p&gt;You launch it.&lt;/p&gt;
&lt;p&gt;The project is complete.&lt;/p&gt;
&lt;p&gt;From a technical perspective, that is not really what happens.&lt;/p&gt;
&lt;p&gt;A modern website is a running software system.&lt;/p&gt;
&lt;p&gt;Its dependencies continue changing after launch.&lt;/p&gt;
&lt;p&gt;Security researchers continue finding vulnerabilities.&lt;/p&gt;
&lt;p&gt;Browsers change.&lt;/p&gt;
&lt;p&gt;APIs change.&lt;/p&gt;
&lt;p&gt;Programming languages reach end of life.&lt;/p&gt;
&lt;p&gt;Plugins release updates.&lt;/p&gt;
&lt;p&gt;CMS platforms release updates.&lt;/p&gt;
&lt;p&gt;Hosting environments change.&lt;/p&gt;
&lt;p&gt;The website might look almost identical for five years while almost everything underneath it requires ongoing maintenance.&lt;/p&gt;
&lt;p&gt;CVE-2026-87902 is a particularly useful example because the vulnerability is not buried inside an obscure third-party WordPress plugin.&lt;/p&gt;
&lt;p&gt;It is in WordPress Core itself.&lt;/p&gt;
&lt;p&gt;The correct conclusion is not that WordPress is uniquely insecure.&lt;/p&gt;
&lt;p&gt;All actively developed software can contain vulnerabilities.&lt;/p&gt;
&lt;p&gt;The important question is whether your architecture and maintenance process allow you to respond when those vulnerabilities are discovered.&lt;/p&gt;
&lt;h2&gt;This is also an architecture decision&lt;/h2&gt;
&lt;p&gt;The technology used to build a website determines part of its long-term operational model.&lt;/p&gt;
&lt;p&gt;WordPress makes it exceptionally easy to add functionality through plugins.&lt;/p&gt;
&lt;p&gt;That can be a major advantage.&lt;/p&gt;
&lt;p&gt;It also means that many WordPress installations accumulate a substantial collection of independently maintained components over time.&lt;/p&gt;
&lt;p&gt;Each one becomes another dependency that needs to be understood, monitored and updated.&lt;/p&gt;
&lt;p&gt;Other architectures move that responsibility elsewhere.&lt;/p&gt;
&lt;p&gt;For example, as I discuss in my comparison of &lt;a href=&quot;/blog/payload-cms-vs-wordpress-mental-model-shift&quot;&gt;Payload CMS vs WordPress mental models&lt;/a&gt;, moving from a plugin-and-theme hierarchy to an application-first stack allows more functionality to live directly within the application codebase rather than being assembled from third-party plugins.&lt;/p&gt;
&lt;p&gt;That does not remove the security responsibility.&lt;/p&gt;
&lt;p&gt;Payload, Next.js, Node.js, libraries and infrastructure all have vulnerabilities and security updates of their own.&lt;/p&gt;
&lt;p&gt;What changes is how those dependencies are managed.&lt;/p&gt;
&lt;p&gt;They become part of a development workflow where dependency versions can be tracked in code, changes can be reviewed, automated tests can run before deployment, and application behaviour can be verified as part of the release process.&lt;/p&gt;
&lt;p&gt;Neither approach eliminates maintenance.&lt;/p&gt;
&lt;p&gt;The question is whether the maintenance model fits the organisation operating the website. For teams that decide a plugin-heavy setup no longer matches their operational capacity, my &lt;a href=&quot;/blog/wordpress-to-payload-migration-guide&quot;&gt;WordPress to Payload migration guide&lt;/a&gt; outlines how to transition content models and media into an owned code architecture without risking SEO.&lt;/p&gt;
&lt;h2&gt;The takeaway&lt;/h2&gt;
&lt;p&gt;If your company runs WordPress, update your site.&lt;/p&gt;
&lt;p&gt;WordPress 7.1.2 fixes CVE-2026-87902 for the current branch, and patched releases have been made available for supported older branches going back to WordPress 4.7.&lt;/p&gt;
&lt;p&gt;But after the update is complete, ask a second question:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Who in our organisation actually owns the ongoing maintenance and security of this website?&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A website does not stop being software when the design is finished.&lt;/p&gt;
&lt;p&gt;Launching it is the beginning of its operational life, not the end.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/wordpress-core-vulnerability-cve-2026-87902"/>
        </item>
        <item>
            <title><![CDATA[Jev and the Rise of Decision Models: A New Paradigm for AI in Software]]></title>
            <description><![CDATA[<p>For the first time in a long time, I am genuinely excited about an AI release that isn&#39;t just another incremental parameter bump or larger context window.</p>
<p>Over the past two years, I’ve spent considerable time wiring generative LLMs into business logic—building sales qualification bots, triaging customer support tickets, and routing incoming leads based on budget and intent. Every time, the workflow was the same: prompt a massive reasoning model, enforce JSON schema output, and wait several seconds while tokens generated, all just to answer simple questions like <em>&quot;is this an enterprise lead?&quot;</em> or <em>&quot;which department handles this issue?&quot;</em> It felt clunky, burned unnecessary tokens, and introduced unpredictable latency into systems that needed immediate deterministic answers.</p>
<p>That is why the arrival of System One decision models like <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">Jev</a> (introduced by TypeSafe AI on September 15, 2026) is such a significant shift.</p>
<p>Instead of generating freeform text and hoping structured output parsers don&#39;t fail, decision models are purpose-built for three specific primitives: continuous scoring, binary true/false evaluation, and multi-class category routing. You pass your payload, define your candidate classes or questions, and receive instant typed judgments with calibrated probabilities. A workflow can ask a series of precise questions, use the answers to determine its next steps, sync embeddings into a vector store via <a href="/blog/auto-sync-cms-openai-vector-store">deterministic vector pipelines</a>, and reserve more capable reasoning models for problems that require deeper analysis.</p>
<p>In cloud deployments, the response times are near-instant, and with open-source alternatives rapidly appearing that you can host on your own infrastructure, the operational cost drops to fractions of a cent.</p>
<p>I see considerable potential for the CMS platforms, internal applications, and business workflows I work on. This article introduces the concept and the architectural shift behind it. I will cover practical integration, open-source alternatives, training, and evaluation in separate articles.</p>
<h2>A different interface for AI</h2>
<p>Most developers first experience modern AI through a generative language model.</p>
<p>We provide a prompt and receive an answer. The model might produce an explanation, write code, summarize a document, or return structured JSON.</p>
<p>That interface is useful because it supports an enormous range of tasks. It has also become our default approach to integrating AI into software.</p>
<p>Consider a customer submitting this message through a website:</p>
<blockquote>
<p>I was charged twice for my order. Please resolve this before Friday.</p>
</blockquote>
<p>The application needs to identify the appropriate department and determine whether the request requires urgent attention.</p>
<p>A generative LLM can analyze the message and return a JSON object containing a department and priority. <a href="/blog/enforcing-json-contracts-openai-automations-zod">Structured-output contracts</a> can constrain that response to an expected schema.</p>
<p>Jev provides a different interface for the same task.</p>
<p>The application supplies the message as context and asks which department should handle it. The possible answers might be <code>billing</code>, <code>sales</code>, and <code>technical</code>. It can also ask whether the customer expresses urgency.</p>
<p>Jev evaluates those predefined questions and returns typed decisions.</p>
<p>A generative LLM produces a response token by token. Jev evaluates the answer options you provide and returns decisions that software can use directly.</p>
<p>This is the essential distinction. The application defines the questions and controls what happens after the model answers them.</p>
<h2>Jev’s three decision primitives</h2>
<p>TypeSafe describes Jev’s interface as unstructured state in, typed probabilistic decisions out.</p>
<p>The state contains the information being evaluated. It could be a support message, an article draft, a document, a retrieved passage, or an AI agent’s proposed action.</p>
<p>The questions define what the application needs to know about that state.</p>
<p>Jev supports three question types:</p>
<table>
<thead>
<tr>
<th align="left">Primitive</th>
<th align="left">What it does</th>
<th align="left">Example</th>
</tr>
</thead>
<tbody><tr>
<td align="left"><strong>Choice</strong></td>
<td align="left">Selects from predefined options</td>
<td align="left">Which department should handle this request?</td>
</tr>
<tr>
<td align="left"><strong>Noul</strong></td>
<td align="left">Evaluates a yes/no condition</td>
<td align="left">Does the customer request a refund?</td>
</tr>
<tr>
<td align="left"><strong>Score</strong></td>
<td align="left">Evaluates a defined scale</td>
<td align="left">How frustrated does the customer appear?</td>
</tr>
</tbody></table>
<p>Multiple questions can be evaluated against the same state in one request. The <a href="https://docs.typesafe.ai/introduction/quickstart">official quick start</a> demonstrates this pattern with customer-support decisions.</p>
<p>Defining the answer space gives the application an explicit contract. If the permitted departments are <code>billing</code>, <code>sales</code>, and <code>technical</code>, the model cannot introduce an unexpected fourth department identifier.</p>
<p>A valid answer can still be incorrect. Jev might select <code>sales</code> when the message clearly belongs to <code>billing</code>. Typed outputs make integration more predictable; reliable automation still requires testing the quality of the decisions.</p>
<h2>The paradigm shift is in how we build applications</h2>
<p>Classification is established technology. Traditional machine-learning classifiers, BERT-based models, natural-language inference, and generative LLMs can all categorize information.</p>
<p>The emerging change is architectural.</p>
<p>Software already contains thousands of decisions. Some are expressed as explicit rules. Others depend on understanding what a person means.</p>
<p>An application can calculate whether an invoice is overdue from its due date and payment status. It can determine whether a user has publishing permission from their assigned role.</p>
<p>Interpreting a customer’s intent is different. The customer may describe a billing problem without mentioning billing. A document may contain a sensitive claim without using any of the keywords an application expects.</p>
<p>Semantic models make it possible to evaluate these meaning-dependent questions within an ordinary workflow.</p>
<p>A website can classify an inquiry before creating a CRM record. A CMS can flag a draft for review. An internal application can identify requests that appear to fall outside its usual process.</p>
<p>Each evaluation becomes a bounded responsibility inside a larger system.</p>
<p>The architectural shift is toward composing applications from deterministic rules, semantic decisions, and deeper reasoning, with each component responsible for a different kind of work.</p>
<p>That separation also gives developers a clearer way to evaluate and replace individual components.</p>
<h2>Understanding the business becomes more important</h2>
<p>This is the part of the approach that interests me most.</p>
<p>I recently worked on a multi-brand <a href="/blog/multi-tenant-dev-environment-nextjs-payload">Payload CMS architecture</a> involving products, articles, recipes, departmental responsibilities, permissions, and editorial approval workflows.</p>
<p>Designing that system required understanding how the organization operates. Different teams own different content. Some material requires additional review. Publishing depends on permissions and workflow state.</p>
<p>A decision model could extend such a system by suggesting which department should handle a draft or identifying content that warrants specialist attention. The CMS would continue enforcing permissions, assigning authorized reviewers via <a href="/blog/payload-admin-ui-components-glossary-v3-6">custom administrative interfaces</a>, and controlling publication.</p>
<p>I have not deployed Jev in that project. The architecture provides a concrete example of where semantic decisions could fit.</p>
<p>To design those decisions, we need to understand the business processes behind them.</p>
<p>“Evaluate this article” is a vague instruction. “Does this article contain a product claim that requires specialist review under our editorial policy?” defines a more precise responsibility.</p>
<p>The second question also exposes work that must happen around the model. Someone needs to define the policy, identify relevant evidence, establish the possible outcomes, and decide how the workflow should respond.</p>
<p>Knowing the business well enough to ask the right questions becomes a central part of building AI-enabled software, demanding <a href="/blog/client-needs-judgment-not-preferred-technology">sound engineering judgment over technology hype</a>.</p>
<p>As decision models become cheaper and faster, identifying valuable decisions may become as important as choosing the models that evaluate them.</p>
<h2>Speed and cost make small decisions interesting</h2>
<p>TypeSafe <a href="https://typesafe.ai/blog/introducing-system-one-models-and-jev">advertises Jev</a> at approximately $0.042 per million input tokens, with no additional output-token charge. The company reports response times of roughly 70 to 500 milliseconds.</p>
<p>Those are vendor-reported figures. Actual performance and cost-effectiveness need to be established for a specific workload.</p>
<p>The interesting implication is how frequently an application might be able to evaluate meaning.</p>
<p>A website could classify every incoming inquiry. A CMS could assess each draft as it enters an approval workflow. An AI agent could evaluate whether its next proposed action requires additional scrutiny.</p>
<p>These are small decisions, but they occur repeatedly.</p>
<p>Low inference cost expands the set of workflows worth investigating. It also makes it practical to consider several focused evaluations instead of asking one model to handle a broad, loosely defined task.</p>
<p>Model price is only one part of the calculation. Integration, infrastructure, monitoring, incorrect classifications, and human review still carry costs. The value of automation depends on the outcomes of the complete workflow.</p>
<h2>Open source makes this bigger than one model</h2>
<p>The interest surrounding Jev has already encouraged developers to explore similar decision-oriented approaches using open models.</p>
<p>One example is <a href="https://github.com/bespokelabsai/nimble">Bespoke Nimble</a>. It uses a Qwen-based model to evaluate predefined answer candidates and return typed decisions. Its maintainers have published a local-inference approach and a training recipe. They state that they did not distill Jev’s outputs.</p>
<p>This creates several possibilities for developers.</p>
<p>A team can evaluate a managed decision API, explore a model running on its own infrastructure, or adapt an open model to a specific domain.</p>
<p>These approaches have different tradeoffs. A hosted service transfers much of the inference operation to a provider, while <a href="/blog/self-hosted-ai-vs-api-providers-decision-framework">evaluating self-hosted AI vs API providers</a> gives a team deeper deployment control at the cost of hardware and maintenance overhead.</p>
<p>Open implementations also vary in accuracy and generalization. Similar interfaces do not establish equivalent model performance.</p>
<p>The broader significance is that decision-oriented AI is becoming an architectural pattern that can be explored independently of a single provider.</p>
<h2>Teaching models which evidence changes a decision</h2>
<p>One of the most useful ideas emerging from the open-source work is contrastive training.</p>
<p>Bespoke Nimble describes an approach built around pairs of examples that are almost identical. One important fact changes, and the correct answer changes with it.</p>
<p>Consider two customer messages:</p>
<blockquote>
<p>I want a refund for this order.</p>
</blockquote>
<blockquote>
<p>I do not want a refund for this order.</p>
</blockquote>
<p>The difference is small, but it changes the customer’s intent.</p>
<p>Training examples like these help show a model which piece of evidence should affect a classification.</p>
<p>The same principle applies to more complex business decisions. A company may need to distinguish between an inquiry that mentions a product and one that makes a claim about what the product can treat. It may need to identify the exact circumstances that require escalation.</p>
<p>This is where business knowledge becomes training data. The people who understand a process can help define examples, label outcomes, and identify situations that a model must distinguish.</p>
<p>Contrastive examples also give developers a useful way to test a model. Changing a decisive fact should change the answer. Changing an irrelevant detail should generally leave it unchanged.</p>
<p>A handful of examples cannot establish reliability. A production model needs representative data, realistic edge cases, and independent evaluation.</p>
<p>I will explore business-specific training in a separate article.</p>
<h2>Probabilities create another kind of workflow</h2>
<p>Jev returns probabilities alongside its decisions.</p>
<p>That creates an opportunity to treat straightforward and uncertain cases differently. A routine request could enter a standard queue, while an ambiguous request receives more analysis or human review.</p>
<p>The probabilities need to be interpreted carefully.</p>
<p>A model reporting 95% probability does not guarantee that a particular decision is correct. Developers need to test calibration: whether predictions made with a given level of confidence are correct at a corresponding rate across representative examples.</p>
<p>This matters especially when a decision carries significant consequences.</p>
<p>Sending a support request to the wrong queue may cause a delay. Publishing sensitive content without review or authorizing an inappropriate action creates a different level of risk.</p>
<p>A semantic model can provide an assessment. The application must determine how that assessment affects the workflow.</p>
<p>TypeSafe’s <a href="https://docs.typesafe.ai/model-jaggedness/jev-1.13">documentation of Jev’s limitations</a> also identifies weaknesses involving numerical precision, date comparisons, multi-step reasoning, and other tasks requiring exact or extended computation.</p>
<p>Permissions, arithmetic, and other deterministic requirements should remain in code. Consequential decisions need safeguards appropriate to their risks.</p>
<h2>System One and System Two belong together</h2>
<p>TypeSafe uses the term System One for fast, decision-oriented models. It borrows the name from the distinction between fast judgment and slower, deliberate reasoning.</p>
<p>For developers, this is a useful analogy for dividing work between components.</p>
<p>A decision model can classify an incoming request. A reasoning model can investigate an unfamiliar problem or examine a complex case. Application code can validate conditions and execute authorized actions.</p>
<p>A workflow can combine these capabilities without requiring every step to use the same model.</p>
<p>That raises a useful architectural question: which decisions need semantic interpretation, which require extended reasoning, and which already have exact answers in code?</p>
<p>Answering it requires understanding both the technical capabilities and the business process.</p>
<p>It also provides the foundation for the next stage of this discussion: how to route work between models, evaluate the quality of each decision, and design the actions that follow.</p>
<h2>What I will explore next</h2>
<p>This article establishes the conceptual foundation. The implementation questions deserve their own treatment.</p>
<p>I plan to explore Jev’s API and TypeScript integration, open-source and self-hosted alternatives, contrastive training for business-specific decisions, and methods for evaluating accuracy, calibration, latency, and cost.</p>
<p>Those topics will move from the idea to practical engineering choices.</p>
<h2>FAQ</h2>
<h3>Is Jev a completely new kind of AI?</h3>
<p>Jev is a specialized decision-model product with a typed, probabilistic interface. Classification and probabilistic prediction existed long before its launch. The emerging paradigm discussed here concerns how developers compose fast semantic decisions inside applications.</p>
<h3>Can a regular LLM perform the same tasks?</h3>
<p>Yes. Generative LLMs can classify information and return structured outputs. The relevant comparison is their performance on a specific workload, including accuracy, calibration, speed, and cost.</p>
<h3>Can Jev replace reasoning models or AI agents?</h3>
<p>Jev is designed for bounded judgments. Open-ended generation and complex investigation require other capabilities. A larger application can combine decision models, reasoning models, and deterministic code.</p>
<h3>Can a business train a model on its own decisions?</h3>
<p>Some open-source implementations support adapting models with labeled examples, including contrastive pairs. The process requires clearly defined decisions, representative data, and independent evaluation.</p>
<h3>Can the application trust a high probability?</h3>
<p>A high reported probability is insufficient on its own. The model needs to be evaluated for calibration, and the consequences of an incorrect decision must determine the safeguards.</p>
<h2>Conclusion</h2>
<p>Jev has brought attention to an approach that could change how we design AI-enabled software: making semantic judgments fast and inexpensive enough to use throughout ordinary applications.</p>
<p>The opportunity extends beyond classification. Developers can break a workflow into precise questions, evaluate them with appropriate models, and connect the answers to existing software that controls what happens next.</p>
<p>For the CMS platforms and internal applications I work on, the most interesting implication is how closely this brings business understanding and software architecture together.</p>
<p>The better we understand the decisions inside a business, the more precisely we can define them, evaluate them, and build useful automation around them.</p>
<p>I will explore the practical implementation and model choices in the next articles.</p>
<p>Thanks,<br>Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/jev-decision-models-system-one-ai-architecture</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/jev-decision-models-system-one-ai-architecture</guid>
            <category><![CDATA[AI]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 16:45:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;For the first time in a long time, I am genuinely excited about an AI release that isn&amp;#39;t just another incremental parameter bump or larger context window.&lt;/p&gt;
&lt;p&gt;Over the past two years, I’ve spent considerable time wiring generative LLMs into business logic—building sales qualification bots, triaging customer support tickets, and routing incoming leads based on budget and intent. Every time, the workflow was the same: prompt a massive reasoning model, enforce JSON schema output, and wait several seconds while tokens generated, all just to answer simple questions like &lt;em&gt;&amp;quot;is this an enterprise lead?&amp;quot;&lt;/em&gt; or &lt;em&gt;&amp;quot;which department handles this issue?&amp;quot;&lt;/em&gt; It felt clunky, burned unnecessary tokens, and introduced unpredictable latency into systems that needed immediate deterministic answers.&lt;/p&gt;
&lt;p&gt;That is why the arrival of System One decision models like &lt;a href=&quot;https://typesafe.ai/blog/introducing-system-one-models-and-jev&quot;&gt;Jev&lt;/a&gt; (introduced by TypeSafe AI on September 15, 2026) is such a significant shift.&lt;/p&gt;
&lt;p&gt;Instead of generating freeform text and hoping structured output parsers don&amp;#39;t fail, decision models are purpose-built for three specific primitives: continuous scoring, binary true/false evaluation, and multi-class category routing. You pass your payload, define your candidate classes or questions, and receive instant typed judgments with calibrated probabilities. A workflow can ask a series of precise questions, use the answers to determine its next steps, sync embeddings into a vector store via &lt;a href=&quot;/blog/auto-sync-cms-openai-vector-store&quot;&gt;deterministic vector pipelines&lt;/a&gt;, and reserve more capable reasoning models for problems that require deeper analysis.&lt;/p&gt;
&lt;p&gt;In cloud deployments, the response times are near-instant, and with open-source alternatives rapidly appearing that you can host on your own infrastructure, the operational cost drops to fractions of a cent.&lt;/p&gt;
&lt;p&gt;I see considerable potential for the CMS platforms, internal applications, and business workflows I work on. This article introduces the concept and the architectural shift behind it. I will cover practical integration, open-source alternatives, training, and evaluation in separate articles.&lt;/p&gt;
&lt;h2&gt;A different interface for AI&lt;/h2&gt;
&lt;p&gt;Most developers first experience modern AI through a generative language model.&lt;/p&gt;
&lt;p&gt;We provide a prompt and receive an answer. The model might produce an explanation, write code, summarize a document, or return structured JSON.&lt;/p&gt;
&lt;p&gt;That interface is useful because it supports an enormous range of tasks. It has also become our default approach to integrating AI into software.&lt;/p&gt;
&lt;p&gt;Consider a customer submitting this message through a website:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;I was charged twice for my order. Please resolve this before Friday.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The application needs to identify the appropriate department and determine whether the request requires urgent attention.&lt;/p&gt;
&lt;p&gt;A generative LLM can analyze the message and return a JSON object containing a department and priority. &lt;a href=&quot;/blog/enforcing-json-contracts-openai-automations-zod&quot;&gt;Structured-output contracts&lt;/a&gt; can constrain that response to an expected schema.&lt;/p&gt;
&lt;p&gt;Jev provides a different interface for the same task.&lt;/p&gt;
&lt;p&gt;The application supplies the message as context and asks which department should handle it. The possible answers might be &lt;code&gt;billing&lt;/code&gt;, &lt;code&gt;sales&lt;/code&gt;, and &lt;code&gt;technical&lt;/code&gt;. It can also ask whether the customer expresses urgency.&lt;/p&gt;
&lt;p&gt;Jev evaluates those predefined questions and returns typed decisions.&lt;/p&gt;
&lt;p&gt;A generative LLM produces a response token by token. Jev evaluates the answer options you provide and returns decisions that software can use directly.&lt;/p&gt;
&lt;p&gt;This is the essential distinction. The application defines the questions and controls what happens after the model answers them.&lt;/p&gt;
&lt;h2&gt;Jev’s three decision primitives&lt;/h2&gt;
&lt;p&gt;TypeSafe describes Jev’s interface as unstructured state in, typed probabilistic decisions out.&lt;/p&gt;
&lt;p&gt;The state contains the information being evaluated. It could be a support message, an article draft, a document, a retrieved passage, or an AI agent’s proposed action.&lt;/p&gt;
&lt;p&gt;The questions define what the application needs to know about that state.&lt;/p&gt;
&lt;p&gt;Jev supports three question types:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th align=&quot;left&quot;&gt;Primitive&lt;/th&gt;
&lt;th align=&quot;left&quot;&gt;What it does&lt;/th&gt;
&lt;th align=&quot;left&quot;&gt;Example&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Choice&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&quot;left&quot;&gt;Selects from predefined options&lt;/td&gt;
&lt;td align=&quot;left&quot;&gt;Which department should handle this request?&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Noul&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&quot;left&quot;&gt;Evaluates a yes/no condition&lt;/td&gt;
&lt;td align=&quot;left&quot;&gt;Does the customer request a refund?&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td align=&quot;left&quot;&gt;&lt;strong&gt;Score&lt;/strong&gt;&lt;/td&gt;
&lt;td align=&quot;left&quot;&gt;Evaluates a defined scale&lt;/td&gt;
&lt;td align=&quot;left&quot;&gt;How frustrated does the customer appear?&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;Multiple questions can be evaluated against the same state in one request. The &lt;a href=&quot;https://docs.typesafe.ai/introduction/quickstart&quot;&gt;official quick start&lt;/a&gt; demonstrates this pattern with customer-support decisions.&lt;/p&gt;
&lt;p&gt;Defining the answer space gives the application an explicit contract. If the permitted departments are &lt;code&gt;billing&lt;/code&gt;, &lt;code&gt;sales&lt;/code&gt;, and &lt;code&gt;technical&lt;/code&gt;, the model cannot introduce an unexpected fourth department identifier.&lt;/p&gt;
&lt;p&gt;A valid answer can still be incorrect. Jev might select &lt;code&gt;sales&lt;/code&gt; when the message clearly belongs to &lt;code&gt;billing&lt;/code&gt;. Typed outputs make integration more predictable; reliable automation still requires testing the quality of the decisions.&lt;/p&gt;
&lt;h2&gt;The paradigm shift is in how we build applications&lt;/h2&gt;
&lt;p&gt;Classification is established technology. Traditional machine-learning classifiers, BERT-based models, natural-language inference, and generative LLMs can all categorize information.&lt;/p&gt;
&lt;p&gt;The emerging change is architectural.&lt;/p&gt;
&lt;p&gt;Software already contains thousands of decisions. Some are expressed as explicit rules. Others depend on understanding what a person means.&lt;/p&gt;
&lt;p&gt;An application can calculate whether an invoice is overdue from its due date and payment status. It can determine whether a user has publishing permission from their assigned role.&lt;/p&gt;
&lt;p&gt;Interpreting a customer’s intent is different. The customer may describe a billing problem without mentioning billing. A document may contain a sensitive claim without using any of the keywords an application expects.&lt;/p&gt;
&lt;p&gt;Semantic models make it possible to evaluate these meaning-dependent questions within an ordinary workflow.&lt;/p&gt;
&lt;p&gt;A website can classify an inquiry before creating a CRM record. A CMS can flag a draft for review. An internal application can identify requests that appear to fall outside its usual process.&lt;/p&gt;
&lt;p&gt;Each evaluation becomes a bounded responsibility inside a larger system.&lt;/p&gt;
&lt;p&gt;The architectural shift is toward composing applications from deterministic rules, semantic decisions, and deeper reasoning, with each component responsible for a different kind of work.&lt;/p&gt;
&lt;p&gt;That separation also gives developers a clearer way to evaluate and replace individual components.&lt;/p&gt;
&lt;h2&gt;Understanding the business becomes more important&lt;/h2&gt;
&lt;p&gt;This is the part of the approach that interests me most.&lt;/p&gt;
&lt;p&gt;I recently worked on a multi-brand &lt;a href=&quot;/blog/multi-tenant-dev-environment-nextjs-payload&quot;&gt;Payload CMS architecture&lt;/a&gt; involving products, articles, recipes, departmental responsibilities, permissions, and editorial approval workflows.&lt;/p&gt;
&lt;p&gt;Designing that system required understanding how the organization operates. Different teams own different content. Some material requires additional review. Publishing depends on permissions and workflow state.&lt;/p&gt;
&lt;p&gt;A decision model could extend such a system by suggesting which department should handle a draft or identifying content that warrants specialist attention. The CMS would continue enforcing permissions, assigning authorized reviewers via &lt;a href=&quot;/blog/payload-admin-ui-components-glossary-v3-6&quot;&gt;custom administrative interfaces&lt;/a&gt;, and controlling publication.&lt;/p&gt;
&lt;p&gt;I have not deployed Jev in that project. The architecture provides a concrete example of where semantic decisions could fit.&lt;/p&gt;
&lt;p&gt;To design those decisions, we need to understand the business processes behind them.&lt;/p&gt;
&lt;p&gt;“Evaluate this article” is a vague instruction. “Does this article contain a product claim that requires specialist review under our editorial policy?” defines a more precise responsibility.&lt;/p&gt;
&lt;p&gt;The second question also exposes work that must happen around the model. Someone needs to define the policy, identify relevant evidence, establish the possible outcomes, and decide how the workflow should respond.&lt;/p&gt;
&lt;p&gt;Knowing the business well enough to ask the right questions becomes a central part of building AI-enabled software, demanding &lt;a href=&quot;/blog/client-needs-judgment-not-preferred-technology&quot;&gt;sound engineering judgment over technology hype&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As decision models become cheaper and faster, identifying valuable decisions may become as important as choosing the models that evaluate them.&lt;/p&gt;
&lt;h2&gt;Speed and cost make small decisions interesting&lt;/h2&gt;
&lt;p&gt;TypeSafe &lt;a href=&quot;https://typesafe.ai/blog/introducing-system-one-models-and-jev&quot;&gt;advertises Jev&lt;/a&gt; at approximately $0.042 per million input tokens, with no additional output-token charge. The company reports response times of roughly 70 to 500 milliseconds.&lt;/p&gt;
&lt;p&gt;Those are vendor-reported figures. Actual performance and cost-effectiveness need to be established for a specific workload.&lt;/p&gt;
&lt;p&gt;The interesting implication is how frequently an application might be able to evaluate meaning.&lt;/p&gt;
&lt;p&gt;A website could classify every incoming inquiry. A CMS could assess each draft as it enters an approval workflow. An AI agent could evaluate whether its next proposed action requires additional scrutiny.&lt;/p&gt;
&lt;p&gt;These are small decisions, but they occur repeatedly.&lt;/p&gt;
&lt;p&gt;Low inference cost expands the set of workflows worth investigating. It also makes it practical to consider several focused evaluations instead of asking one model to handle a broad, loosely defined task.&lt;/p&gt;
&lt;p&gt;Model price is only one part of the calculation. Integration, infrastructure, monitoring, incorrect classifications, and human review still carry costs. The value of automation depends on the outcomes of the complete workflow.&lt;/p&gt;
&lt;h2&gt;Open source makes this bigger than one model&lt;/h2&gt;
&lt;p&gt;The interest surrounding Jev has already encouraged developers to explore similar decision-oriented approaches using open models.&lt;/p&gt;
&lt;p&gt;One example is &lt;a href=&quot;https://github.com/bespokelabsai/nimble&quot;&gt;Bespoke Nimble&lt;/a&gt;. It uses a Qwen-based model to evaluate predefined answer candidates and return typed decisions. Its maintainers have published a local-inference approach and a training recipe. They state that they did not distill Jev’s outputs.&lt;/p&gt;
&lt;p&gt;This creates several possibilities for developers.&lt;/p&gt;
&lt;p&gt;A team can evaluate a managed decision API, explore a model running on its own infrastructure, or adapt an open model to a specific domain.&lt;/p&gt;
&lt;p&gt;These approaches have different tradeoffs. A hosted service transfers much of the inference operation to a provider, while &lt;a href=&quot;/blog/self-hosted-ai-vs-api-providers-decision-framework&quot;&gt;evaluating self-hosted AI vs API providers&lt;/a&gt; gives a team deeper deployment control at the cost of hardware and maintenance overhead.&lt;/p&gt;
&lt;p&gt;Open implementations also vary in accuracy and generalization. Similar interfaces do not establish equivalent model performance.&lt;/p&gt;
&lt;p&gt;The broader significance is that decision-oriented AI is becoming an architectural pattern that can be explored independently of a single provider.&lt;/p&gt;
&lt;h2&gt;Teaching models which evidence changes a decision&lt;/h2&gt;
&lt;p&gt;One of the most useful ideas emerging from the open-source work is contrastive training.&lt;/p&gt;
&lt;p&gt;Bespoke Nimble describes an approach built around pairs of examples that are almost identical. One important fact changes, and the correct answer changes with it.&lt;/p&gt;
&lt;p&gt;Consider two customer messages:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;I want a refund for this order.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;blockquote&gt;
&lt;p&gt;I do not want a refund for this order.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The difference is small, but it changes the customer’s intent.&lt;/p&gt;
&lt;p&gt;Training examples like these help show a model which piece of evidence should affect a classification.&lt;/p&gt;
&lt;p&gt;The same principle applies to more complex business decisions. A company may need to distinguish between an inquiry that mentions a product and one that makes a claim about what the product can treat. It may need to identify the exact circumstances that require escalation.&lt;/p&gt;
&lt;p&gt;This is where business knowledge becomes training data. The people who understand a process can help define examples, label outcomes, and identify situations that a model must distinguish.&lt;/p&gt;
&lt;p&gt;Contrastive examples also give developers a useful way to test a model. Changing a decisive fact should change the answer. Changing an irrelevant detail should generally leave it unchanged.&lt;/p&gt;
&lt;p&gt;A handful of examples cannot establish reliability. A production model needs representative data, realistic edge cases, and independent evaluation.&lt;/p&gt;
&lt;p&gt;I will explore business-specific training in a separate article.&lt;/p&gt;
&lt;h2&gt;Probabilities create another kind of workflow&lt;/h2&gt;
&lt;p&gt;Jev returns probabilities alongside its decisions.&lt;/p&gt;
&lt;p&gt;That creates an opportunity to treat straightforward and uncertain cases differently. A routine request could enter a standard queue, while an ambiguous request receives more analysis or human review.&lt;/p&gt;
&lt;p&gt;The probabilities need to be interpreted carefully.&lt;/p&gt;
&lt;p&gt;A model reporting 95% probability does not guarantee that a particular decision is correct. Developers need to test calibration: whether predictions made with a given level of confidence are correct at a corresponding rate across representative examples.&lt;/p&gt;
&lt;p&gt;This matters especially when a decision carries significant consequences.&lt;/p&gt;
&lt;p&gt;Sending a support request to the wrong queue may cause a delay. Publishing sensitive content without review or authorizing an inappropriate action creates a different level of risk.&lt;/p&gt;
&lt;p&gt;A semantic model can provide an assessment. The application must determine how that assessment affects the workflow.&lt;/p&gt;
&lt;p&gt;TypeSafe’s &lt;a href=&quot;https://docs.typesafe.ai/model-jaggedness/jev-1.13&quot;&gt;documentation of Jev’s limitations&lt;/a&gt; also identifies weaknesses involving numerical precision, date comparisons, multi-step reasoning, and other tasks requiring exact or extended computation.&lt;/p&gt;
&lt;p&gt;Permissions, arithmetic, and other deterministic requirements should remain in code. Consequential decisions need safeguards appropriate to their risks.&lt;/p&gt;
&lt;h2&gt;System One and System Two belong together&lt;/h2&gt;
&lt;p&gt;TypeSafe uses the term System One for fast, decision-oriented models. It borrows the name from the distinction between fast judgment and slower, deliberate reasoning.&lt;/p&gt;
&lt;p&gt;For developers, this is a useful analogy for dividing work between components.&lt;/p&gt;
&lt;p&gt;A decision model can classify an incoming request. A reasoning model can investigate an unfamiliar problem or examine a complex case. Application code can validate conditions and execute authorized actions.&lt;/p&gt;
&lt;p&gt;A workflow can combine these capabilities without requiring every step to use the same model.&lt;/p&gt;
&lt;p&gt;That raises a useful architectural question: which decisions need semantic interpretation, which require extended reasoning, and which already have exact answers in code?&lt;/p&gt;
&lt;p&gt;Answering it requires understanding both the technical capabilities and the business process.&lt;/p&gt;
&lt;p&gt;It also provides the foundation for the next stage of this discussion: how to route work between models, evaluate the quality of each decision, and design the actions that follow.&lt;/p&gt;
&lt;h2&gt;What I will explore next&lt;/h2&gt;
&lt;p&gt;This article establishes the conceptual foundation. The implementation questions deserve their own treatment.&lt;/p&gt;
&lt;p&gt;I plan to explore Jev’s API and TypeScript integration, open-source and self-hosted alternatives, contrastive training for business-specific decisions, and methods for evaluating accuracy, calibration, latency, and cost.&lt;/p&gt;
&lt;p&gt;Those topics will move from the idea to practical engineering choices.&lt;/p&gt;
&lt;h2&gt;FAQ&lt;/h2&gt;
&lt;h3&gt;Is Jev a completely new kind of AI?&lt;/h3&gt;
&lt;p&gt;Jev is a specialized decision-model product with a typed, probabilistic interface. Classification and probabilistic prediction existed long before its launch. The emerging paradigm discussed here concerns how developers compose fast semantic decisions inside applications.&lt;/p&gt;
&lt;h3&gt;Can a regular LLM perform the same tasks?&lt;/h3&gt;
&lt;p&gt;Yes. Generative LLMs can classify information and return structured outputs. The relevant comparison is their performance on a specific workload, including accuracy, calibration, speed, and cost.&lt;/p&gt;
&lt;h3&gt;Can Jev replace reasoning models or AI agents?&lt;/h3&gt;
&lt;p&gt;Jev is designed for bounded judgments. Open-ended generation and complex investigation require other capabilities. A larger application can combine decision models, reasoning models, and deterministic code.&lt;/p&gt;
&lt;h3&gt;Can a business train a model on its own decisions?&lt;/h3&gt;
&lt;p&gt;Some open-source implementations support adapting models with labeled examples, including contrastive pairs. The process requires clearly defined decisions, representative data, and independent evaluation.&lt;/p&gt;
&lt;h3&gt;Can the application trust a high probability?&lt;/h3&gt;
&lt;p&gt;A high reported probability is insufficient on its own. The model needs to be evaluated for calibration, and the consequences of an incorrect decision must determine the safeguards.&lt;/p&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Jev has brought attention to an approach that could change how we design AI-enabled software: making semantic judgments fast and inexpensive enough to use throughout ordinary applications.&lt;/p&gt;
&lt;p&gt;The opportunity extends beyond classification. Developers can break a workflow into precise questions, evaluate them with appropriate models, and connect the answers to existing software that controls what happens next.&lt;/p&gt;
&lt;p&gt;For the CMS platforms and internal applications I work on, the most interesting implication is how closely this brings business understanding and software architecture together.&lt;/p&gt;
&lt;p&gt;The better we understand the decisions inside a business, the more precisely we can define them, evaluate them, and build useful automation around them.&lt;/p&gt;
&lt;p&gt;I will explore the practical implementation and model choices in the next articles.&lt;/p&gt;
&lt;p&gt;Thanks,&lt;br&gt;Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/jev-decision-models-system-one-ai-architecture"/>
        </item>
        <item>
            <title><![CDATA[Stop Starting From Scratch: How Vertical Slices Build Reusable Frontends]]></title>
            <description><![CDATA[<p>If you listen to a project manager, a frontend developer, and a product designer discuss building a new web feature, you will often hear three completely different vocabularies for the same screen.</p>
<p>The designer talks about design systems and visual consistency. The developer talks about utility classes, shadcn components, or headless primitives. The project manager just wants to know why building a product listing on the homepage took three weeks, and why building an almost identical listing on the category page is slated to take three more.</p>
<p>When teams start from scratch with every ticket, the confusion isn&#39;t caused by bad code. It&#39;s caused by a failure to agree on <strong>levels of abstraction</strong>:</p>
<ol>
<li><strong>The Styling Layer (The Foundation)</strong>: Where raw visual tokens live—custom CSS, CSS Modules, or atomic utility classes like Tailwind.</li>
<li><strong>The Component &amp; Primitive Layer (The Machinery)</strong>: Interactive elements like buttons, dialogs, sheets, and dropdowns that bundle headless interaction behavior with styling contracts (such as Radix or Base UI).</li>
<li><strong>The Section &amp; Content Block Layer (The Composition)</strong>: Structured, relational CMS blocks—such as Payload CMS layout blocks—that compose existing primitives into repeatable page sections without re-declaring their internal logic.</li>
</ol>
<p>When technical leaders make these abstraction layers explicit, teams stop rebuilding components from scratch and start delivering features as cohesive, reusable vertical slices.</p>
<h2>Every abstraction saves you from rebuilding something below it</h2>
<p>At the lowest level, the browser already gives us HTML elements, CSS, JavaScript, and built-in interaction behavior.</p>
<p>We can work directly with those capabilities. We can write bespoke styles, implement custom controls, and arrange everything ourselves.</p>
<p>But we can also build—or adopt—abstractions that package recurring decisions.</p>
<p>A styling system gives us reusable tokens, typography, and layout conventions. A UI primitive handles difficult interaction behavior. A styled component combines behavior with a particular visual treatment. A section arranges components into something meaningful, such as a product grid. A page template composes sections into a repeatable page structure.</p>
<p>Each level potentially saves us from making the same lower-level decisions again.</p>
<p>Think of the available building blocks like this:</p>
<table>
<thead>
<tr>
<th>Level</th>
<th>Example</th>
</tr>
</thead>
<tbody><tr>
<td>Browser capabilities</td>
<td>HTML, CSS, JavaScript</td>
</tr>
<tr>
<td>Styling abstractions</td>
<td>Tokens, Tailwind utilities, reusable CSS patterns</td>
</tr>
<tr>
<td>UI behavior primitives</td>
<td>Select, Dialog, Combobox</td>
</tr>
<tr>
<td>Application components</td>
<td>ProductCard, ProductSearch</td>
</tr>
<tr>
<td>Sections</td>
<td>ProductGrid, FilterPanel</td>
</tr>
<tr>
<td>Page templates</td>
<td>Product listing, product detail</td>
</tr>
<tr>
<td>Complete features</td>
<td>A working, data-connected product listing</td>
</tr>
</tbody></table>
<p>For complex accessibility, focus management, and keyboard handling at the behavioral level, adopting <a href="/blog/headless-ui-primitives-when-to-own-ui-behavior">Headless UI Primitives</a> (such as Radix, Base UI, or Floating UI) allows teams to own presentation without reinventing intricate state machines.</p>
<p>This isn&#39;t a rigid technical hierarchy. Styling and interaction primitives, for example, address different concerns and can be combined in different ways.</p>
<p>It&#39;s a way to recognize <strong>how much functionality and how many decisions have already been packaged for reuse.</strong></p>
<p>The higher-level building block isn&#39;t automatically better. A ready-made template that doesn&#39;t fit your requirements may be harder to adapt than a new page assembled from existing sections.</p>
<p>The useful question is: <em>What&#39;s the largest existing building block that fits this job without forcing the wrong structure?</em></p>
<h2>Off the shelf doesn&#39;t have to mean a third-party library</h2>
<p>When developers hear “reuse,” they often think of installing another dependency.</p>
<p>That is one option. We can use a mature UI primitive instead of writing all the keyboard and focus behavior for a combobox. We can use an established styling system rather than inventing every spacing and typography convention.</p>
<p>But a project&#39;s <strong>own codebase should increasingly become its most relevant source of reusable building blocks</strong>.</p>
<p>After the first product listing is finished, the project may already have a ProductCard, ProductGrid, filter controls, and a listing template.</p>
<p>Those are now off-the-shelf options for the <em>next feature in that project</em>.</p>
<p>This is where abstraction and vertical slicing meet.</p>
<h2>A vertical slice turns building blocks into a working feature</h2>
<p>A vertical slice is not simply a collection of finished UI components.</p>
<p>It is a complete piece of functionality that works through the parts of the system it needs.</p>
<p>For our product listing, that means more than rendering a convincing mockup. A visitor should be able to open the page, search for a product, apply a filter, and see results supplied by the actual product data source.</p>
<p>To deliver that slice, we might:</p>
<ul>
<li>Reuse the site&#39;s existing styling foundations.</li>
<li>Adopt a proven combobox primitive for search.</li>
<li>Adapt an existing ProductCard.</li>
<li>Compose a ProductGrid and filtering section.</li>
<li>Connect the listing template to Payload CMS.</li>
<li>Verify the result with real content, interaction tests, and responsive layouts.</li>
</ul>
<p>In <a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a>, I detail how to integrate vertically with the data layer while preserving visual parity, rather than stalling delivery on speculative component rewrites. When developers understand that unfinished work is part of a deliberate architectural sequence rather than an unassigned gap, they avoid the coordination drag explored in <a href="/blog/when-helping-creates-more-work">When Helping Creates More Work</a>.</p>
<p>Some pieces come from the ecosystem. Some come from the project. Some must be built specifically for this feature.</p>
<p>The goal isn&#39;t to maximize reuse at any cost. <strong>It&#39;s to deliver one complete experience without unnecessarily recreating capabilities that already exist.</strong></p>
<p>And once that experience works, something important has changed.</p>
<p>The project now has more to reuse than it did before.</p>
<h2>The second feature should start higher up</h2>
<p>Now imagine building the related-products section on a product detail page.</p>
<p>We don&#39;t need to begin with CSS rules or product-card markup.</p>
<p>We may not even need to begin at the component level.</p>
<p>If the ProductGrid already supports the layout we need, we can reuse the entire section and supply a different set of products.</p>
<p>The original vertical slice has given the next slice a higher starting point.</p>
<p>Then we build a category landing page.</p>
<p>If its requirements match the existing listing template, we may be able to reuse that template, configure its filters and product source, and concentrate on the parts that are genuinely different.</p>
<p>The progression looks like this:</p>
<p><strong>First feature:</strong> Assemble primitives and components into a new section and template.</p>
<p><strong>Second feature:</strong> Reuse the section; implement only the missing integration or variation.</p>
<p><strong>Third feature:</strong> Reuse the template if it fits; configure rather than reconstruct.</p>
<p>That is the compounding effect of a well-structured frontend.</p>
<p>The amount of work doesn&#39;t necessarily decrease with every feature—some features introduce entirely new problems. But the team no longer has to solve <em>every old problem again</em>.</p>
<h2>Reuse the highest suitable abstraction, not the highest available one</h2>
<p>There is a trap in this approach.</p>
<p>Once a team has created a reusable section, it can become tempting to make every future requirement fit that section. Soon, its API contains dozens of options, special cases, and conditional layouts.</p>
<p>The abstraction that was supposed to save time becomes difficult to understand.</p>
<p>So the rule needs a qualification:</p>
<p><strong>Start at the highest abstraction that genuinely fits. Move down only as far as necessary.</strong></p>
<p>If the template fits, use it.</p>
<p>If the template doesn&#39;t fit but its sections do, compose a different page from those sections.</p>
<p>If a section doesn&#39;t fit but its components do, reuse the components.</p>
<p>If the components don&#39;t fit, perhaps their UI primitives or styling foundations still will.</p>
<p>And if the requirement really is unique, build what it needs.</p>
<p>Balancing these layers objectively requires aligning technical tools with client business requirements rather than dogmatic tool bias, as discussed in <a href="/blog/client-needs-judgment-not-preferred-technology">Client Judgment vs. Preferred Technology</a>.</p>
<p>This is also why not every piece of code needs to become reusable the moment it&#39;s written. Sometimes the right choice is to implement a feature clearly, then extract a shared abstraction when a second real use case reveals what the common contract should be.</p>
<p>Reuse should emerge from genuine shared requirements, not from trying to predict every future possibility.</p>
<h2>A growing frontend should become easier to compose</h2>
<p>The promise of vertical slicing is often framed around delivery: ship one working piece, validate it, then move to the next.</p>
<p>That&#39;s valuable, but there is a second benefit.</p>
<p><strong>Each completed slice can expand the set of reliable abstractions available to the project.</strong></p>
<p>The first feature may require substantial work at the component and section levels. The next may reuse an entire section. Another may be mostly template configuration and data integration.</p>
<p>Developers spend less time reconstructing familiar interface patterns and more time solving the requirements that make each feature different.</p>
<p>That&#39;s the frontend I want to build: not one where everything is forced into a universal component system, and not one where every new page starts with an empty file.</p>
<p>Then, for each new feature, we start as high up that ladder as the requirements allow—and deliver a complete vertical slice from there.</p>
<hr>
<h2>Related Reading &amp; Frontend Architecture</h2>
<p>For deeper guides on frontend design systems, UI behavior primitives, and delivery frameworks:</p>
<ul>
<li><strong><a href="/blog/headless-ui-primitives-when-to-own-ui-behavior">Headless UI Primitives: When to Own UI Behavior</a></strong> — When to use Radix, Base UI, or Floating UI instead of building custom state engines.</li>
<li><strong><a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a></strong> — Preserving design parity, proving stability, and integrating vertically.</li>
<li><strong><a href="/blog/when-css-modules-help-migration-guide">When CSS Modules Help: Migration Guide</a></strong> — Scoped styling vs utility-first CSS in component-driven applications.</li>
<li><strong><a href="/blog/when-helping-creates-more-work">When Helping Creates More Work</a></strong> — Why unfinished components aren&#39;t unclaimed tasks and how architectural sequencing prevents duplicated work.</li>
<li><strong><a href="/blog/client-needs-judgment-not-preferred-technology">Client Judgment vs. Preferred Technology</a></strong> — Separating tool bias from business outcomes when advising clients.</li>
<li><strong><a href="/blog/technical-leadership-more-than-having-the-answer">Technical Leadership Is More Than Having the Answer</a></strong> — Connecting technical decisions to business outcomes and leading teams effectively.</li>
</ul>
<p>If you are structuring a modern Next.js or React application, explore my <a href="/nextjs-payload-cms-advisory">Next.js &amp; Payload CMS Advisory</a> or learn about my <a href="/b2b-website-development">B2B Website Development</a> process.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends</guid>
            <category><![CDATA[React]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;If you listen to a project manager, a frontend developer, and a product designer discuss building a new web feature, you will often hear three completely different vocabularies for the same screen.&lt;/p&gt;
&lt;p&gt;The designer talks about design systems and visual consistency. The developer talks about utility classes, shadcn components, or headless primitives. The project manager just wants to know why building a product listing on the homepage took three weeks, and why building an almost identical listing on the category page is slated to take three more.&lt;/p&gt;
&lt;p&gt;When teams start from scratch with every ticket, the confusion isn&amp;#39;t caused by bad code. It&amp;#39;s caused by a failure to agree on &lt;strong&gt;levels of abstraction&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The Styling Layer (The Foundation)&lt;/strong&gt;: Where raw visual tokens live—custom CSS, CSS Modules, or atomic utility classes like Tailwind.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Component &amp;amp; Primitive Layer (The Machinery)&lt;/strong&gt;: Interactive elements like buttons, dialogs, sheets, and dropdowns that bundle headless interaction behavior with styling contracts (such as Radix or Base UI).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The Section &amp;amp; Content Block Layer (The Composition)&lt;/strong&gt;: Structured, relational CMS blocks—such as Payload CMS layout blocks—that compose existing primitives into repeatable page sections without re-declaring their internal logic.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When technical leaders make these abstraction layers explicit, teams stop rebuilding components from scratch and start delivering features as cohesive, reusable vertical slices.&lt;/p&gt;
&lt;h2&gt;Every abstraction saves you from rebuilding something below it&lt;/h2&gt;
&lt;p&gt;At the lowest level, the browser already gives us HTML elements, CSS, JavaScript, and built-in interaction behavior.&lt;/p&gt;
&lt;p&gt;We can work directly with those capabilities. We can write bespoke styles, implement custom controls, and arrange everything ourselves.&lt;/p&gt;
&lt;p&gt;But we can also build—or adopt—abstractions that package recurring decisions.&lt;/p&gt;
&lt;p&gt;A styling system gives us reusable tokens, typography, and layout conventions. A UI primitive handles difficult interaction behavior. A styled component combines behavior with a particular visual treatment. A section arranges components into something meaningful, such as a product grid. A page template composes sections into a repeatable page structure.&lt;/p&gt;
&lt;p&gt;Each level potentially saves us from making the same lower-level decisions again.&lt;/p&gt;
&lt;p&gt;Think of the available building blocks like this:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Level&lt;/th&gt;
&lt;th&gt;Example&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Browser capabilities&lt;/td&gt;
&lt;td&gt;HTML, CSS, JavaScript&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Styling abstractions&lt;/td&gt;
&lt;td&gt;Tokens, Tailwind utilities, reusable CSS patterns&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;UI behavior primitives&lt;/td&gt;
&lt;td&gt;Select, Dialog, Combobox&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Application components&lt;/td&gt;
&lt;td&gt;ProductCard, ProductSearch&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Sections&lt;/td&gt;
&lt;td&gt;ProductGrid, FilterPanel&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Page templates&lt;/td&gt;
&lt;td&gt;Product listing, product detail&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Complete features&lt;/td&gt;
&lt;td&gt;A working, data-connected product listing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;For complex accessibility, focus management, and keyboard handling at the behavioral level, adopting &lt;a href=&quot;/blog/headless-ui-primitives-when-to-own-ui-behavior&quot;&gt;Headless UI Primitives&lt;/a&gt; (such as Radix, Base UI, or Floating UI) allows teams to own presentation without reinventing intricate state machines.&lt;/p&gt;
&lt;p&gt;This isn&amp;#39;t a rigid technical hierarchy. Styling and interaction primitives, for example, address different concerns and can be combined in different ways.&lt;/p&gt;
&lt;p&gt;It&amp;#39;s a way to recognize &lt;strong&gt;how much functionality and how many decisions have already been packaged for reuse.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The higher-level building block isn&amp;#39;t automatically better. A ready-made template that doesn&amp;#39;t fit your requirements may be harder to adapt than a new page assembled from existing sections.&lt;/p&gt;
&lt;p&gt;The useful question is: &lt;em&gt;What&amp;#39;s the largest existing building block that fits this job without forcing the wrong structure?&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;Off the shelf doesn&amp;#39;t have to mean a third-party library&lt;/h2&gt;
&lt;p&gt;When developers hear “reuse,” they often think of installing another dependency.&lt;/p&gt;
&lt;p&gt;That is one option. We can use a mature UI primitive instead of writing all the keyboard and focus behavior for a combobox. We can use an established styling system rather than inventing every spacing and typography convention.&lt;/p&gt;
&lt;p&gt;But a project&amp;#39;s &lt;strong&gt;own codebase should increasingly become its most relevant source of reusable building blocks&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;After the first product listing is finished, the project may already have a ProductCard, ProductGrid, filter controls, and a listing template.&lt;/p&gt;
&lt;p&gt;Those are now off-the-shelf options for the &lt;em&gt;next feature in that project&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;This is where abstraction and vertical slicing meet.&lt;/p&gt;
&lt;h2&gt;A vertical slice turns building blocks into a working feature&lt;/h2&gt;
&lt;p&gt;A vertical slice is not simply a collection of finished UI components.&lt;/p&gt;
&lt;p&gt;It is a complete piece of functionality that works through the parts of the system it needs.&lt;/p&gt;
&lt;p&gt;For our product listing, that means more than rendering a convincing mockup. A visitor should be able to open the page, search for a product, apply a filter, and see results supplied by the actual product data source.&lt;/p&gt;
&lt;p&gt;To deliver that slice, we might:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Reuse the site&amp;#39;s existing styling foundations.&lt;/li&gt;
&lt;li&gt;Adopt a proven combobox primitive for search.&lt;/li&gt;
&lt;li&gt;Adapt an existing ProductCard.&lt;/li&gt;
&lt;li&gt;Compose a ProductGrid and filtering section.&lt;/li&gt;
&lt;li&gt;Connect the listing template to Payload CMS.&lt;/li&gt;
&lt;li&gt;Verify the result with real content, interaction tests, and responsive layouts.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In &lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;, I detail how to integrate vertically with the data layer while preserving visual parity, rather than stalling delivery on speculative component rewrites. When developers understand that unfinished work is part of a deliberate architectural sequence rather than an unassigned gap, they avoid the coordination drag explored in &lt;a href=&quot;/blog/when-helping-creates-more-work&quot;&gt;When Helping Creates More Work&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Some pieces come from the ecosystem. Some come from the project. Some must be built specifically for this feature.&lt;/p&gt;
&lt;p&gt;The goal isn&amp;#39;t to maximize reuse at any cost. &lt;strong&gt;It&amp;#39;s to deliver one complete experience without unnecessarily recreating capabilities that already exist.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;And once that experience works, something important has changed.&lt;/p&gt;
&lt;p&gt;The project now has more to reuse than it did before.&lt;/p&gt;
&lt;h2&gt;The second feature should start higher up&lt;/h2&gt;
&lt;p&gt;Now imagine building the related-products section on a product detail page.&lt;/p&gt;
&lt;p&gt;We don&amp;#39;t need to begin with CSS rules or product-card markup.&lt;/p&gt;
&lt;p&gt;We may not even need to begin at the component level.&lt;/p&gt;
&lt;p&gt;If the ProductGrid already supports the layout we need, we can reuse the entire section and supply a different set of products.&lt;/p&gt;
&lt;p&gt;The original vertical slice has given the next slice a higher starting point.&lt;/p&gt;
&lt;p&gt;Then we build a category landing page.&lt;/p&gt;
&lt;p&gt;If its requirements match the existing listing template, we may be able to reuse that template, configure its filters and product source, and concentrate on the parts that are genuinely different.&lt;/p&gt;
&lt;p&gt;The progression looks like this:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;First feature:&lt;/strong&gt; Assemble primitives and components into a new section and template.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Second feature:&lt;/strong&gt; Reuse the section; implement only the missing integration or variation.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Third feature:&lt;/strong&gt; Reuse the template if it fits; configure rather than reconstruct.&lt;/p&gt;
&lt;p&gt;That is the compounding effect of a well-structured frontend.&lt;/p&gt;
&lt;p&gt;The amount of work doesn&amp;#39;t necessarily decrease with every feature—some features introduce entirely new problems. But the team no longer has to solve &lt;em&gt;every old problem again&lt;/em&gt;.&lt;/p&gt;
&lt;h2&gt;Reuse the highest suitable abstraction, not the highest available one&lt;/h2&gt;
&lt;p&gt;There is a trap in this approach.&lt;/p&gt;
&lt;p&gt;Once a team has created a reusable section, it can become tempting to make every future requirement fit that section. Soon, its API contains dozens of options, special cases, and conditional layouts.&lt;/p&gt;
&lt;p&gt;The abstraction that was supposed to save time becomes difficult to understand.&lt;/p&gt;
&lt;p&gt;So the rule needs a qualification:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Start at the highest abstraction that genuinely fits. Move down only as far as necessary.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;If the template fits, use it.&lt;/p&gt;
&lt;p&gt;If the template doesn&amp;#39;t fit but its sections do, compose a different page from those sections.&lt;/p&gt;
&lt;p&gt;If a section doesn&amp;#39;t fit but its components do, reuse the components.&lt;/p&gt;
&lt;p&gt;If the components don&amp;#39;t fit, perhaps their UI primitives or styling foundations still will.&lt;/p&gt;
&lt;p&gt;And if the requirement really is unique, build what it needs.&lt;/p&gt;
&lt;p&gt;Balancing these layers objectively requires aligning technical tools with client business requirements rather than dogmatic tool bias, as discussed in &lt;a href=&quot;/blog/client-needs-judgment-not-preferred-technology&quot;&gt;Client Judgment vs. Preferred Technology&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This is also why not every piece of code needs to become reusable the moment it&amp;#39;s written. Sometimes the right choice is to implement a feature clearly, then extract a shared abstraction when a second real use case reveals what the common contract should be.&lt;/p&gt;
&lt;p&gt;Reuse should emerge from genuine shared requirements, not from trying to predict every future possibility.&lt;/p&gt;
&lt;h2&gt;A growing frontend should become easier to compose&lt;/h2&gt;
&lt;p&gt;The promise of vertical slicing is often framed around delivery: ship one working piece, validate it, then move to the next.&lt;/p&gt;
&lt;p&gt;That&amp;#39;s valuable, but there is a second benefit.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Each completed slice can expand the set of reliable abstractions available to the project.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The first feature may require substantial work at the component and section levels. The next may reuse an entire section. Another may be mostly template configuration and data integration.&lt;/p&gt;
&lt;p&gt;Developers spend less time reconstructing familiar interface patterns and more time solving the requirements that make each feature different.&lt;/p&gt;
&lt;p&gt;That&amp;#39;s the frontend I want to build: not one where everything is forced into a universal component system, and not one where every new page starts with an empty file.&lt;/p&gt;
&lt;p&gt;Then, for each new feature, we start as high up that ladder as the requirements allow—and deliver a complete vertical slice from there.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Related Reading &amp;amp; Frontend Architecture&lt;/h2&gt;
&lt;p&gt;For deeper guides on frontend design systems, UI behavior primitives, and delivery frameworks:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/headless-ui-primitives-when-to-own-ui-behavior&quot;&gt;Headless UI Primitives: When to Own UI Behavior&lt;/a&gt;&lt;/strong&gt; — When to use Radix, Base UI, or Floating UI instead of building custom state engines.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;&lt;/strong&gt; — Preserving design parity, proving stability, and integrating vertically.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/when-css-modules-help-migration-guide&quot;&gt;When CSS Modules Help: Migration Guide&lt;/a&gt;&lt;/strong&gt; — Scoped styling vs utility-first CSS in component-driven applications.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/when-helping-creates-more-work&quot;&gt;When Helping Creates More Work&lt;/a&gt;&lt;/strong&gt; — Why unfinished components aren&amp;#39;t unclaimed tasks and how architectural sequencing prevents duplicated work.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/client-needs-judgment-not-preferred-technology&quot;&gt;Client Judgment vs. Preferred Technology&lt;/a&gt;&lt;/strong&gt; — Separating tool bias from business outcomes when advising clients.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/technical-leadership-more-than-having-the-answer&quot;&gt;Technical Leadership Is More Than Having the Answer&lt;/a&gt;&lt;/strong&gt; — Connecting technical decisions to business outcomes and leading teams effectively.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you are structuring a modern Next.js or React application, explore my &lt;a href=&quot;/nextjs-payload-cms-advisory&quot;&gt;Next.js &amp;amp; Payload CMS Advisory&lt;/a&gt; or learn about my &lt;a href=&quot;/b2b-website-development&quot;&gt;B2B Website Development&lt;/a&gt; process.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends"/>
        </item>
        <item>
            <title><![CDATA[Your Client Doesn't Need Your Preferred Technology. They Need Your Judgment.]]></title>
            <description><![CDATA[<p><em>On technical language, objectivity, and the responsibility of a senior software provider.</em></p>
<p>A few weeks ago, I found myself in a familiar situation.</p>
<p>We were taking an existing frontend prototype and turning it into a production website. The design was already there. The components existed. The client was working toward a launch, and several developers were involved in the implementation.</p>
<p>Then a technical question emerged.</p>
<p>Should we keep the existing CSS, or rewrite the components using Tailwind?</p>
<p>It sounds like a perfectly ordinary engineering decision. And it is.</p>
<p>But it also exposed something I think we underestimate in client work: <strong>how easily technical preferences can become business decisions without the client fully understanding what they are agreeing to.</strong></p>
<h2>The language we use is rarely neutral</h2>
<p>Imagine sitting in a meeting with two developers.</p>
<p>One says:</p>
<p>&quot;We should use Tailwind. It&#39;s the modern, standard approach, and it will make the codebase more maintainable.&quot;</p>
<p>The other says:</p>
<p>&quot;We should preserve the existing styling. Rewriting everything introduces unnecessary work and risks breaking the design.&quot;</p>
<p>Both statements can sound reasonable.</p>
<p>Both can also be misleading.</p>
<p>The first associates a particular technology with modernity and maintainability. The second associates changing technology with waste and risk.</p>
<p>Neither statement tells the client what they actually need to know.</p>
<p>How much work is involved? What problems exist in the current implementation? Which problems would the proposed change solve? Does the change affect the launch date? What happens if we do nothing? What happens six months later?</p>
<p>Terms such as <em>best practice</em>, <em>modern</em>, <em>clean</em>, <em>scalable</em>, and <em>technical debt</em> carry considerable persuasive weight.</p>
<p>They aren&#39;t necessarily wrong. But without context, they can substitute for an explanation.</p>
<p>A client who cannot independently evaluate the underlying engineering arguments may reasonably interpret &quot;this is the industry standard&quot; as &quot;this is what we need to do.&quot;</p>
<p>That&#39;s a significant amount of influence to exercise with a few words.</p>
<h2>A technical preference is not automatically a business requirement</h2>
<p>In this particular project, the existing prototype already had an established styling system.</p>
<p>The question wasn&#39;t whether Tailwind was good or bad. The project already used Tailwind in some capacity.</p>
<p>The actual decision concerned how much existing styling should be converted, when that work should happen, and whether it should become a prerequisite for launch.</p>
<p>Those are very different questions.</p>
<p>A developer might prefer working with utility classes because they are familiar, productive, and consistent with their usual workflow.</p>
<p>Another developer might prefer keeping the existing CSS because it preserves the design and avoids an immediate conversion.</p>
<p>Both preferences are legitimate.</p>
<p>But neither is sufficient justification for asking the client to spend money or accept additional delivery risk.</p>
<p>The client&#39;s business objective wasn&#39;t to have a website written entirely in Tailwind.</p>
<p>The objective was to launch a functioning website that preserved the approved design, supported the required content workflows, and could be maintained after delivery.</p>
<p>That distinction changes the conversation.</p>
<p>Instead of asking, &quot;Which styling approach should we use?&quot;</p>
<p>We can ask:</p>
<p>&quot;What work is necessary to deliver the website, what improvements are worth making now, and what can safely happen afterward?&quot;</p>
<p>The technology becomes a means to an outcome rather than the outcome itself.</p>
<h2>Objectivity is harder when you have a preferred answer</h2>
<p>There is an uncomfortable part of this conversation that applies to me as much as anyone else.</p>
<p>I had my own preferred implementation approach.</p>
<p>I wanted to preserve the existing design and styling during the initial integration, connect the components to the CMS, and then improve selected components incrementally.</p>
<p>I believed that would protect delivery momentum.</p>
<p>But believing an approach is appropriate doesn&#39;t make my explanation objective.</p>
<p>I could easily have described a full Tailwind conversion as an unnecessary rewrite, expensive duplication, or premature optimization.</p>
<p>Those phrases would strengthen my argument.</p>
<p>They would also risk exaggerating the disadvantages of the alternative.</p>
<p>A full conversion could have genuine benefits. It might simplify the development team&#39;s workflow, reduce inconsistencies in certain parts of the codebase, and make future contributions easier for developers who already work primarily with Tailwind.</p>
<p>Likewise, retaining existing CSS isn&#39;t free of consequences. It can preserve complexity, inconsistent conventions, and maintenance problems that deserve attention.</p>
<p>The challenge is to acknowledge those possibilities even when they weaken your preferred argument.</p>
<p><strong>Objectivity doesn&#39;t mean pretending you have no opinion. It means separating the evidence, the assumptions, and your professional recommendation.</strong></p>
<p>You can say what you would do.</p>
<p>You should also be able to explain what would make you change your mind.</p>
<h2>The missing option is often sequencing</h2>
<p>Technical discussions have a tendency to become binary.</p>
<p>Rewrite or retain.</p>
<p>Replace or keep.</p>
<p>Modernize or accept technical debt.</p>
<p>But many implementation decisions are not binary. They are sequencing decisions.</p>
<p>In our case, I proposed three phases.</p>
<p>First, bring the existing components into the production application without changing their visual presentation.</p>
<p>Second, connect them to the CMS so the website becomes functional.</p>
<p>Third, improve the implementation, including the styling architecture and selected interactive components.</p>
<p>This follows the preserve-first, vertical-integration sequence I detail in <a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a> and <a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">Vertical Slices: Stop Starting From Scratch</a>. When you evaluate <a href="/blog/when-css-modules-help-migration-guide">when CSS Modules help</a> versus utility-first CSS, scoping changes to discrete, data-connected features keeps momentum high.</p>
<p>This made it possible to discuss the styling decision independently from the work needed to connect the website.</p>
<p>It also created an opportunity for the client&#39;s internal development team to contribute without duplicating work already underway.</p>
<p>The advantage wasn&#39;t that we had somehow discovered a universally superior CSS architecture.</p>
<p>It was that we had separated work that needed to happen now from work whose timing still needed to be justified.</p>
<p>There are circumstances where a full rewrite is the right choice. If the existing implementation is fundamentally unsuitable, preserving it may simply postpone an expensive problem.</p>
<p>But that needs to be demonstrated, not assumed.</p>
<p>And if we can deliver the required functionality while improving the architecture incrementally, we should evaluate that option too.</p>
<h2>Your client&#39;s circumstances should influence your technical advice</h2>
<p>A recommendation doesn&#39;t exist in isolation.</p>
<p>The same architecture decision can be appropriate for one client and inappropriate for another.</p>
<p>A company launching a new product in six months has different constraints from a company trying to replace a vulnerable legacy website before an approaching deadline.</p>
<p>A team of experienced frontend developers has different needs from a marketing department that depends on external providers for implementation.</p>
<p>A business that expects to maintain a system for ten years may reasonably invest more in its foundations than one building a temporary campaign.</p>
<p>In our project, the client had an existing design, an active development team, a new CMS foundation, and a launch to coordinate.</p>
<p>A full styling conversion might improve the codebase, but it would also consume implementation capacity and require visual verification.</p>
<p>Leaving every styling issue untouched might protect the immediate timeline, but it could transfer avoidable problems to the people maintaining the website later.</p>
<p>My responsibility was to consider both.</p>
<p>A senior provider shouldn&#39;t simply ask, &quot;What is the technically preferable solution?&quot;</p>
<p>They should also ask, &quot;What is the technically responsible solution given this client&#39;s current situation?&quot;</p>
<p>As discussed in <a href="/blog/technical-leadership-more-than-having-the-answer">Technical Leadership Is More Than Having the Answer</a>, technical depth is only valuable when translated into business constraints. And <a href="/blog/when-helping-creates-more-work">When Helping Creates More Work</a> explores what happens when teams push premature code without shared clarity.</p>
<p>Those questions can produce different answers.</p>
<h2>The client should understand what they are choosing</h2>
<p>When a non-technical decision-maker asks for your recommendation, they are delegating part of the analysis, not surrendering ownership of the decision.</p>
<p>You don&#39;t need to teach them every detail of CSS architecture.</p>
<p>You do need to explain the consequences in terms they can evaluate.</p>
<p>For example:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>What the client needs to understand</th>
</tr>
</thead>
<tbody><tr>
<td>Convert the existing styling now</td>
<td>What specific improvements it delivers, what additional work it requires, and how visual fidelity and delivery will be verified.</td>
</tr>
<tr>
<td>Retain the existing styling</td>
<td>What can be delivered sooner, which existing limitations remain, and how those limitations affect future maintenance.</td>
</tr>
<tr>
<td>Convert incrementally</td>
<td>Which improvements happen before launch, which happen afterward, and how responsibility for the remaining work is handled.</td>
</tr>
</tbody></table>
<p>The table doesn&#39;t make the decision.</p>
<p>It makes the trade-offs visible.</p>
<p>It is also important to be transparent about commercial implications.</p>
<p>If my recommendation creates additional billable work for me, that is relevant.</p>
<p>If my preferred approach reduces the work I personally need to do but transfers more responsibility to the client&#39;s internal team, that is relevant too.</p>
<p>A recommendation that ignores those interests isn&#39;t necessarily dishonest, but it is incomplete.</p>
<h2>The responsibility doesn&#39;t end when the client agrees</h2>
<p>Getting agreement in a meeting isn&#39;t proof that the decision was well understood.</p>
<p>A client may agree because the explanation sounded convincing, because several developers appeared aligned, or because they trusted the person presenting the recommendation.</p>
<p>That trust creates a responsibility to make the decision clear enough to revisit.</p>
<p>What did we decide? Why? What assumptions were we making? What risks did we accept? What would cause us to reconsider?</p>
<p>These questions matter because circumstances change.</p>
<p>A deadline can move. A dependency can disappear. A prototype can reveal unexpected complexity. Another developer can uncover a better implementation.</p>
<p>Changing direction in response to new evidence isn&#39;t necessarily indecision.</p>
<p>It&#39;s part of responsible engineering.</p>
<p>The important thing is that the change follows an explicit reassessment rather than whichever argument was most persuasive in the latest meeting.</p>
<h2>Seniority is not about winning the technical argument</h2>
<p>The longer I work with clients, the more I think the distinction between a developer and a senior technical provider lies partly in the decisions they help other people make.</p>
<p>Writing good code and choosing appropriate tools matters.</p>
<p>Understanding architecture, performance, and maintainability matters.</p>
<p>But none of those skills automatically makes someone good at advising a business.</p>
<p>That requires understanding what the client is trying to accomplish, recognizing the constraints they are operating under, and being willing to recommend an approach that might not be your personal preference.</p>
<p>Sometimes that means challenging the client&#39;s assumptions.</p>
<p>Sometimes it means challenging another developer&#39;s recommendation.</p>
<p>And sometimes it means questioning your own enthusiasm for a technically interesting solution.</p>
<p><strong>The client hired you to help them achieve an outcome, not to give you an opportunity to build your preferred architecture.</strong></p>
<hr>
<h2>Related Reading &amp; Engineering Decision Making</h2>
<p>Explore related perspectives on technical consulting, frontend migration, and architectural strategy:</p>
<ul>
<li><strong><a href="/blog/technical-leadership-more-than-having-the-answer">Technical Leadership Is More Than Having the Answer</a></strong> — Connecting technical decisions to business outcomes, communicating trade-offs, and leading without dogmatic attachment.</li>
<li><strong><a href="/blog/when-helping-creates-more-work">When Helping Creates More Work</a></strong> — Why adding developers to a project doesn&#39;t always make it move faster, and how shared context prevents duplicated work.</li>
<li><strong><a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">Stop Starting From Scratch: Vertical Slices in Frontends</a></strong> — How component abstraction levels and vertical slices keep teams aligned without rewriting code.</li>
<li><strong><a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a></strong> — Preserving design parity, proving stability, and integrating vertically.</li>
<li><strong><a href="/blog/when-css-modules-help-migration-guide">When CSS Modules Help: Migration Guide</a></strong> — Evaluating CSS Modules vs utility-first styling for component-level maintainability.</li>
<li><strong><a href="/blog/architecture-first-website-rebuilds">Architecture-First Website Rebuilds</a></strong> — Why website projects must start with data architecture and business requirements rather than mockups.</li>
</ul>
<p>If your organization is evaluating frontend frameworks or planning a CMS transition, learn more about my <a href="/cms-architecture-review">CMS Architecture Review</a> advisory and <a href="/b2b-website-strategy">B2B Website Strategy</a> guidance.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/client-needs-judgment-not-preferred-technology</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/client-needs-judgment-not-preferred-technology</guid>
            <category><![CDATA[Entrepreneurship]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;&lt;em&gt;On technical language, objectivity, and the responsibility of a senior software provider.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A few weeks ago, I found myself in a familiar situation.&lt;/p&gt;
&lt;p&gt;We were taking an existing frontend prototype and turning it into a production website. The design was already there. The components existed. The client was working toward a launch, and several developers were involved in the implementation.&lt;/p&gt;
&lt;p&gt;Then a technical question emerged.&lt;/p&gt;
&lt;p&gt;Should we keep the existing CSS, or rewrite the components using Tailwind?&lt;/p&gt;
&lt;p&gt;It sounds like a perfectly ordinary engineering decision. And it is.&lt;/p&gt;
&lt;p&gt;But it also exposed something I think we underestimate in client work: &lt;strong&gt;how easily technical preferences can become business decisions without the client fully understanding what they are agreeing to.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;The language we use is rarely neutral&lt;/h2&gt;
&lt;p&gt;Imagine sitting in a meeting with two developers.&lt;/p&gt;
&lt;p&gt;One says:&lt;/p&gt;
&lt;p&gt;&amp;quot;We should use Tailwind. It&amp;#39;s the modern, standard approach, and it will make the codebase more maintainable.&amp;quot;&lt;/p&gt;
&lt;p&gt;The other says:&lt;/p&gt;
&lt;p&gt;&amp;quot;We should preserve the existing styling. Rewriting everything introduces unnecessary work and risks breaking the design.&amp;quot;&lt;/p&gt;
&lt;p&gt;Both statements can sound reasonable.&lt;/p&gt;
&lt;p&gt;Both can also be misleading.&lt;/p&gt;
&lt;p&gt;The first associates a particular technology with modernity and maintainability. The second associates changing technology with waste and risk.&lt;/p&gt;
&lt;p&gt;Neither statement tells the client what they actually need to know.&lt;/p&gt;
&lt;p&gt;How much work is involved? What problems exist in the current implementation? Which problems would the proposed change solve? Does the change affect the launch date? What happens if we do nothing? What happens six months later?&lt;/p&gt;
&lt;p&gt;Terms such as &lt;em&gt;best practice&lt;/em&gt;, &lt;em&gt;modern&lt;/em&gt;, &lt;em&gt;clean&lt;/em&gt;, &lt;em&gt;scalable&lt;/em&gt;, and &lt;em&gt;technical debt&lt;/em&gt; carry considerable persuasive weight.&lt;/p&gt;
&lt;p&gt;They aren&amp;#39;t necessarily wrong. But without context, they can substitute for an explanation.&lt;/p&gt;
&lt;p&gt;A client who cannot independently evaluate the underlying engineering arguments may reasonably interpret &amp;quot;this is the industry standard&amp;quot; as &amp;quot;this is what we need to do.&amp;quot;&lt;/p&gt;
&lt;p&gt;That&amp;#39;s a significant amount of influence to exercise with a few words.&lt;/p&gt;
&lt;h2&gt;A technical preference is not automatically a business requirement&lt;/h2&gt;
&lt;p&gt;In this particular project, the existing prototype already had an established styling system.&lt;/p&gt;
&lt;p&gt;The question wasn&amp;#39;t whether Tailwind was good or bad. The project already used Tailwind in some capacity.&lt;/p&gt;
&lt;p&gt;The actual decision concerned how much existing styling should be converted, when that work should happen, and whether it should become a prerequisite for launch.&lt;/p&gt;
&lt;p&gt;Those are very different questions.&lt;/p&gt;
&lt;p&gt;A developer might prefer working with utility classes because they are familiar, productive, and consistent with their usual workflow.&lt;/p&gt;
&lt;p&gt;Another developer might prefer keeping the existing CSS because it preserves the design and avoids an immediate conversion.&lt;/p&gt;
&lt;p&gt;Both preferences are legitimate.&lt;/p&gt;
&lt;p&gt;But neither is sufficient justification for asking the client to spend money or accept additional delivery risk.&lt;/p&gt;
&lt;p&gt;The client&amp;#39;s business objective wasn&amp;#39;t to have a website written entirely in Tailwind.&lt;/p&gt;
&lt;p&gt;The objective was to launch a functioning website that preserved the approved design, supported the required content workflows, and could be maintained after delivery.&lt;/p&gt;
&lt;p&gt;That distinction changes the conversation.&lt;/p&gt;
&lt;p&gt;Instead of asking, &amp;quot;Which styling approach should we use?&amp;quot;&lt;/p&gt;
&lt;p&gt;We can ask:&lt;/p&gt;
&lt;p&gt;&amp;quot;What work is necessary to deliver the website, what improvements are worth making now, and what can safely happen afterward?&amp;quot;&lt;/p&gt;
&lt;p&gt;The technology becomes a means to an outcome rather than the outcome itself.&lt;/p&gt;
&lt;h2&gt;Objectivity is harder when you have a preferred answer&lt;/h2&gt;
&lt;p&gt;There is an uncomfortable part of this conversation that applies to me as much as anyone else.&lt;/p&gt;
&lt;p&gt;I had my own preferred implementation approach.&lt;/p&gt;
&lt;p&gt;I wanted to preserve the existing design and styling during the initial integration, connect the components to the CMS, and then improve selected components incrementally.&lt;/p&gt;
&lt;p&gt;I believed that would protect delivery momentum.&lt;/p&gt;
&lt;p&gt;But believing an approach is appropriate doesn&amp;#39;t make my explanation objective.&lt;/p&gt;
&lt;p&gt;I could easily have described a full Tailwind conversion as an unnecessary rewrite, expensive duplication, or premature optimization.&lt;/p&gt;
&lt;p&gt;Those phrases would strengthen my argument.&lt;/p&gt;
&lt;p&gt;They would also risk exaggerating the disadvantages of the alternative.&lt;/p&gt;
&lt;p&gt;A full conversion could have genuine benefits. It might simplify the development team&amp;#39;s workflow, reduce inconsistencies in certain parts of the codebase, and make future contributions easier for developers who already work primarily with Tailwind.&lt;/p&gt;
&lt;p&gt;Likewise, retaining existing CSS isn&amp;#39;t free of consequences. It can preserve complexity, inconsistent conventions, and maintenance problems that deserve attention.&lt;/p&gt;
&lt;p&gt;The challenge is to acknowledge those possibilities even when they weaken your preferred argument.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Objectivity doesn&amp;#39;t mean pretending you have no opinion. It means separating the evidence, the assumptions, and your professional recommendation.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;You can say what you would do.&lt;/p&gt;
&lt;p&gt;You should also be able to explain what would make you change your mind.&lt;/p&gt;
&lt;h2&gt;The missing option is often sequencing&lt;/h2&gt;
&lt;p&gt;Technical discussions have a tendency to become binary.&lt;/p&gt;
&lt;p&gt;Rewrite or retain.&lt;/p&gt;
&lt;p&gt;Replace or keep.&lt;/p&gt;
&lt;p&gt;Modernize or accept technical debt.&lt;/p&gt;
&lt;p&gt;But many implementation decisions are not binary. They are sequencing decisions.&lt;/p&gt;
&lt;p&gt;In our case, I proposed three phases.&lt;/p&gt;
&lt;p&gt;First, bring the existing components into the production application without changing their visual presentation.&lt;/p&gt;
&lt;p&gt;Second, connect them to the CMS so the website becomes functional.&lt;/p&gt;
&lt;p&gt;Third, improve the implementation, including the styling architecture and selected interactive components.&lt;/p&gt;
&lt;p&gt;This follows the preserve-first, vertical-integration sequence I detail in &lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt; and &lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;Vertical Slices: Stop Starting From Scratch&lt;/a&gt;. When you evaluate &lt;a href=&quot;/blog/when-css-modules-help-migration-guide&quot;&gt;when CSS Modules help&lt;/a&gt; versus utility-first CSS, scoping changes to discrete, data-connected features keeps momentum high.&lt;/p&gt;
&lt;p&gt;This made it possible to discuss the styling decision independently from the work needed to connect the website.&lt;/p&gt;
&lt;p&gt;It also created an opportunity for the client&amp;#39;s internal development team to contribute without duplicating work already underway.&lt;/p&gt;
&lt;p&gt;The advantage wasn&amp;#39;t that we had somehow discovered a universally superior CSS architecture.&lt;/p&gt;
&lt;p&gt;It was that we had separated work that needed to happen now from work whose timing still needed to be justified.&lt;/p&gt;
&lt;p&gt;There are circumstances where a full rewrite is the right choice. If the existing implementation is fundamentally unsuitable, preserving it may simply postpone an expensive problem.&lt;/p&gt;
&lt;p&gt;But that needs to be demonstrated, not assumed.&lt;/p&gt;
&lt;p&gt;And if we can deliver the required functionality while improving the architecture incrementally, we should evaluate that option too.&lt;/p&gt;
&lt;h2&gt;Your client&amp;#39;s circumstances should influence your technical advice&lt;/h2&gt;
&lt;p&gt;A recommendation doesn&amp;#39;t exist in isolation.&lt;/p&gt;
&lt;p&gt;The same architecture decision can be appropriate for one client and inappropriate for another.&lt;/p&gt;
&lt;p&gt;A company launching a new product in six months has different constraints from a company trying to replace a vulnerable legacy website before an approaching deadline.&lt;/p&gt;
&lt;p&gt;A team of experienced frontend developers has different needs from a marketing department that depends on external providers for implementation.&lt;/p&gt;
&lt;p&gt;A business that expects to maintain a system for ten years may reasonably invest more in its foundations than one building a temporary campaign.&lt;/p&gt;
&lt;p&gt;In our project, the client had an existing design, an active development team, a new CMS foundation, and a launch to coordinate.&lt;/p&gt;
&lt;p&gt;A full styling conversion might improve the codebase, but it would also consume implementation capacity and require visual verification.&lt;/p&gt;
&lt;p&gt;Leaving every styling issue untouched might protect the immediate timeline, but it could transfer avoidable problems to the people maintaining the website later.&lt;/p&gt;
&lt;p&gt;My responsibility was to consider both.&lt;/p&gt;
&lt;p&gt;A senior provider shouldn&amp;#39;t simply ask, &amp;quot;What is the technically preferable solution?&amp;quot;&lt;/p&gt;
&lt;p&gt;They should also ask, &amp;quot;What is the technically responsible solution given this client&amp;#39;s current situation?&amp;quot;&lt;/p&gt;
&lt;p&gt;As discussed in &lt;a href=&quot;/blog/technical-leadership-more-than-having-the-answer&quot;&gt;Technical Leadership Is More Than Having the Answer&lt;/a&gt;, technical depth is only valuable when translated into business constraints. And &lt;a href=&quot;/blog/when-helping-creates-more-work&quot;&gt;When Helping Creates More Work&lt;/a&gt; explores what happens when teams push premature code without shared clarity.&lt;/p&gt;
&lt;p&gt;Those questions can produce different answers.&lt;/p&gt;
&lt;h2&gt;The client should understand what they are choosing&lt;/h2&gt;
&lt;p&gt;When a non-technical decision-maker asks for your recommendation, they are delegating part of the analysis, not surrendering ownership of the decision.&lt;/p&gt;
&lt;p&gt;You don&amp;#39;t need to teach them every detail of CSS architecture.&lt;/p&gt;
&lt;p&gt;You do need to explain the consequences in terms they can evaluate.&lt;/p&gt;
&lt;p&gt;For example:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Option&lt;/th&gt;
&lt;th&gt;What the client needs to understand&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;td&gt;Convert the existing styling now&lt;/td&gt;
&lt;td&gt;What specific improvements it delivers, what additional work it requires, and how visual fidelity and delivery will be verified.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Retain the existing styling&lt;/td&gt;
&lt;td&gt;What can be delivered sooner, which existing limitations remain, and how those limitations affect future maintenance.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Convert incrementally&lt;/td&gt;
&lt;td&gt;Which improvements happen before launch, which happen afterward, and how responsibility for the remaining work is handled.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;
&lt;p&gt;The table doesn&amp;#39;t make the decision.&lt;/p&gt;
&lt;p&gt;It makes the trade-offs visible.&lt;/p&gt;
&lt;p&gt;It is also important to be transparent about commercial implications.&lt;/p&gt;
&lt;p&gt;If my recommendation creates additional billable work for me, that is relevant.&lt;/p&gt;
&lt;p&gt;If my preferred approach reduces the work I personally need to do but transfers more responsibility to the client&amp;#39;s internal team, that is relevant too.&lt;/p&gt;
&lt;p&gt;A recommendation that ignores those interests isn&amp;#39;t necessarily dishonest, but it is incomplete.&lt;/p&gt;
&lt;h2&gt;The responsibility doesn&amp;#39;t end when the client agrees&lt;/h2&gt;
&lt;p&gt;Getting agreement in a meeting isn&amp;#39;t proof that the decision was well understood.&lt;/p&gt;
&lt;p&gt;A client may agree because the explanation sounded convincing, because several developers appeared aligned, or because they trusted the person presenting the recommendation.&lt;/p&gt;
&lt;p&gt;That trust creates a responsibility to make the decision clear enough to revisit.&lt;/p&gt;
&lt;p&gt;What did we decide? Why? What assumptions were we making? What risks did we accept? What would cause us to reconsider?&lt;/p&gt;
&lt;p&gt;These questions matter because circumstances change.&lt;/p&gt;
&lt;p&gt;A deadline can move. A dependency can disappear. A prototype can reveal unexpected complexity. Another developer can uncover a better implementation.&lt;/p&gt;
&lt;p&gt;Changing direction in response to new evidence isn&amp;#39;t necessarily indecision.&lt;/p&gt;
&lt;p&gt;It&amp;#39;s part of responsible engineering.&lt;/p&gt;
&lt;p&gt;The important thing is that the change follows an explicit reassessment rather than whichever argument was most persuasive in the latest meeting.&lt;/p&gt;
&lt;h2&gt;Seniority is not about winning the technical argument&lt;/h2&gt;
&lt;p&gt;The longer I work with clients, the more I think the distinction between a developer and a senior technical provider lies partly in the decisions they help other people make.&lt;/p&gt;
&lt;p&gt;Writing good code and choosing appropriate tools matters.&lt;/p&gt;
&lt;p&gt;Understanding architecture, performance, and maintainability matters.&lt;/p&gt;
&lt;p&gt;But none of those skills automatically makes someone good at advising a business.&lt;/p&gt;
&lt;p&gt;That requires understanding what the client is trying to accomplish, recognizing the constraints they are operating under, and being willing to recommend an approach that might not be your personal preference.&lt;/p&gt;
&lt;p&gt;Sometimes that means challenging the client&amp;#39;s assumptions.&lt;/p&gt;
&lt;p&gt;Sometimes it means challenging another developer&amp;#39;s recommendation.&lt;/p&gt;
&lt;p&gt;And sometimes it means questioning your own enthusiasm for a technically interesting solution.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The client hired you to help them achieve an outcome, not to give you an opportunity to build your preferred architecture.&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Related Reading &amp;amp; Engineering Decision Making&lt;/h2&gt;
&lt;p&gt;Explore related perspectives on technical consulting, frontend migration, and architectural strategy:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/technical-leadership-more-than-having-the-answer&quot;&gt;Technical Leadership Is More Than Having the Answer&lt;/a&gt;&lt;/strong&gt; — Connecting technical decisions to business outcomes, communicating trade-offs, and leading without dogmatic attachment.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/when-helping-creates-more-work&quot;&gt;When Helping Creates More Work&lt;/a&gt;&lt;/strong&gt; — Why adding developers to a project doesn&amp;#39;t always make it move faster, and how shared context prevents duplicated work.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;Stop Starting From Scratch: Vertical Slices in Frontends&lt;/a&gt;&lt;/strong&gt; — How component abstraction levels and vertical slices keep teams aligned without rewriting code.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;&lt;/strong&gt; — Preserving design parity, proving stability, and integrating vertically.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/when-css-modules-help-migration-guide&quot;&gt;When CSS Modules Help: Migration Guide&lt;/a&gt;&lt;/strong&gt; — Evaluating CSS Modules vs utility-first styling for component-level maintainability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/architecture-first-website-rebuilds&quot;&gt;Architecture-First Website Rebuilds&lt;/a&gt;&lt;/strong&gt; — Why website projects must start with data architecture and business requirements rather than mockups.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If your organization is evaluating frontend frameworks or planning a CMS transition, learn more about my &lt;a href=&quot;/cms-architecture-review&quot;&gt;CMS Architecture Review&lt;/a&gt; advisory and &lt;a href=&quot;/b2b-website-strategy&quot;&gt;B2B Website Strategy&lt;/a&gt; guidance.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/client-needs-judgment-not-preferred-technology"/>
        </item>
        <item>
            <title><![CDATA[WordPress Gravity Forms Vulnerability (CVE-2026-84434): Check Your Site]]></title>
            <description><![CDATA[<p><strong>Your company&#39;s WordPress website could be exposed. Check this plugin today.</strong></p>
<p>A critical vulnerability has been disclosed in Gravity Forms, a widely used WordPress form plugin.</p>
<p>CVE-2026-84434 carries a severity score of <strong>9.8 out of 10</strong>.</p>
<p>The vulnerability could allow attackers to upload potentially executable files without logging in, potentially leading to remote code execution.</p>
<p>Not every Gravity Forms installation is exploitable. The attack requires a publicly accessible form containing a File Upload field with its visibility set to Hidden.</p>
<h2>If your company runs its website on WordPress, here&#39;s what to do today:</h2>
<ol>
<li>Ask whoever manages your website whether Gravity Forms is installed.</li>
<li>If it is, check that you&#39;re running version 3.1.1 or newer. Version 3.1.2 is also available.</li>
<li>Ask them to review your forms for hidden file upload fields and investigate suspicious uploads if your site was exposed.</li>
<li>Make sure your contact forms, lead generation forms, and integrations still work after updating.</li>
</ol>
<p>The security fix was released on September 3. The vulnerability was publicly disclosed on September 18.</p>
<p>For more than two weeks, the fix was available, but the release notes described it only as &quot;security enhancements.&quot;</p>
<h2>Why dependency control matters</h2>
<p>Every third-party plugin introduces another dependency that needs to be monitored, updated, and tested. But third-party extensions are not the only exposure point—as demonstrated by the recent <a href="/blog/wordpress-core-vulnerability-cve-2026-87902">critical WordPress Core template vulnerability (CVE-2026-87902)</a>, the underlying platform itself requires rapid operational response.</p>
<p>This is one of the primary reasons I build client websites with <a href="https://payloadcms.com/">Payload CMS</a>. We can implement form handling, uploads, and integrations directly in the application layer rather than relying on an ever-growing collection of third-party plugins.</p>
<p>If you are currently evaluating your CMS architecture or moving away from legacy WordPress maintenance overhead, see my <a href="/blog/wordpress-to-payload-migration-guide">Complete 2026 WordPress to Payload Migration Guide</a> for how to migrate data safely. For technical teams planning production infrastructure, <a href="/blog/payload-cms-in-production-honest-answers">Payload CMS in Production: Honest Answers</a> and the <a href="/blog/deploy-payload-cms-nextjs-16-self-hosted">Self-Hosted Next.js 16 + Payload Deployment Guide</a> explore how direct code ownership gives you full control over your security surface.</p>
<p>It doesn&#39;t eliminate security risks. But it gives us greater control over our dependencies and how we maintain them.</p>
<p>Source: <a href="https://www.wordfence.com/threat-intel/vulnerabilities/wordpress-plugins/gravityforms/gravity-forms-3104-unauthenticated-arbitrary-file-upload-via-hidden-file-upload-field">Wordfence vulnerability report</a></p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/wordpress-gravity-forms-vulnerability-cve-2026-84434</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/wordpress-gravity-forms-vulnerability-cve-2026-84434</guid>
            <category><![CDATA[Payload]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;&lt;strong&gt;Your company&amp;#39;s WordPress website could be exposed. Check this plugin today.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;A critical vulnerability has been disclosed in Gravity Forms, a widely used WordPress form plugin.&lt;/p&gt;
&lt;p&gt;CVE-2026-84434 carries a severity score of &lt;strong&gt;9.8 out of 10&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The vulnerability could allow attackers to upload potentially executable files without logging in, potentially leading to remote code execution.&lt;/p&gt;
&lt;p&gt;Not every Gravity Forms installation is exploitable. The attack requires a publicly accessible form containing a File Upload field with its visibility set to Hidden.&lt;/p&gt;
&lt;h2&gt;If your company runs its website on WordPress, here&amp;#39;s what to do today:&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Ask whoever manages your website whether Gravity Forms is installed.&lt;/li&gt;
&lt;li&gt;If it is, check that you&amp;#39;re running version 3.1.1 or newer. Version 3.1.2 is also available.&lt;/li&gt;
&lt;li&gt;Ask them to review your forms for hidden file upload fields and investigate suspicious uploads if your site was exposed.&lt;/li&gt;
&lt;li&gt;Make sure your contact forms, lead generation forms, and integrations still work after updating.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The security fix was released on September 3. The vulnerability was publicly disclosed on September 18.&lt;/p&gt;
&lt;p&gt;For more than two weeks, the fix was available, but the release notes described it only as &amp;quot;security enhancements.&amp;quot;&lt;/p&gt;
&lt;h2&gt;Why dependency control matters&lt;/h2&gt;
&lt;p&gt;Every third-party plugin introduces another dependency that needs to be monitored, updated, and tested. But third-party extensions are not the only exposure point—as demonstrated by the recent &lt;a href=&quot;/blog/wordpress-core-vulnerability-cve-2026-87902&quot;&gt;critical WordPress Core template vulnerability (CVE-2026-87902)&lt;/a&gt;, the underlying platform itself requires rapid operational response.&lt;/p&gt;
&lt;p&gt;This is one of the primary reasons I build client websites with &lt;a href=&quot;https://payloadcms.com/&quot;&gt;Payload CMS&lt;/a&gt;. We can implement form handling, uploads, and integrations directly in the application layer rather than relying on an ever-growing collection of third-party plugins.&lt;/p&gt;
&lt;p&gt;If you are currently evaluating your CMS architecture or moving away from legacy WordPress maintenance overhead, see my &lt;a href=&quot;/blog/wordpress-to-payload-migration-guide&quot;&gt;Complete 2026 WordPress to Payload Migration Guide&lt;/a&gt; for how to migrate data safely. For technical teams planning production infrastructure, &lt;a href=&quot;/blog/payload-cms-in-production-honest-answers&quot;&gt;Payload CMS in Production: Honest Answers&lt;/a&gt; and the &lt;a href=&quot;/blog/deploy-payload-cms-nextjs-16-self-hosted&quot;&gt;Self-Hosted Next.js 16 + Payload Deployment Guide&lt;/a&gt; explore how direct code ownership gives you full control over your security surface.&lt;/p&gt;
&lt;p&gt;It doesn&amp;#39;t eliminate security risks. But it gives us greater control over our dependencies and how we maintain them.&lt;/p&gt;
&lt;p&gt;Source: &lt;a href=&quot;https://www.wordfence.com/threat-intel/vulnerabilities/wordpress-plugins/gravityforms/gravity-forms-3104-unauthenticated-arbitrary-file-upload-via-hidden-file-upload-field&quot;&gt;Wordfence vulnerability report&lt;/a&gt;&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/wordpress-gravity-forms-vulnerability-cve-2026-84434"/>
        </item>
        <item>
            <title><![CDATA[When Helping Creates More Work: Why Adding Developers Slows Down Projects]]></title>
            <description><![CDATA[<p><em>Why adding developers to a project doesn&#39;t always make it move faster.</em></p>
<p>A client wants to speed up a website project. They have additional developers available, so they bring them in to help. The new team looks at the codebase, finds several unfinished pages, and starts implementing them. A few days later, they have working components, functional interactions, and something tangible to demonstrate. The client sees immediate visual progress, and the new team feels productive.</p>
<p>Meanwhile, another developer has been working on those exact same parts of the website. They haven&#39;t finished the pages yet because they&#39;re still deciding how the components should fit into the larger system, which elements should be reusable, and how data should flow through the application. The new team doesn&#39;t know that. From their perspective, they simply picked up unfinished work and helped move the project forward.</p>
<p>Eventually, the two implementations need to come together—and that&#39;s when everyone discovers that the work was done twice.</p>
<p>Now the team needs to compare implementations, reconcile conflicting changes, and decide which parts to keep. Nobody did anything wrong; everyone was genuinely trying to help. But adding more hands created more work than it eliminated.</p>
<h2>Everyone has a reasonable explanation</h2>
<p>What&#39;s fascinating about this situation is that it doesn&#39;t require anyone to be careless or incompetent.</p>
<p>Consider the client&#39;s perspective: they have a project to deliver, an impending deadline, and surplus development capacity available. It seems entirely reasonable to put those developers to work rather than leave them idle—more people should intuitively mean more progress.</p>
<p>The incoming developers have an equally reasonable perspective. They see unfinished work in the repository, recognize an opportunity to contribute, and begin building. They&#39;re not trying to step on toes; they believe they are actively reducing the remaining workload.</p>
<p>At the same time, the existing developer has a clear plan of their own. They might be working through a deliberate architectural sequence—establishing the component hierarchy before connecting live APIs, or waiting for critical schema decisions to settle. The components that appeared &quot;unfinished&quot; to someone browsing the repo were actually paused on purpose.</p>
<p>Each participant acts rationally on their own isolated understanding of the project. Because each perspective makes total sense independently, the mismatch remains hidden until the pull requests collide.</p>
<p><strong>Everyone can be making progress individually while the project is becoming harder to complete collectively.</strong></p>
<h2>Unfinished doesn&#39;t mean unclaimed</h2>
<p>When we join an existing software project, our instinct is to look for gaps: a missing page, a stubbed component, or an incomplete interaction. These look like clear opportunities to jump in and add value.</p>
<p>However, an unfinished component in a repository can mean several completely different things:</p>
<ul>
<li>Nobody has started working on it yet.</li>
<li>Someone has started locally but hasn&#39;t pushed their branch.</li>
<li>Its implementation is blocked on an external dependency.</li>
<li>Or, very often, it was deliberately paused while foundational architecture or data contracts are being resolved.</li>
</ul>
<p>Those situations look identical from the outside.</p>
<h3>The Illusion of Unclaimed Work</h3>
<p>Imagine a developer working on a complex product listing page. Before finishing the UI, they want to establish how filters behave across multiple templates, which components can be shared, and how the content management system exposes product relationships. While exploring that architecture, they might temporarily use placeholder data and leave certain interactions stubbed out.</p>
<p>Another developer sees the incomplete listing page and decides to help by finishing it. They wire up filters, fetch data, and build components based on their own assumptions. The result might look polished and functional, but it may contradict the broader system the first developer was preparing.</p>
<p>Now the project has two conflicting interpretations of the same feature. As I break down in <a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">Vertical Slices: Stop Starting From Scratch</a>, component architecture succeeds when teams agree on abstraction levels—from UI primitives to shared templates—before implementing redundant one-offs.</p>
<p><strong>What appeared to be a gap in execution was actually a gap in shared context.</strong> The solution isn&#39;t to discourage initiative; it&#39;s to make work-in-progress visible enough that everyone can distinguish unclaimed tasks from deliberate sequencing.</p>
<h2>More output isn&#39;t necessarily more progress</h2>
<p>Software projects often measure progress through metrics that are easy to see: completed pages, styled components, closed tickets, and merged pull requests. While useful, these surface signals don&#39;t tell the whole story.</p>
<p>A client might see five newly implemented pages and reasonably conclude that delivery is accelerating. The developers who built them might report that their sprint backlog is cleared. But if those pages overlap with another developer&#39;s ongoing architecture, that progress is illusory—it must now be reconciled before it can ship.</p>
<p>The hidden overhead includes comparing disparate component trees, deciding which implementation to keep, rewriting conflicting logic, and adapting data layers. None of this means the new code was poorly written; it simply means the work wasn&#39;t independent.</p>
<h3>The Mathematics of Team Throughput</h3>
<p>Adding capacity only increases throughput when new tasks are truly orthogonal to existing work. If two developers build independent features, their output compounds cleanly. But if they independently tackle the same feature or shared boundaries, the project doesn&#39;t get double the progress—it gets two half-solutions and a massive integration bottleneck.</p>
<p>The cost is insidious because two branches can merge cleanly at the Git level while still containing duplicate logic, competing state management, or incompatible architectural assumptions. Visible activity should never be mistaken for true progress toward production.</p>
<h2>The misunderstanding happens before anyone writes code</h2>
<p>The obvious remedy seems to be &quot;more communication.&quot; But informal communication alone rarely solves coordination drag.</p>
<p>Consider a scenario where a technical lead outlines the roadmap: first, the existing frontend will be reorganized into reusable components; next, those components will be connected to the CMS; finally, the styling will be polished. The lead recommends holding off on styling until the component structure stabilizes. In <a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a>, I detail how to preserve design parity and integrate vertically before starting speculative styling refactors.</p>
<p>Everyone hears the roadmap, but everyone interprets it through their own lens:</p>
<ul>
<li>The client assumes the technical lead is handling the backend while the other team accelerates frontend builds.</li>
<li>The additional developers assume they should start moving components into the production repo immediately.</li>
<li>The technical lead assumes the additional team will wait or experiment strictly in an isolated sandbox.</li>
</ul>
<p>Nobody realizes they are working under conflicting premises until code is committed. A written plan is helpful, but sending a message does not guarantee alignment.</p>
<p><strong>A recommendation is not the same thing as a decision, and a decision is not the same thing as shared ownership.</strong></p>
<p>In <a href="/blog/technical-leadership-more-than-having-the-answer">Technical Leadership Is More Than Having the Answer</a>, I explore why making ownership and business consequences explicit matters far more than having the cleverest technical argument. Whenever work crosses team boundaries, make ownership explicit:</p>
<ul>
<li>What has actually been decided versus what is still exploratory?</li>
<li>Who owns which specific component and route?</li>
<li>Which areas of the codebase are frozen until foundational work lands?</li>
<li>Exactly when and how will branches be integrated?</li>
</ul>
<h2>What happens when you discover the overlap?</h2>
<p>Suppose the work is already done: one team has finished several pages, another has built overlapping components, and both have invested significant time.</p>
<p>At this point, stubbornly defending the original plan is counterproductive. The original roadmap may have been sound, but reality has changed—there is now working code on the table that contains valuable insights.</p>
<p>The immediate goal should be pragmatic triage:</p>
<ol>
<li><strong>Bring implementations into a common environment</strong>: Compare the branches side-by-side.</li>
<li><strong>Catalog what exists</strong>: Identify overlapping components, isolate cleanly reusable pieces, and flag conflicting abstractions.</li>
<li><strong>Decide cleanly</strong>: Pick one architectural path for shared components rather than cobbling together an awkward hybrid.</li>
</ol>
<h3>Focus on the Work, Not the Blame</h3>
<p>This is where technical leadership must separate code mechanics from interpersonal friction. The conversation cannot devolve into who was &quot;right&quot; or who should have asked first. The only productive questions are: <em>What can we preserve? What still needs to be built? How do we prevent duplicate work from here on out?</em></p>
<p>Once the code is reconciled, establish clear divisions of labor. Perhaps one team focuses on design tokens and presentational components while the other wires up data fetching and mutations. When reality disrupts your plan, the goal isn&#39;t to protect the plan—it&#39;s to find the most direct path forward from where you are right now.</p>
<h2>Give people code to review before asking them to decide</h2>
<p>A common friction point in multi-team projects is the &quot;surprise demo&quot;: a developer shares their screen in a meeting and demos several completed pages.</p>
<p>The demo looks impressive on the surface. But the engineer responsible for maintaining the system hasn&#39;t seen the code, compared the diffs, or vetted the data flow. They are forced to evaluate an entire architectural implementation in real time on a video call.</p>
<p>A visual demo proves that an implementation works under happy-path conditions. It tells you nothing about maintainability, edge-case resilience, or whether the code fits the broader system.</p>
<p>For meaningful technical changes, insist on asynchronous review:</p>
<ul>
<li>Open the pull request early with clear architectural notes.</li>
<li>Give the team time to inspect the code and evaluate trade-offs before meeting.</li>
<li>Use sync meetings only to resolve specific, documented friction points.</li>
<li>Document every agreed decision in writing immediately afterward.</li>
</ul>
<p>The problem in software teams is rarely a lack of meetings—it&#39;s a lack of verified, shared understanding.</p>
<h2>More hands need more context</h2>
<p>Adding developers can dramatically accelerate delivery when the work is properly decoupled. But scaling a team requires more than handing out repository access and pointing at a backlog.</p>
<p>Incoming developers need to understand the architecture, component boundaries, and unwritten sequencing rules. The existing team needs visibility into what is being built in parallel. And stakeholders need to know how the pieces will converge.</p>
<p>This doesn&#39;t require bureaucratic process or bloated project management. It requires simple discipline: a shared task board, clear domain ownership, frequent integration, and explicit technical decisions.</p>
<p>The goal isn&#39;t to micromanage developers or stifle initiative. It&#39;s to ensure everyone&#39;s energy pulls in the exact same direction. The most expensive coordination failures aren&#39;t the ones where work stops—they&#39;re the ones where everyone works tirelessly in opposite directions.</p>
<hr>
<p>The next time you&#39;re tempted to add developers to accelerate an in-flight project, don&#39;t just ask how much code they can write. Ask what they can cleanly own, what context they need to succeed, and how their work will integrate with what&#39;s already underway.</p>
<p><strong>More hands create more capacity. Shared context is what turns that capacity into progress.</strong></p>
<hr>
<h2>Related Reading &amp; Engineering Management</h2>
<p>For more on team coordination, architecture sequencing, and delivery frameworks:</p>
<ul>
<li><strong><a href="/blog/technical-leadership-more-than-having-the-answer">Technical Leadership Is More Than Having the Answer</a></strong> — Connecting technical decisions to business outcomes and communicating trade-offs effectively.</li>
<li><strong><a href="/blog/client-needs-judgment-not-preferred-technology">Client Judgment vs. Preferred Technology</a></strong> — How easily developer preferences turn into unvetted business decisions and how to evaluate options objectively.</li>
<li><strong><a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">Stop Starting From Scratch: Vertical Slices in Frontends</a></strong> — How component abstraction levels and vertical slices keep teams aligned without rewriting code.</li>
<li><strong><a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a></strong> — Preserving design parity, proving stability, and integrating vertically.</li>
<li><strong><a href="/blog/architecture-first-website-rebuilds">Architecture-First Website Rebuilds</a></strong> — Why website projects must start with data architecture and business requirements rather than mockups.</li>
</ul>
<p>If your team is managing a complex rebuild or needs senior advisory on frontend sequencing, learn more about my <a href="/b2b-website-strategy">B2B Website Strategy</a> and <a href="/cms-architecture-review">CMS Architecture Review</a> services.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/when-helping-creates-more-work</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/when-helping-creates-more-work</guid>
            <category><![CDATA[Entrepreneurship]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;&lt;em&gt;Why adding developers to a project doesn&amp;#39;t always make it move faster.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;A client wants to speed up a website project. They have additional developers available, so they bring them in to help. The new team looks at the codebase, finds several unfinished pages, and starts implementing them. A few days later, they have working components, functional interactions, and something tangible to demonstrate. The client sees immediate visual progress, and the new team feels productive.&lt;/p&gt;
&lt;p&gt;Meanwhile, another developer has been working on those exact same parts of the website. They haven&amp;#39;t finished the pages yet because they&amp;#39;re still deciding how the components should fit into the larger system, which elements should be reusable, and how data should flow through the application. The new team doesn&amp;#39;t know that. From their perspective, they simply picked up unfinished work and helped move the project forward.&lt;/p&gt;
&lt;p&gt;Eventually, the two implementations need to come together—and that&amp;#39;s when everyone discovers that the work was done twice.&lt;/p&gt;
&lt;p&gt;Now the team needs to compare implementations, reconcile conflicting changes, and decide which parts to keep. Nobody did anything wrong; everyone was genuinely trying to help. But adding more hands created more work than it eliminated.&lt;/p&gt;
&lt;h2&gt;Everyone has a reasonable explanation&lt;/h2&gt;
&lt;p&gt;What&amp;#39;s fascinating about this situation is that it doesn&amp;#39;t require anyone to be careless or incompetent.&lt;/p&gt;
&lt;p&gt;Consider the client&amp;#39;s perspective: they have a project to deliver, an impending deadline, and surplus development capacity available. It seems entirely reasonable to put those developers to work rather than leave them idle—more people should intuitively mean more progress.&lt;/p&gt;
&lt;p&gt;The incoming developers have an equally reasonable perspective. They see unfinished work in the repository, recognize an opportunity to contribute, and begin building. They&amp;#39;re not trying to step on toes; they believe they are actively reducing the remaining workload.&lt;/p&gt;
&lt;p&gt;At the same time, the existing developer has a clear plan of their own. They might be working through a deliberate architectural sequence—establishing the component hierarchy before connecting live APIs, or waiting for critical schema decisions to settle. The components that appeared &amp;quot;unfinished&amp;quot; to someone browsing the repo were actually paused on purpose.&lt;/p&gt;
&lt;p&gt;Each participant acts rationally on their own isolated understanding of the project. Because each perspective makes total sense independently, the mismatch remains hidden until the pull requests collide.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Everyone can be making progress individually while the project is becoming harder to complete collectively.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;Unfinished doesn&amp;#39;t mean unclaimed&lt;/h2&gt;
&lt;p&gt;When we join an existing software project, our instinct is to look for gaps: a missing page, a stubbed component, or an incomplete interaction. These look like clear opportunities to jump in and add value.&lt;/p&gt;
&lt;p&gt;However, an unfinished component in a repository can mean several completely different things:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Nobody has started working on it yet.&lt;/li&gt;
&lt;li&gt;Someone has started locally but hasn&amp;#39;t pushed their branch.&lt;/li&gt;
&lt;li&gt;Its implementation is blocked on an external dependency.&lt;/li&gt;
&lt;li&gt;Or, very often, it was deliberately paused while foundational architecture or data contracts are being resolved.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Those situations look identical from the outside.&lt;/p&gt;
&lt;h3&gt;The Illusion of Unclaimed Work&lt;/h3&gt;
&lt;p&gt;Imagine a developer working on a complex product listing page. Before finishing the UI, they want to establish how filters behave across multiple templates, which components can be shared, and how the content management system exposes product relationships. While exploring that architecture, they might temporarily use placeholder data and leave certain interactions stubbed out.&lt;/p&gt;
&lt;p&gt;Another developer sees the incomplete listing page and decides to help by finishing it. They wire up filters, fetch data, and build components based on their own assumptions. The result might look polished and functional, but it may contradict the broader system the first developer was preparing.&lt;/p&gt;
&lt;p&gt;Now the project has two conflicting interpretations of the same feature. As I break down in &lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;Vertical Slices: Stop Starting From Scratch&lt;/a&gt;, component architecture succeeds when teams agree on abstraction levels—from UI primitives to shared templates—before implementing redundant one-offs.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What appeared to be a gap in execution was actually a gap in shared context.&lt;/strong&gt; The solution isn&amp;#39;t to discourage initiative; it&amp;#39;s to make work-in-progress visible enough that everyone can distinguish unclaimed tasks from deliberate sequencing.&lt;/p&gt;
&lt;h2&gt;More output isn&amp;#39;t necessarily more progress&lt;/h2&gt;
&lt;p&gt;Software projects often measure progress through metrics that are easy to see: completed pages, styled components, closed tickets, and merged pull requests. While useful, these surface signals don&amp;#39;t tell the whole story.&lt;/p&gt;
&lt;p&gt;A client might see five newly implemented pages and reasonably conclude that delivery is accelerating. The developers who built them might report that their sprint backlog is cleared. But if those pages overlap with another developer&amp;#39;s ongoing architecture, that progress is illusory—it must now be reconciled before it can ship.&lt;/p&gt;
&lt;p&gt;The hidden overhead includes comparing disparate component trees, deciding which implementation to keep, rewriting conflicting logic, and adapting data layers. None of this means the new code was poorly written; it simply means the work wasn&amp;#39;t independent.&lt;/p&gt;
&lt;h3&gt;The Mathematics of Team Throughput&lt;/h3&gt;
&lt;p&gt;Adding capacity only increases throughput when new tasks are truly orthogonal to existing work. If two developers build independent features, their output compounds cleanly. But if they independently tackle the same feature or shared boundaries, the project doesn&amp;#39;t get double the progress—it gets two half-solutions and a massive integration bottleneck.&lt;/p&gt;
&lt;p&gt;The cost is insidious because two branches can merge cleanly at the Git level while still containing duplicate logic, competing state management, or incompatible architectural assumptions. Visible activity should never be mistaken for true progress toward production.&lt;/p&gt;
&lt;h2&gt;The misunderstanding happens before anyone writes code&lt;/h2&gt;
&lt;p&gt;The obvious remedy seems to be &amp;quot;more communication.&amp;quot; But informal communication alone rarely solves coordination drag.&lt;/p&gt;
&lt;p&gt;Consider a scenario where a technical lead outlines the roadmap: first, the existing frontend will be reorganized into reusable components; next, those components will be connected to the CMS; finally, the styling will be polished. The lead recommends holding off on styling until the component structure stabilizes. In &lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;, I detail how to preserve design parity and integrate vertically before starting speculative styling refactors.&lt;/p&gt;
&lt;p&gt;Everyone hears the roadmap, but everyone interprets it through their own lens:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The client assumes the technical lead is handling the backend while the other team accelerates frontend builds.&lt;/li&gt;
&lt;li&gt;The additional developers assume they should start moving components into the production repo immediately.&lt;/li&gt;
&lt;li&gt;The technical lead assumes the additional team will wait or experiment strictly in an isolated sandbox.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Nobody realizes they are working under conflicting premises until code is committed. A written plan is helpful, but sending a message does not guarantee alignment.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A recommendation is not the same thing as a decision, and a decision is not the same thing as shared ownership.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;In &lt;a href=&quot;/blog/technical-leadership-more-than-having-the-answer&quot;&gt;Technical Leadership Is More Than Having the Answer&lt;/a&gt;, I explore why making ownership and business consequences explicit matters far more than having the cleverest technical argument. Whenever work crosses team boundaries, make ownership explicit:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;What has actually been decided versus what is still exploratory?&lt;/li&gt;
&lt;li&gt;Who owns which specific component and route?&lt;/li&gt;
&lt;li&gt;Which areas of the codebase are frozen until foundational work lands?&lt;/li&gt;
&lt;li&gt;Exactly when and how will branches be integrated?&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;What happens when you discover the overlap?&lt;/h2&gt;
&lt;p&gt;Suppose the work is already done: one team has finished several pages, another has built overlapping components, and both have invested significant time.&lt;/p&gt;
&lt;p&gt;At this point, stubbornly defending the original plan is counterproductive. The original roadmap may have been sound, but reality has changed—there is now working code on the table that contains valuable insights.&lt;/p&gt;
&lt;p&gt;The immediate goal should be pragmatic triage:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Bring implementations into a common environment&lt;/strong&gt;: Compare the branches side-by-side.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Catalog what exists&lt;/strong&gt;: Identify overlapping components, isolate cleanly reusable pieces, and flag conflicting abstractions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decide cleanly&lt;/strong&gt;: Pick one architectural path for shared components rather than cobbling together an awkward hybrid.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Focus on the Work, Not the Blame&lt;/h3&gt;
&lt;p&gt;This is where technical leadership must separate code mechanics from interpersonal friction. The conversation cannot devolve into who was &amp;quot;right&amp;quot; or who should have asked first. The only productive questions are: &lt;em&gt;What can we preserve? What still needs to be built? How do we prevent duplicate work from here on out?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Once the code is reconciled, establish clear divisions of labor. Perhaps one team focuses on design tokens and presentational components while the other wires up data fetching and mutations. When reality disrupts your plan, the goal isn&amp;#39;t to protect the plan—it&amp;#39;s to find the most direct path forward from where you are right now.&lt;/p&gt;
&lt;h2&gt;Give people code to review before asking them to decide&lt;/h2&gt;
&lt;p&gt;A common friction point in multi-team projects is the &amp;quot;surprise demo&amp;quot;: a developer shares their screen in a meeting and demos several completed pages.&lt;/p&gt;
&lt;p&gt;The demo looks impressive on the surface. But the engineer responsible for maintaining the system hasn&amp;#39;t seen the code, compared the diffs, or vetted the data flow. They are forced to evaluate an entire architectural implementation in real time on a video call.&lt;/p&gt;
&lt;p&gt;A visual demo proves that an implementation works under happy-path conditions. It tells you nothing about maintainability, edge-case resilience, or whether the code fits the broader system.&lt;/p&gt;
&lt;p&gt;For meaningful technical changes, insist on asynchronous review:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Open the pull request early with clear architectural notes.&lt;/li&gt;
&lt;li&gt;Give the team time to inspect the code and evaluate trade-offs before meeting.&lt;/li&gt;
&lt;li&gt;Use sync meetings only to resolve specific, documented friction points.&lt;/li&gt;
&lt;li&gt;Document every agreed decision in writing immediately afterward.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The problem in software teams is rarely a lack of meetings—it&amp;#39;s a lack of verified, shared understanding.&lt;/p&gt;
&lt;h2&gt;More hands need more context&lt;/h2&gt;
&lt;p&gt;Adding developers can dramatically accelerate delivery when the work is properly decoupled. But scaling a team requires more than handing out repository access and pointing at a backlog.&lt;/p&gt;
&lt;p&gt;Incoming developers need to understand the architecture, component boundaries, and unwritten sequencing rules. The existing team needs visibility into what is being built in parallel. And stakeholders need to know how the pieces will converge.&lt;/p&gt;
&lt;p&gt;This doesn&amp;#39;t require bureaucratic process or bloated project management. It requires simple discipline: a shared task board, clear domain ownership, frequent integration, and explicit technical decisions.&lt;/p&gt;
&lt;p&gt;The goal isn&amp;#39;t to micromanage developers or stifle initiative. It&amp;#39;s to ensure everyone&amp;#39;s energy pulls in the exact same direction. The most expensive coordination failures aren&amp;#39;t the ones where work stops—they&amp;#39;re the ones where everyone works tirelessly in opposite directions.&lt;/p&gt;
&lt;hr&gt;
&lt;p&gt;The next time you&amp;#39;re tempted to add developers to accelerate an in-flight project, don&amp;#39;t just ask how much code they can write. Ask what they can cleanly own, what context they need to succeed, and how their work will integrate with what&amp;#39;s already underway.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;More hands create more capacity. Shared context is what turns that capacity into progress.&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Related Reading &amp;amp; Engineering Management&lt;/h2&gt;
&lt;p&gt;For more on team coordination, architecture sequencing, and delivery frameworks:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/technical-leadership-more-than-having-the-answer&quot;&gt;Technical Leadership Is More Than Having the Answer&lt;/a&gt;&lt;/strong&gt; — Connecting technical decisions to business outcomes and communicating trade-offs effectively.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/client-needs-judgment-not-preferred-technology&quot;&gt;Client Judgment vs. Preferred Technology&lt;/a&gt;&lt;/strong&gt; — How easily developer preferences turn into unvetted business decisions and how to evaluate options objectively.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;Stop Starting From Scratch: Vertical Slices in Frontends&lt;/a&gt;&lt;/strong&gt; — How component abstraction levels and vertical slices keep teams aligned without rewriting code.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;&lt;/strong&gt; — Preserving design parity, proving stability, and integrating vertically.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/architecture-first-website-rebuilds&quot;&gt;Architecture-First Website Rebuilds&lt;/a&gt;&lt;/strong&gt; — Why website projects must start with data architecture and business requirements rather than mockups.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If your team is managing a complex rebuild or needs senior advisory on frontend sequencing, learn more about my &lt;a href=&quot;/b2b-website-strategy&quot;&gt;B2B Website Strategy&lt;/a&gt; and &lt;a href=&quot;/cms-architecture-review&quot;&gt;CMS Architecture Review&lt;/a&gt; services.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/when-helping-creates-more-work"/>
        </item>
        <item>
            <title><![CDATA[Technical Leadership Is More Than Having the Answer]]></title>
            <description><![CDATA[<p><em>On connecting technical decisions to business outcomes, communicating trade-offs, and learning to lead without needing to be right.</em></p>
<p>Early in my career, I thought being good at software development was largely about knowing how to solve problems.</p>
<p>Understand the requirements, evaluate the available technologies, choose an appropriate approach, and build something that works.</p>
<p>Those skills are still essential. But as I&#39;ve taken on more responsibility for delivering projects, I&#39;ve realized that having a technical answer is only part of the job.</p>
<p>The harder part is helping other people understand what that answer means for them.</p>
<p>A client might ask for something that sounds straightforward but introduces significant architectural consequences. A development team might prefer a particular technology because they&#39;re familiar with it. A technically elegant solution might require more time, money, or organizational change than the business can reasonably accommodate.</p>
<p>When guiding a <a href="/b2b-website-strategy">B2B website strategy</a> or evaluating <a href="/blog/enterprise-clients-readiness-checklist">enterprise client readiness</a>, none of these situations can be resolved through technical expertise alone.</p>
<p>You need to understand what the business is trying to accomplish, what constraints it operates under, and how the available technical approaches support or complicate those objectives.</p>
<p>You also need enough technical depth to understand the implementation consequences.</p>
<p>And then you need to connect those two perspectives in a way that allows people to make informed decisions.</p>
<p>That&#39;s what I&#39;ve been thinking about a lot recently.</p>
<h2>The technically correct solution isn&#39;t always the right solution</h2>
<p>As developers, we&#39;re trained to look for good technical solutions.</p>
<p>We care about maintainability, performance, accessibility, scalability, and clean architecture. We want to avoid unnecessary duplication, reduce complexity, and build systems that can evolve.</p>
<p>These are important considerations. But they aren&#39;t the only ones.</p>
<p>Imagine working with a company whose development team is already familiar with a particular frontend framework.</p>
<p>You might prefer a different approach because you believe it would preserve more of the existing implementation, reduce migration work, or provide a cleaner architectural foundation.</p>
<p>Your recommendation might be technically sound.</p>
<p>But the company has other considerations.</p>
<p>Its developers already know the framework. It has invested in training and tooling. It wants its internal team to maintain the system after you leave. Perhaps the alternative would introduce a dependency on expertise the company doesn&#39;t currently have.</p>
<p>Suddenly, the question isn&#39;t simply which approach produces the cleanest implementation.</p>
<p>It&#39;s which approach makes the most sense for this particular organization.</p>
<p>That doesn&#39;t mean technical quality should be sacrificed whenever a business has a preference. It means technical quality needs to be considered alongside the organization&#39;s ability to deliver, operate, and maintain the solution. As I explore in <a href="/blog/client-needs-judgment-not-preferred-technology">Client Judgment vs. Preferred Technology</a>, separating personal tool preferences from business realities is often the first test of senior engineering objectivity. When planning <a href="/blog/architecture-first-website-rebuilds">architecture-first website rebuilds</a>, starting with business outcomes rather than premature rewrites saves months of coordination friction.</p>
<p><strong>The purpose of architecture is to serve the business, not the other way around.</strong></p>
<h2>You need to operate at two different levels</h2>
<p>One of the most demanding aspects of technical leadership is constantly moving between the bigger picture and the implementation details. If you stay exclusively at the 30,000-foot view, you make architecture promises the codebase cannot keep. If you stay buried in the pull requests, you build elegant systems that solve the wrong business problem.</p>
<p>Effective leaders deliberately operate across two distinct planes:</p>
<h3>Level 1: The Strategic Business View (Why We Are Building)</h3>
<p>In one conversation, you might be discussing why a company wants to replace its existing website. Perhaps marketing teams depend too heavily on developers for simple copy changes. Publishing content requires too many manual approvals. Product information is scattered across multiple systems. The company wants more autonomy, better governance, and a platform that can support future growth.</p>
<p>In a structured <a href="/cms-architecture-review">CMS architecture review</a>, those business tensions directly dictate whether you structure collections for developer velocity or editorial independence. Those are business problems—rooted in operational cost, team autonomy, and delivery speed.</p>
<h3>Level 2: The Ground-Level Implementation (How It Gets Built)</h3>
<p>A few hours later, you might be examining whether a UI component should own its filtering state, whether its behavior can be reused across multiple pages, or whether the content management system should expose a particular configuration option. Those are implementation problems.</p>
<p>The two levels are intimately connected. Consider a seemingly small decision about whether to make a page section configurable through a CMS:</p>
<ul>
<li><strong>From the technical perspective</strong>, you&#39;re deciding between a reusable content block, a fixed template, and a hardcoded component. Whether you are building <a href="/blog/payload-cms-custom-admin-ui-components-guide">custom Admin UI components in Payload CMS</a> or organizing field structures to prevent content bottlenecks, schema design determines long-term maintainability.</li>
<li><strong>From the business perspective</strong>, you&#39;re deciding who can make changes, how much freedom editors have, and whether an engineer needs to be pulled away from product features every time marketing wants to run a campaign.</li>
</ul>
<p>Too little flexibility creates operational bottlenecks; too much flexibility introduces visual inconsistency, maintenance overhead, and editorial confusion. The appropriate solution requires fluency at both levels—translating business intent into architectural boundaries, and communicating technical trade-offs in terms stakeholders actually care about.</p>
<h2>Recognizing a problem is easier than explaining it</h2>
<p>This is something I personally find challenging.</p>
<p>With experience, you begin recognizing certain patterns almost instinctively.</p>
<p>You look at a proposed implementation and see where responsibilities might overlap, where an abstraction could become problematic, or where a seemingly harmless decision could create additional work later.</p>
<p>You might recognize the risk within seconds.</p>
<p>But the person you&#39;re speaking with hasn&#39;t necessarily followed the same reasoning.</p>
<p>They don&#39;t have your technical background. They may not know the architecture or understand why two tasks that appear independent could interfere with one another.</p>
<p>And you cannot simply announce your conclusion and expect them to understand its significance.</p>
<p>You have to reconstruct the reasoning that led you there.</p>
<p>Introduce the relevant concepts. Explain how the pieces fit together. Distinguish what you know from what you suspect. Describe what could happen and why it matters.</p>
<p>Sometimes I catch myself going too deep into the implementation details because I&#39;m trying to make sure the other person understands precisely what I mean.</p>
<p>But that can introduce another problem.</p>
<p>The more technical context I provide, the harder it can become for someone to identify the actual decision we&#39;re discussing.</p>
<p>I&#39;m learning that a useful starting point is to explain the situation, the potential consequence, and the recommendation before getting into the technical details.</p>
<p>For example, instead of beginning with an explanation of component architecture, Git branches, and data contracts, I might say:</p>
<p>&quot;Two teams are making changes to overlapping parts of the website. That creates a risk of duplicated work and integration conflicts. I suggest we agree on ownership before continuing, so we don&#39;t spend time implementing the same things twice.&quot;</p>
<p>Establishing clear component contracts through <a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">Vertical Slices and Reusable Frontends</a> ensures both groups can build against shared boundaries without collision.</p>
<p>The technical explanation is still available if someone needs it.</p>
<p>But now everyone understands why the conversation matters.</p>
<p><strong>The goal isn&#39;t to make everyone understand everything you know. It&#39;s to give them enough understanding to participate meaningfully in the decision.</strong></p>
<p>That requires more than choosing simpler words.</p>
<p>It requires listening, recognizing when someone is confused, adjusting the explanation, and creating an environment where people feel comfortable asking questions.</p>
<p>Communication isn&#39;t something that happens after the technical work. It&#39;s part of the technical work.</p>
<h2>A recommendation is not a decision</h2>
<p>When a client asks for your expertise, you should have an opinion.</p>
<p>You should evaluate the options, explain their trade-offs, and recommend the approach you believe serves their needs.</p>
<p>But having a recommendation doesn&#39;t mean you own the final decision.</p>
<p>Consider a project where there are three possible implementation approaches.</p>
<p>One preserves the existing code and minimizes immediate development effort, but carries some technical debt forward.</p>
<p>Another rebuilds the implementation around a different framework, potentially improving consistency with the internal team&#39;s tooling but introducing additional development effort and regression risk.</p>
<p>A third takes a hybrid approach, preserving the existing design while gradually improving the underlying implementation.</p>
<p>You might recommend the hybrid approach.</p>
<p>You explain why. You describe what each alternative offers, what it costs, and which risks it introduces.</p>
<p>Then the client chooses the rebuild.</p>
<p>What happens next?</p>
<p>You could spend the following meetings explaining why your original recommendation was preferable.</p>
<p>You could treat every difficulty as further evidence that you were right.</p>
<p>Or you could recognize that the decision has been made and focus on making the chosen approach successful.</p>
<p>That doesn&#39;t mean pretending the risks have disappeared.</p>
<p>You still have a responsibility to identify them, propose mitigations, and communicate when new information changes the situation.</p>
<p>But your recommendation should not become something you need to defend for its own sake.</p>
<p><strong>The objective is to help the client make a good decision, not to make sure they choose yours.</strong></p>
<h2>Working with the situation you actually have</h2>
<p>This becomes particularly important when a project doesn&#39;t unfold according to the original plan.</p>
<p>Imagine two teams working on different aspects of the same website.</p>
<p>One is adapting an existing frontend into a content management system, deciding how components should be organized and how they will receive their data.</p>
<p>Another is rebuilding parts of that frontend using a different styling approach.</p>
<p>Both teams are making progress.</p>
<p>Both have working implementations.</p>
<p>Then they discover they&#39;ve been working on some of the same components independently.</p>
<p>There is now a risk of duplicated effort, competing implementations, and merge conflicts.</p>
<p>This is the exact coordination trap I describe in <a href="/blog/when-helping-creates-more-work">When Helping Creates More Work</a>: adding hands without shared architectural visibility inevitably multiplies delivery friction instead of cutting it.</p>
<p>Perhaps the risk was identified earlier. Perhaps the responsibilities weren&#39;t sufficiently clear. Perhaps the additional work was intended to accelerate delivery.</p>
<p>At this point, determining who should have done what doesn&#39;t resolve the immediate technical problem.</p>
<p>The useful questions are different.</p>
<p>What has already been built?</p>
<p>Which parts can we preserve?</p>
<p>How much overlap actually exists?</p>
<p>What is the most practical way to bring the work together?</p>
<p>How should responsibilities be divided going forward?</p>
<p>Sometimes the answer requires changing your own plan.</p>
<p>You might stop working on a particular area, allow another team to finish its implementation, and then resume your work once the shared foundation is ready.</p>
<p>That may not be how you originally intended to approach the project.</p>
<p>But the circumstances have changed.</p>
<p>Continuing with the original plan simply because it was your plan could create even more unnecessary work. In <a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a>, I examine how preserving existing team momentum and proving parity takes precedence over asserting individual architectural dominance.</p>
<p>This is something I&#39;m learning to appreciate about technical leadership: you can be confident in your reasoning while remaining flexible about the implementation.</p>
<p>You don&#39;t have to abandon your principles to adapt.</p>
<p>You have to understand which principles matter, which decisions are still open, and which constraints have changed.</p>
<h2>Good decisions need more than a meeting</h2>
<p>Another lesson I&#39;ve been thinking about is how technical decisions are actually made.</p>
<p>A meeting can be useful for discussing options, resolving disagreements, and establishing a shared understanding.</p>
<p>But a live demonstration isn&#39;t always enough to evaluate an implementation.</p>
<p>Someone might show you a completed page. It looks good, the interactions work, and the team has clearly made progress.</p>
<p>What you cannot necessarily establish from that demonstration is how the code is structured, how it integrates with the rest of the system, or whether it introduces conflicting assumptions.</p>
<p>Those questions require examining the actual implementation.</p>
<p>I increasingly prefer having the opportunity to review technical work asynchronously before discussing consequential decisions.</p>
<p>Give me the code, the proposed changes, the reasoning behind them, and the specific questions that need answering.</p>
<p>Let me examine the implementation and think through its implications.</p>
<p>Then we can have a focused conversation about the things that genuinely require discussion.</p>
<p>This isn&#39;t about avoiding meetings.</p>
<p>It&#39;s about making better use of them.</p>
<p>I also believe important decisions should be documented afterward.</p>
<p>A conversation can create the impression that everyone agrees, while participants leave with different interpretations of what was decided.</p>
<p>A written record of the decision, its rationale, the remaining risks, and who owns the next steps gives everyone something concrete to work from.</p>
<p>Of course, documentation alone doesn&#39;t create alignment. People need to acknowledge the decision and act on it.</p>
<p>But it provides a foundation for shared understanding rather than relying on everyone&#39;s memory of a conversation.</p>
<h2>Technical leadership is ultimately about responsibility</h2>
<p>The more I work with clients, the more I realize that my responsibility extends beyond the code I personally write.</p>
<p>I&#39;m responsible for understanding what they&#39;re trying to achieve.</p>
<p>For identifying technical risks they may not see.</p>
<p>For explaining the consequences of their options.</p>
<p>For making recommendations grounded in their circumstances rather than my personal preferences.</p>
<p>And for helping turn their decisions into working systems.</p>
<p>This doesn&#39;t mean taking responsibility for every decision or every action taken by every team.</p>
<p>Leadership also requires clear ownership, appropriate boundaries, and knowing when a decision belongs to someone else.</p>
<p>But it does mean thinking beyond your individual contribution.</p>
<p>A successful implementation isn&#39;t necessarily the one that most closely resembles the architecture you would have designed in isolation.</p>
<p>It&#39;s one that meets the business&#39;s needs, can be operated and maintained by the people responsible for it, and achieves the outcomes the project was intended to deliver.</p>
<p>I&#39;m still learning how to communicate these ideas more clearly.</p>
<p>Sometimes I explain too much. Sometimes I assume that something obvious to me will be obvious to someone else. Sometimes I need to recognize sooner that the conversation has moved from evaluating options to deciding what happens next.</p>
<p>But I think that is part of developing as a technical leader.</p>
<p>The technical knowledge remains essential. Without it, you cannot reliably evaluate the options or understand their consequences.</p>
<p>But knowledge alone doesn&#39;t help a client make a decision.</p>
<p>You have to make that knowledge accessible, apply it to their circumstances, and remain accountable for the work that follows.</p>
<p><strong>Having the answer is valuable. Helping people understand their options, make informed decisions, and turn those decisions into successful outcomes is what technical leadership is really about.</strong></p>
<hr>
<h2>Related Reading &amp; Architectural Strategy</h2>
<p>If you are navigating technical decisions, team coordination, or platform migrations:</p>
<ul>
<li><strong><a href="/blog/client-needs-judgment-not-preferred-technology">Client Judgment vs. Preferred Technology</a></strong> — Why senior engineering delivery is about objective trade-off analysis rather than personal tool preference.</li>
<li><strong><a href="/blog/when-helping-creates-more-work">When Helping Creates More Work</a></strong> — Why adding developers to an in-flight project often creates coordination friction, and how shared context prevents duplicated work.</li>
<li><strong><a href="/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends">Stop Starting From Scratch: Vertical Slices in Frontends</a></strong> — How component abstraction levels and vertical slices keep teams aligned without rewriting code.</li>
<li><strong><a href="/blog/architecture-first-website-rebuilds">Architecture-First Website Rebuilds</a></strong> — Why website projects must start with data architecture and business requirements rather than mockups.</li>
<li><strong><a href="/blog/taking-over-a-frontend-framework">How to Take Over a Frontend: A 4-Step Production Framework</a></strong> — How to preserve design parity, integrate vertically, and deliver without high-risk rewrites.</li>
<li><strong><a href="/blog/enterprise-clients-readiness-checklist">Enterprise Clients Readiness Checklist</a></strong> — Documentation, security baselines, account ownership, and SLAs for agencies.</li>
</ul>
<p>If you are planning an upcoming replatforming or need an objective evaluation of your CMS architecture, explore my <a href="/cms-architecture-review">CMS Architecture Review</a> advisory or read more on <a href="/b2b-website-strategy">B2B Website Strategy</a>.</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/technical-leadership-more-than-having-the-answer</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/technical-leadership-more-than-having-the-answer</guid>
            <category><![CDATA[Entrepreneurship]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 06:00:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;&lt;em&gt;On connecting technical decisions to business outcomes, communicating trade-offs, and learning to lead without needing to be right.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Early in my career, I thought being good at software development was largely about knowing how to solve problems.&lt;/p&gt;
&lt;p&gt;Understand the requirements, evaluate the available technologies, choose an appropriate approach, and build something that works.&lt;/p&gt;
&lt;p&gt;Those skills are still essential. But as I&amp;#39;ve taken on more responsibility for delivering projects, I&amp;#39;ve realized that having a technical answer is only part of the job.&lt;/p&gt;
&lt;p&gt;The harder part is helping other people understand what that answer means for them.&lt;/p&gt;
&lt;p&gt;A client might ask for something that sounds straightforward but introduces significant architectural consequences. A development team might prefer a particular technology because they&amp;#39;re familiar with it. A technically elegant solution might require more time, money, or organizational change than the business can reasonably accommodate.&lt;/p&gt;
&lt;p&gt;When guiding a &lt;a href=&quot;/b2b-website-strategy&quot;&gt;B2B website strategy&lt;/a&gt; or evaluating &lt;a href=&quot;/blog/enterprise-clients-readiness-checklist&quot;&gt;enterprise client readiness&lt;/a&gt;, none of these situations can be resolved through technical expertise alone.&lt;/p&gt;
&lt;p&gt;You need to understand what the business is trying to accomplish, what constraints it operates under, and how the available technical approaches support or complicate those objectives.&lt;/p&gt;
&lt;p&gt;You also need enough technical depth to understand the implementation consequences.&lt;/p&gt;
&lt;p&gt;And then you need to connect those two perspectives in a way that allows people to make informed decisions.&lt;/p&gt;
&lt;p&gt;That&amp;#39;s what I&amp;#39;ve been thinking about a lot recently.&lt;/p&gt;
&lt;h2&gt;The technically correct solution isn&amp;#39;t always the right solution&lt;/h2&gt;
&lt;p&gt;As developers, we&amp;#39;re trained to look for good technical solutions.&lt;/p&gt;
&lt;p&gt;We care about maintainability, performance, accessibility, scalability, and clean architecture. We want to avoid unnecessary duplication, reduce complexity, and build systems that can evolve.&lt;/p&gt;
&lt;p&gt;These are important considerations. But they aren&amp;#39;t the only ones.&lt;/p&gt;
&lt;p&gt;Imagine working with a company whose development team is already familiar with a particular frontend framework.&lt;/p&gt;
&lt;p&gt;You might prefer a different approach because you believe it would preserve more of the existing implementation, reduce migration work, or provide a cleaner architectural foundation.&lt;/p&gt;
&lt;p&gt;Your recommendation might be technically sound.&lt;/p&gt;
&lt;p&gt;But the company has other considerations.&lt;/p&gt;
&lt;p&gt;Its developers already know the framework. It has invested in training and tooling. It wants its internal team to maintain the system after you leave. Perhaps the alternative would introduce a dependency on expertise the company doesn&amp;#39;t currently have.&lt;/p&gt;
&lt;p&gt;Suddenly, the question isn&amp;#39;t simply which approach produces the cleanest implementation.&lt;/p&gt;
&lt;p&gt;It&amp;#39;s which approach makes the most sense for this particular organization.&lt;/p&gt;
&lt;p&gt;That doesn&amp;#39;t mean technical quality should be sacrificed whenever a business has a preference. It means technical quality needs to be considered alongside the organization&amp;#39;s ability to deliver, operate, and maintain the solution. As I explore in &lt;a href=&quot;/blog/client-needs-judgment-not-preferred-technology&quot;&gt;Client Judgment vs. Preferred Technology&lt;/a&gt;, separating personal tool preferences from business realities is often the first test of senior engineering objectivity. When planning &lt;a href=&quot;/blog/architecture-first-website-rebuilds&quot;&gt;architecture-first website rebuilds&lt;/a&gt;, starting with business outcomes rather than premature rewrites saves months of coordination friction.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The purpose of architecture is to serve the business, not the other way around.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;You need to operate at two different levels&lt;/h2&gt;
&lt;p&gt;One of the most demanding aspects of technical leadership is constantly moving between the bigger picture and the implementation details. If you stay exclusively at the 30,000-foot view, you make architecture promises the codebase cannot keep. If you stay buried in the pull requests, you build elegant systems that solve the wrong business problem.&lt;/p&gt;
&lt;p&gt;Effective leaders deliberately operate across two distinct planes:&lt;/p&gt;
&lt;h3&gt;Level 1: The Strategic Business View (Why We Are Building)&lt;/h3&gt;
&lt;p&gt;In one conversation, you might be discussing why a company wants to replace its existing website. Perhaps marketing teams depend too heavily on developers for simple copy changes. Publishing content requires too many manual approvals. Product information is scattered across multiple systems. The company wants more autonomy, better governance, and a platform that can support future growth.&lt;/p&gt;
&lt;p&gt;In a structured &lt;a href=&quot;/cms-architecture-review&quot;&gt;CMS architecture review&lt;/a&gt;, those business tensions directly dictate whether you structure collections for developer velocity or editorial independence. Those are business problems—rooted in operational cost, team autonomy, and delivery speed.&lt;/p&gt;
&lt;h3&gt;Level 2: The Ground-Level Implementation (How It Gets Built)&lt;/h3&gt;
&lt;p&gt;A few hours later, you might be examining whether a UI component should own its filtering state, whether its behavior can be reused across multiple pages, or whether the content management system should expose a particular configuration option. Those are implementation problems.&lt;/p&gt;
&lt;p&gt;The two levels are intimately connected. Consider a seemingly small decision about whether to make a page section configurable through a CMS:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;From the technical perspective&lt;/strong&gt;, you&amp;#39;re deciding between a reusable content block, a fixed template, and a hardcoded component. Whether you are building &lt;a href=&quot;/blog/payload-cms-custom-admin-ui-components-guide&quot;&gt;custom Admin UI components in Payload CMS&lt;/a&gt; or organizing field structures to prevent content bottlenecks, schema design determines long-term maintainability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;From the business perspective&lt;/strong&gt;, you&amp;#39;re deciding who can make changes, how much freedom editors have, and whether an engineer needs to be pulled away from product features every time marketing wants to run a campaign.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Too little flexibility creates operational bottlenecks; too much flexibility introduces visual inconsistency, maintenance overhead, and editorial confusion. The appropriate solution requires fluency at both levels—translating business intent into architectural boundaries, and communicating technical trade-offs in terms stakeholders actually care about.&lt;/p&gt;
&lt;h2&gt;Recognizing a problem is easier than explaining it&lt;/h2&gt;
&lt;p&gt;This is something I personally find challenging.&lt;/p&gt;
&lt;p&gt;With experience, you begin recognizing certain patterns almost instinctively.&lt;/p&gt;
&lt;p&gt;You look at a proposed implementation and see where responsibilities might overlap, where an abstraction could become problematic, or where a seemingly harmless decision could create additional work later.&lt;/p&gt;
&lt;p&gt;You might recognize the risk within seconds.&lt;/p&gt;
&lt;p&gt;But the person you&amp;#39;re speaking with hasn&amp;#39;t necessarily followed the same reasoning.&lt;/p&gt;
&lt;p&gt;They don&amp;#39;t have your technical background. They may not know the architecture or understand why two tasks that appear independent could interfere with one another.&lt;/p&gt;
&lt;p&gt;And you cannot simply announce your conclusion and expect them to understand its significance.&lt;/p&gt;
&lt;p&gt;You have to reconstruct the reasoning that led you there.&lt;/p&gt;
&lt;p&gt;Introduce the relevant concepts. Explain how the pieces fit together. Distinguish what you know from what you suspect. Describe what could happen and why it matters.&lt;/p&gt;
&lt;p&gt;Sometimes I catch myself going too deep into the implementation details because I&amp;#39;m trying to make sure the other person understands precisely what I mean.&lt;/p&gt;
&lt;p&gt;But that can introduce another problem.&lt;/p&gt;
&lt;p&gt;The more technical context I provide, the harder it can become for someone to identify the actual decision we&amp;#39;re discussing.&lt;/p&gt;
&lt;p&gt;I&amp;#39;m learning that a useful starting point is to explain the situation, the potential consequence, and the recommendation before getting into the technical details.&lt;/p&gt;
&lt;p&gt;For example, instead of beginning with an explanation of component architecture, Git branches, and data contracts, I might say:&lt;/p&gt;
&lt;p&gt;&amp;quot;Two teams are making changes to overlapping parts of the website. That creates a risk of duplicated work and integration conflicts. I suggest we agree on ownership before continuing, so we don&amp;#39;t spend time implementing the same things twice.&amp;quot;&lt;/p&gt;
&lt;p&gt;Establishing clear component contracts through &lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;Vertical Slices and Reusable Frontends&lt;/a&gt; ensures both groups can build against shared boundaries without collision.&lt;/p&gt;
&lt;p&gt;The technical explanation is still available if someone needs it.&lt;/p&gt;
&lt;p&gt;But now everyone understands why the conversation matters.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The goal isn&amp;#39;t to make everyone understand everything you know. It&amp;#39;s to give them enough understanding to participate meaningfully in the decision.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;That requires more than choosing simpler words.&lt;/p&gt;
&lt;p&gt;It requires listening, recognizing when someone is confused, adjusting the explanation, and creating an environment where people feel comfortable asking questions.&lt;/p&gt;
&lt;p&gt;Communication isn&amp;#39;t something that happens after the technical work. It&amp;#39;s part of the technical work.&lt;/p&gt;
&lt;h2&gt;A recommendation is not a decision&lt;/h2&gt;
&lt;p&gt;When a client asks for your expertise, you should have an opinion.&lt;/p&gt;
&lt;p&gt;You should evaluate the options, explain their trade-offs, and recommend the approach you believe serves their needs.&lt;/p&gt;
&lt;p&gt;But having a recommendation doesn&amp;#39;t mean you own the final decision.&lt;/p&gt;
&lt;p&gt;Consider a project where there are three possible implementation approaches.&lt;/p&gt;
&lt;p&gt;One preserves the existing code and minimizes immediate development effort, but carries some technical debt forward.&lt;/p&gt;
&lt;p&gt;Another rebuilds the implementation around a different framework, potentially improving consistency with the internal team&amp;#39;s tooling but introducing additional development effort and regression risk.&lt;/p&gt;
&lt;p&gt;A third takes a hybrid approach, preserving the existing design while gradually improving the underlying implementation.&lt;/p&gt;
&lt;p&gt;You might recommend the hybrid approach.&lt;/p&gt;
&lt;p&gt;You explain why. You describe what each alternative offers, what it costs, and which risks it introduces.&lt;/p&gt;
&lt;p&gt;Then the client chooses the rebuild.&lt;/p&gt;
&lt;p&gt;What happens next?&lt;/p&gt;
&lt;p&gt;You could spend the following meetings explaining why your original recommendation was preferable.&lt;/p&gt;
&lt;p&gt;You could treat every difficulty as further evidence that you were right.&lt;/p&gt;
&lt;p&gt;Or you could recognize that the decision has been made and focus on making the chosen approach successful.&lt;/p&gt;
&lt;p&gt;That doesn&amp;#39;t mean pretending the risks have disappeared.&lt;/p&gt;
&lt;p&gt;You still have a responsibility to identify them, propose mitigations, and communicate when new information changes the situation.&lt;/p&gt;
&lt;p&gt;But your recommendation should not become something you need to defend for its own sake.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The objective is to help the client make a good decision, not to make sure they choose yours.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;Working with the situation you actually have&lt;/h2&gt;
&lt;p&gt;This becomes particularly important when a project doesn&amp;#39;t unfold according to the original plan.&lt;/p&gt;
&lt;p&gt;Imagine two teams working on different aspects of the same website.&lt;/p&gt;
&lt;p&gt;One is adapting an existing frontend into a content management system, deciding how components should be organized and how they will receive their data.&lt;/p&gt;
&lt;p&gt;Another is rebuilding parts of that frontend using a different styling approach.&lt;/p&gt;
&lt;p&gt;Both teams are making progress.&lt;/p&gt;
&lt;p&gt;Both have working implementations.&lt;/p&gt;
&lt;p&gt;Then they discover they&amp;#39;ve been working on some of the same components independently.&lt;/p&gt;
&lt;p&gt;There is now a risk of duplicated effort, competing implementations, and merge conflicts.&lt;/p&gt;
&lt;p&gt;This is the exact coordination trap I describe in &lt;a href=&quot;/blog/when-helping-creates-more-work&quot;&gt;When Helping Creates More Work&lt;/a&gt;: adding hands without shared architectural visibility inevitably multiplies delivery friction instead of cutting it.&lt;/p&gt;
&lt;p&gt;Perhaps the risk was identified earlier. Perhaps the responsibilities weren&amp;#39;t sufficiently clear. Perhaps the additional work was intended to accelerate delivery.&lt;/p&gt;
&lt;p&gt;At this point, determining who should have done what doesn&amp;#39;t resolve the immediate technical problem.&lt;/p&gt;
&lt;p&gt;The useful questions are different.&lt;/p&gt;
&lt;p&gt;What has already been built?&lt;/p&gt;
&lt;p&gt;Which parts can we preserve?&lt;/p&gt;
&lt;p&gt;How much overlap actually exists?&lt;/p&gt;
&lt;p&gt;What is the most practical way to bring the work together?&lt;/p&gt;
&lt;p&gt;How should responsibilities be divided going forward?&lt;/p&gt;
&lt;p&gt;Sometimes the answer requires changing your own plan.&lt;/p&gt;
&lt;p&gt;You might stop working on a particular area, allow another team to finish its implementation, and then resume your work once the shared foundation is ready.&lt;/p&gt;
&lt;p&gt;That may not be how you originally intended to approach the project.&lt;/p&gt;
&lt;p&gt;But the circumstances have changed.&lt;/p&gt;
&lt;p&gt;Continuing with the original plan simply because it was your plan could create even more unnecessary work. In &lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;, I examine how preserving existing team momentum and proving parity takes precedence over asserting individual architectural dominance.&lt;/p&gt;
&lt;p&gt;This is something I&amp;#39;m learning to appreciate about technical leadership: you can be confident in your reasoning while remaining flexible about the implementation.&lt;/p&gt;
&lt;p&gt;You don&amp;#39;t have to abandon your principles to adapt.&lt;/p&gt;
&lt;p&gt;You have to understand which principles matter, which decisions are still open, and which constraints have changed.&lt;/p&gt;
&lt;h2&gt;Good decisions need more than a meeting&lt;/h2&gt;
&lt;p&gt;Another lesson I&amp;#39;ve been thinking about is how technical decisions are actually made.&lt;/p&gt;
&lt;p&gt;A meeting can be useful for discussing options, resolving disagreements, and establishing a shared understanding.&lt;/p&gt;
&lt;p&gt;But a live demonstration isn&amp;#39;t always enough to evaluate an implementation.&lt;/p&gt;
&lt;p&gt;Someone might show you a completed page. It looks good, the interactions work, and the team has clearly made progress.&lt;/p&gt;
&lt;p&gt;What you cannot necessarily establish from that demonstration is how the code is structured, how it integrates with the rest of the system, or whether it introduces conflicting assumptions.&lt;/p&gt;
&lt;p&gt;Those questions require examining the actual implementation.&lt;/p&gt;
&lt;p&gt;I increasingly prefer having the opportunity to review technical work asynchronously before discussing consequential decisions.&lt;/p&gt;
&lt;p&gt;Give me the code, the proposed changes, the reasoning behind them, and the specific questions that need answering.&lt;/p&gt;
&lt;p&gt;Let me examine the implementation and think through its implications.&lt;/p&gt;
&lt;p&gt;Then we can have a focused conversation about the things that genuinely require discussion.&lt;/p&gt;
&lt;p&gt;This isn&amp;#39;t about avoiding meetings.&lt;/p&gt;
&lt;p&gt;It&amp;#39;s about making better use of them.&lt;/p&gt;
&lt;p&gt;I also believe important decisions should be documented afterward.&lt;/p&gt;
&lt;p&gt;A conversation can create the impression that everyone agrees, while participants leave with different interpretations of what was decided.&lt;/p&gt;
&lt;p&gt;A written record of the decision, its rationale, the remaining risks, and who owns the next steps gives everyone something concrete to work from.&lt;/p&gt;
&lt;p&gt;Of course, documentation alone doesn&amp;#39;t create alignment. People need to acknowledge the decision and act on it.&lt;/p&gt;
&lt;p&gt;But it provides a foundation for shared understanding rather than relying on everyone&amp;#39;s memory of a conversation.&lt;/p&gt;
&lt;h2&gt;Technical leadership is ultimately about responsibility&lt;/h2&gt;
&lt;p&gt;The more I work with clients, the more I realize that my responsibility extends beyond the code I personally write.&lt;/p&gt;
&lt;p&gt;I&amp;#39;m responsible for understanding what they&amp;#39;re trying to achieve.&lt;/p&gt;
&lt;p&gt;For identifying technical risks they may not see.&lt;/p&gt;
&lt;p&gt;For explaining the consequences of their options.&lt;/p&gt;
&lt;p&gt;For making recommendations grounded in their circumstances rather than my personal preferences.&lt;/p&gt;
&lt;p&gt;And for helping turn their decisions into working systems.&lt;/p&gt;
&lt;p&gt;This doesn&amp;#39;t mean taking responsibility for every decision or every action taken by every team.&lt;/p&gt;
&lt;p&gt;Leadership also requires clear ownership, appropriate boundaries, and knowing when a decision belongs to someone else.&lt;/p&gt;
&lt;p&gt;But it does mean thinking beyond your individual contribution.&lt;/p&gt;
&lt;p&gt;A successful implementation isn&amp;#39;t necessarily the one that most closely resembles the architecture you would have designed in isolation.&lt;/p&gt;
&lt;p&gt;It&amp;#39;s one that meets the business&amp;#39;s needs, can be operated and maintained by the people responsible for it, and achieves the outcomes the project was intended to deliver.&lt;/p&gt;
&lt;p&gt;I&amp;#39;m still learning how to communicate these ideas more clearly.&lt;/p&gt;
&lt;p&gt;Sometimes I explain too much. Sometimes I assume that something obvious to me will be obvious to someone else. Sometimes I need to recognize sooner that the conversation has moved from evaluating options to deciding what happens next.&lt;/p&gt;
&lt;p&gt;But I think that is part of developing as a technical leader.&lt;/p&gt;
&lt;p&gt;The technical knowledge remains essential. Without it, you cannot reliably evaluate the options or understand their consequences.&lt;/p&gt;
&lt;p&gt;But knowledge alone doesn&amp;#39;t help a client make a decision.&lt;/p&gt;
&lt;p&gt;You have to make that knowledge accessible, apply it to their circumstances, and remain accountable for the work that follows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Having the answer is valuable. Helping people understand their options, make informed decisions, and turn those decisions into successful outcomes is what technical leadership is really about.&lt;/strong&gt;&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Related Reading &amp;amp; Architectural Strategy&lt;/h2&gt;
&lt;p&gt;If you are navigating technical decisions, team coordination, or platform migrations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/client-needs-judgment-not-preferred-technology&quot;&gt;Client Judgment vs. Preferred Technology&lt;/a&gt;&lt;/strong&gt; — Why senior engineering delivery is about objective trade-off analysis rather than personal tool preference.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/when-helping-creates-more-work&quot;&gt;When Helping Creates More Work&lt;/a&gt;&lt;/strong&gt; — Why adding developers to an in-flight project often creates coordination friction, and how shared context prevents duplicated work.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/stop-starting-from-scratch-vertical-slices-reusable-frontends&quot;&gt;Stop Starting From Scratch: Vertical Slices in Frontends&lt;/a&gt;&lt;/strong&gt; — How component abstraction levels and vertical slices keep teams aligned without rewriting code.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/architecture-first-website-rebuilds&quot;&gt;Architecture-First Website Rebuilds&lt;/a&gt;&lt;/strong&gt; — Why website projects must start with data architecture and business requirements rather than mockups.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/taking-over-a-frontend-framework&quot;&gt;How to Take Over a Frontend: A 4-Step Production Framework&lt;/a&gt;&lt;/strong&gt; — How to preserve design parity, integrate vertically, and deliver without high-risk rewrites.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;a href=&quot;/blog/enterprise-clients-readiness-checklist&quot;&gt;Enterprise Clients Readiness Checklist&lt;/a&gt;&lt;/strong&gt; — Documentation, security baselines, account ownership, and SLAs for agencies.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you are planning an upcoming replatforming or need an objective evaluation of your CMS architecture, explore my &lt;a href=&quot;/cms-architecture-review&quot;&gt;CMS Architecture Review&lt;/a&gt; advisory or read more on &lt;a href=&quot;/b2b-website-strategy&quot;&gt;B2B Website Strategy&lt;/a&gt;.&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/technical-leadership-more-than-having-the-answer"/>
        </item>
        <item>
            <title><![CDATA[How to Implement Content Signals in Next.js 16 (robots.ts)]]></title>
            <description><![CDATA[<p>I was recently looking through my Cloudflare dashboard, checking their new AI Overview and scraper analytics, when I noticed something glaring: my production site had no signal preferences configured at all. While bots and AI crawlers were routinely visiting my content, Cloudflare&#39;s report showed blank preferences because standard <code>robots.txt</code> offers only binary choices—either you allow an automated crawler completely, or you lock them out entirely.</p>
<p>With AI crawlers indexing content for live search answers, RAG systems, and foundation model training, site owners need a way to declare nuanced, granular permissions without blocking traditional search discovery.</p>
<p>When I tried to configure the emerging Content Signals standard in Next.js, I hit an immediate framework limitation: older versions of <code>robots.ts</code> stripped non-standard directives from output. With Next.js 16.3, the framework introduced an official escape hatch for non-standard directives. In this guide, I will show you how to implement Content Signals directly inside <code>app/robots.ts</code> using the new <code>other</code> directive map, declaring clear preferences for search indexing, live AI answers, and model training.</p>
<hr>
<h2>Understanding Content Signals Directives</h2>
<p>Before writing configuration code, we need to understand how Content Signals convey publisher preferences to automated crawlers. Originating from an IETF internet draft and popularized by Cloudflare, Content Signals establish three distinct categories of content usage:</p>
<ol>
<li><code>search</code>: Building a search engine index and displaying links and short snippets in search results.</li>
<li><code>ai-input</code>: Passing website content into an AI system in real time, such as Retrieval-Augmented Generation (RAG) queries, grounded chat answers, or AI search summaries.</li>
<li><code>ai-train</code>: Ingesting content to train, pre-train, or fine-tune artificial intelligence foundation models.</li>
</ol>
<p>Each category accepts a simple <code>yes</code> or <code>no</code> value. A directive string combines them in comma-delimited pairs, like this:</p>
<pre><code class="language-txt">Content-Signal: ai-train=yes, search=yes, ai-input=yes
</code></pre>
<p>Depending on your business goals, you can disallow model training while remaining discoverable in AI search engines, or you can allow full access across all three categories to maximize your presence across AI assistants and web crawlers.</p>
<hr>
<h2>Step 1: Upgrading Next.js to 16.3 or Newer</h2>
<p>Next.js added support for custom directives on crawler rules in version 16.3.0. In older releases, the <code>MetadataRoute.Robots</code> TypeScript interface and the underlying string generator only handled <code>userAgent</code>, <code>allow</code>, <code>disallow</code>, and <code>crawlDelay</code>. Any additional keys passed to the rule object were quietly dropped during serialization.</p>
<p>Check your current Next.js version in <code>package.json</code> and ensure it is updated to at least <code>16.3.0</code>:</p>
<pre><code class="language-json">// File: package.json
{
  &quot;dependencies&quot;: {
    &quot;next&quot;: &quot;^16.3.5&quot;
  }
}
</code></pre>
<p>If you need to update your installation, run your package manager update command:</p>
<pre><code class="language-bash">pnpm add next@latest
</code></pre>
<p>This ensures your project receives the updated <code>MetadataRoute.Robots</code> types, which include the <code>other</code> directive record:</p>
<pre><code class="language-typescript">type RobotsRule = {
  userAgent?: string | string[]
  allow?: string | string[]
  disallow?: string | string[]
  crawlDelay?: number
  other?: Record&lt;string, string | number | Array&lt;string | number&gt;&gt;
}
</code></pre>
<p>With the package upgraded, Next.js will preserve the exact casing of keys declared inside <code>other</code> and render each key-value pair directly beneath the corresponding <code>User-agent</code> block.</p>
<hr>
<h2>Step 2: Configuring Content Signals in <code>app/robots.ts</code></h2>
<p>Now we can implement our rules inside <code>src/app/robots.ts</code>. We want our signals to apply both to generic crawlers via the wildcard <code>*</code> agent and to specific, high-profile AI crawlers such as <code>GPTBot</code>, <code>ClaudeBot</code>, and <code>PerplexityBot</code>.</p>
<p>Here is the complete implementation:</p>
<pre><code class="language-typescript">// File: src/app/robots.ts
import { MetadataRoute } from &#39;next&#39;
import { siteOrigin } from &#39;@/lib/site-url&#39;

const baseUrl = siteOrigin

const adminPaths = [&#39;/studio&#39;, &#39;/api/&#39;, &#39;/admin&#39;, &#39;/dashboard&#39;, &#39;/wp-admin&#39;]

const llmAgents = [
  &#39;GPTBot&#39;,
  &#39;ChatGPT-User&#39;,
  &#39;Claude-Web&#39;,
  &#39;ClaudeBot&#39;,
  &#39;anthropic-ai&#39;,
  &#39;PerplexityBot&#39;,
  &#39;CCBot&#39;,
  &#39;Omgilibot&#39;,
  &#39;FacebookBot&#39;,
  &#39;Google-Extended&#39;,
  &#39;cohere-ai&#39;,
  &#39;Applebot-Extended&#39;,
  &#39;Bytespider&#39;,
  &#39;Diffbot&#39;,
]

export default function robots(): MetadataRoute.Robots {
  const contentSignalPolicy = &#39;ai-train=yes, search=yes, ai-input=yes&#39;

  return {
    sitemap: `${baseUrl}/sitemap.xml`,
    rules: [
      {
        userAgent: &#39;*&#39;,
        allow: &#39;/&#39;,
        disallow: adminPaths,
        other: {
          &#39;Content-Signal&#39;: contentSignalPolicy,
        },
      },
      ...llmAgents.map((userAgent) =&gt; ({
        userAgent,
        allow: &#39;/&#39;,
        disallow: adminPaths,
        other: {
          &#39;Content-Signal&#39;: contentSignalPolicy,
        },
      })),
    ],
  }
}
</code></pre>
<p>In this implementation, we define an array of restricted administrative paths and a list of recognized LLM crawler identifiers. We define our <code>contentSignalPolicy</code> variable according to our preferred permissions. In this example, we set <code>ai-train=yes, search=yes, ai-input=yes</code> to invite search engines, citation systems, and AI tools to index and cite our work freely.</p>
<p>Next, we map our rules array. The first rule targets the global wildcard <code>*</code>. The subsequent rules iterate through our list of specific AI user-agents. Inside each rule, we supply the <code>other</code> dictionary with our <code>&#39;Content-Signal&#39;</code> header.</p>
<p>Because robots.txt parser rules state that crawlers matching a specific user-agent header disregard the generic wildcard block, adding <code>other</code> to each explicit AI bot entry ensures the directive is observed regardless of which block the crawler matches.</p>
<hr>
<h2>Step 3: Verifying the Generated <code>robots.txt</code> Output</h2>
<p>Next.js automatically serves the return value of <code>app/robots.ts</code> at the <code>/robots.txt</code> path. You can verify the final serialized text by running your development server or requesting the route directly in your browser.</p>
<p>The generated output will look like this:</p>
<pre><code class="language-txt">User-Agent: *
Allow: /
Disallow: /studio
Disallow: /api/
Disallow: /admin
Disallow: /dashboard
Disallow: /wp-admin
Content-Signal: ai-train=yes, search=yes, ai-input=yes

User-Agent: GPTBot
Allow: /
Disallow: /studio
Disallow: /api/
Disallow: /admin
Disallow: /dashboard
Disallow: /wp-admin
Content-Signal: ai-train=yes, search=yes, ai-input=yes

User-Agent: ClaudeBot
Allow: /
Disallow: /studio
Disallow: /api/
Disallow: /admin
Disallow: /dashboard
Disallow: /wp-admin
Content-Signal: ai-train=yes, search=yes, ai-input=yes

Sitemap: https://www.buildwithmatija.com/sitemap.xml
</code></pre>
<p>Notice how Next.js preserves the <code>Content-Signal</code> casing and groups the directive cleanly inside each stanza. The admin paths remain disallowed, the sitemap URL resolves dynamically against your configured domain, and compliant AI scrapers receive unambiguous guidelines on how your content may be consumed.</p>
<hr>
<h2>Conclusion</h2>
<p>Controlling how automated agents interact with your content no longer requires an all-or-nothing approach. In this guide, we explored how the Content Signals standard categorizes automated content usage across search indexing, real-time AI input, and model training. We then leveraged the <code>other</code> directive map introduced in Next.js 16.3 to emit type-safe, non-standard directives directly inside <code>app/robots.ts</code>, avoiding the need to write custom route handlers or manage raw static text files.</p>
<p>With this setup in place, your application provides clear, machine-readable preferences for search engines and AI operators while keeping your metadata configuration centralized and maintainable.</p>
<p>Keep in mind that application-level rules in <code>robots.ts</code> only take effect if the incoming crawler actually reaches Next.js. If you host on Vercel, automated AI agents from cloud hosting IP ranges may be throttled before this file is ever evaluated — see <a href="/blog/configure-vercel-firewall-ai-bots-edge-rate-limits">Configure Vercel Firewall for AI Bots Without 429 Rate Limits</a> for the companion edge WAF configuration. For multi-site setups, see <a href="/blog/dynamic-robots-txt-nextjs-multi-tenant">Dynamic robots.txt in Multi-Tenant Next.js</a>, and pair this with an <a href="/blog/implementing-llms-txt-nextjs-15-sanity-cms">llms.txt route for structured agent discovery</a>.</p>
<p>Let me know in the comments if you have questions, and subscribe for more practical development guides.</p>
<p>Thanks, Matija</p>
]]></description>
            <link>https://www.buildwithmatija.com/blog/content-signals-nextjs-robots-txt</link>
            <guid isPermaLink="false">https://www.buildwithmatija.com/blog/content-signals-nextjs-robots-txt</guid>
            <category><![CDATA[Next.js]]></category>
            <dc:creator><![CDATA[Matija Žiberna]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 14:20:00 GMT</pubDate>
            <content:encoded>&lt;p&gt;I was recently looking through my Cloudflare dashboard, checking their new AI Overview and scraper analytics, when I noticed something glaring: my production site had no signal preferences configured at all. While bots and AI crawlers were routinely visiting my content, Cloudflare&amp;#39;s report showed blank preferences because standard &lt;code&gt;robots.txt&lt;/code&gt; offers only binary choices—either you allow an automated crawler completely, or you lock them out entirely.&lt;/p&gt;
&lt;p&gt;With AI crawlers indexing content for live search answers, RAG systems, and foundation model training, site owners need a way to declare nuanced, granular permissions without blocking traditional search discovery.&lt;/p&gt;
&lt;p&gt;When I tried to configure the emerging Content Signals standard in Next.js, I hit an immediate framework limitation: older versions of &lt;code&gt;robots.ts&lt;/code&gt; stripped non-standard directives from output. With Next.js 16.3, the framework introduced an official escape hatch for non-standard directives. In this guide, I will show you how to implement Content Signals directly inside &lt;code&gt;app/robots.ts&lt;/code&gt; using the new &lt;code&gt;other&lt;/code&gt; directive map, declaring clear preferences for search indexing, live AI answers, and model training.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Understanding Content Signals Directives&lt;/h2&gt;
&lt;p&gt;Before writing configuration code, we need to understand how Content Signals convey publisher preferences to automated crawlers. Originating from an IETF internet draft and popularized by Cloudflare, Content Signals establish three distinct categories of content usage:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;code&gt;search&lt;/code&gt;: Building a search engine index and displaying links and short snippets in search results.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ai-input&lt;/code&gt;: Passing website content into an AI system in real time, such as Retrieval-Augmented Generation (RAG) queries, grounded chat answers, or AI search summaries.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ai-train&lt;/code&gt;: Ingesting content to train, pre-train, or fine-tune artificial intelligence foundation models.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Each category accepts a simple &lt;code&gt;yes&lt;/code&gt; or &lt;code&gt;no&lt;/code&gt; value. A directive string combines them in comma-delimited pairs, like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-txt&quot;&gt;Content-Signal: ai-train=yes, search=yes, ai-input=yes
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Depending on your business goals, you can disallow model training while remaining discoverable in AI search engines, or you can allow full access across all three categories to maximize your presence across AI assistants and web crawlers.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Step 1: Upgrading Next.js to 16.3 or Newer&lt;/h2&gt;
&lt;p&gt;Next.js added support for custom directives on crawler rules in version 16.3.0. In older releases, the &lt;code&gt;MetadataRoute.Robots&lt;/code&gt; TypeScript interface and the underlying string generator only handled &lt;code&gt;userAgent&lt;/code&gt;, &lt;code&gt;allow&lt;/code&gt;, &lt;code&gt;disallow&lt;/code&gt;, and &lt;code&gt;crawlDelay&lt;/code&gt;. Any additional keys passed to the rule object were quietly dropped during serialization.&lt;/p&gt;
&lt;p&gt;Check your current Next.js version in &lt;code&gt;package.json&lt;/code&gt; and ensure it is updated to at least &lt;code&gt;16.3.0&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;// File: package.json
{
  &amp;quot;dependencies&amp;quot;: {
    &amp;quot;next&amp;quot;: &amp;quot;^16.3.5&amp;quot;
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you need to update your installation, run your package manager update command:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pnpm add next@latest
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This ensures your project receives the updated &lt;code&gt;MetadataRoute.Robots&lt;/code&gt; types, which include the &lt;code&gt;other&lt;/code&gt; directive record:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;type RobotsRule = {
  userAgent?: string | string[]
  allow?: string | string[]
  disallow?: string | string[]
  crawlDelay?: number
  other?: Record&amp;lt;string, string | number | Array&amp;lt;string | number&amp;gt;&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With the package upgraded, Next.js will preserve the exact casing of keys declared inside &lt;code&gt;other&lt;/code&gt; and render each key-value pair directly beneath the corresponding &lt;code&gt;User-agent&lt;/code&gt; block.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Step 2: Configuring Content Signals in &lt;code&gt;app/robots.ts&lt;/code&gt;&lt;/h2&gt;
&lt;p&gt;Now we can implement our rules inside &lt;code&gt;src/app/robots.ts&lt;/code&gt;. We want our signals to apply both to generic crawlers via the wildcard &lt;code&gt;*&lt;/code&gt; agent and to specific, high-profile AI crawlers such as &lt;code&gt;GPTBot&lt;/code&gt;, &lt;code&gt;ClaudeBot&lt;/code&gt;, and &lt;code&gt;PerplexityBot&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Here is the complete implementation:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-typescript&quot;&gt;// File: src/app/robots.ts
import { MetadataRoute } from &amp;#39;next&amp;#39;
import { siteOrigin } from &amp;#39;@/lib/site-url&amp;#39;

const baseUrl = siteOrigin

const adminPaths = [&amp;#39;/studio&amp;#39;, &amp;#39;/api/&amp;#39;, &amp;#39;/admin&amp;#39;, &amp;#39;/dashboard&amp;#39;, &amp;#39;/wp-admin&amp;#39;]

const llmAgents = [
  &amp;#39;GPTBot&amp;#39;,
  &amp;#39;ChatGPT-User&amp;#39;,
  &amp;#39;Claude-Web&amp;#39;,
  &amp;#39;ClaudeBot&amp;#39;,
  &amp;#39;anthropic-ai&amp;#39;,
  &amp;#39;PerplexityBot&amp;#39;,
  &amp;#39;CCBot&amp;#39;,
  &amp;#39;Omgilibot&amp;#39;,
  &amp;#39;FacebookBot&amp;#39;,
  &amp;#39;Google-Extended&amp;#39;,
  &amp;#39;cohere-ai&amp;#39;,
  &amp;#39;Applebot-Extended&amp;#39;,
  &amp;#39;Bytespider&amp;#39;,
  &amp;#39;Diffbot&amp;#39;,
]

export default function robots(): MetadataRoute.Robots {
  const contentSignalPolicy = &amp;#39;ai-train=yes, search=yes, ai-input=yes&amp;#39;

  return {
    sitemap: `${baseUrl}/sitemap.xml`,
    rules: [
      {
        userAgent: &amp;#39;*&amp;#39;,
        allow: &amp;#39;/&amp;#39;,
        disallow: adminPaths,
        other: {
          &amp;#39;Content-Signal&amp;#39;: contentSignalPolicy,
        },
      },
      ...llmAgents.map((userAgent) =&amp;gt; ({
        userAgent,
        allow: &amp;#39;/&amp;#39;,
        disallow: adminPaths,
        other: {
          &amp;#39;Content-Signal&amp;#39;: contentSignalPolicy,
        },
      })),
    ],
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this implementation, we define an array of restricted administrative paths and a list of recognized LLM crawler identifiers. We define our &lt;code&gt;contentSignalPolicy&lt;/code&gt; variable according to our preferred permissions. In this example, we set &lt;code&gt;ai-train=yes, search=yes, ai-input=yes&lt;/code&gt; to invite search engines, citation systems, and AI tools to index and cite our work freely.&lt;/p&gt;
&lt;p&gt;Next, we map our rules array. The first rule targets the global wildcard &lt;code&gt;*&lt;/code&gt;. The subsequent rules iterate through our list of specific AI user-agents. Inside each rule, we supply the &lt;code&gt;other&lt;/code&gt; dictionary with our &lt;code&gt;&amp;#39;Content-Signal&amp;#39;&lt;/code&gt; header.&lt;/p&gt;
&lt;p&gt;Because robots.txt parser rules state that crawlers matching a specific user-agent header disregard the generic wildcard block, adding &lt;code&gt;other&lt;/code&gt; to each explicit AI bot entry ensures the directive is observed regardless of which block the crawler matches.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Step 3: Verifying the Generated &lt;code&gt;robots.txt&lt;/code&gt; Output&lt;/h2&gt;
&lt;p&gt;Next.js automatically serves the return value of &lt;code&gt;app/robots.ts&lt;/code&gt; at the &lt;code&gt;/robots.txt&lt;/code&gt; path. You can verify the final serialized text by running your development server or requesting the route directly in your browser.&lt;/p&gt;
&lt;p&gt;The generated output will look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-txt&quot;&gt;User-Agent: *
Allow: /
Disallow: /studio
Disallow: /api/
Disallow: /admin
Disallow: /dashboard
Disallow: /wp-admin
Content-Signal: ai-train=yes, search=yes, ai-input=yes

User-Agent: GPTBot
Allow: /
Disallow: /studio
Disallow: /api/
Disallow: /admin
Disallow: /dashboard
Disallow: /wp-admin
Content-Signal: ai-train=yes, search=yes, ai-input=yes

User-Agent: ClaudeBot
Allow: /
Disallow: /studio
Disallow: /api/
Disallow: /admin
Disallow: /dashboard
Disallow: /wp-admin
Content-Signal: ai-train=yes, search=yes, ai-input=yes

Sitemap: https://www.buildwithmatija.com/sitemap.xml
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice how Next.js preserves the &lt;code&gt;Content-Signal&lt;/code&gt; casing and groups the directive cleanly inside each stanza. The admin paths remain disallowed, the sitemap URL resolves dynamically against your configured domain, and compliant AI scrapers receive unambiguous guidelines on how your content may be consumed.&lt;/p&gt;
&lt;hr&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Controlling how automated agents interact with your content no longer requires an all-or-nothing approach. In this guide, we explored how the Content Signals standard categorizes automated content usage across search indexing, real-time AI input, and model training. We then leveraged the &lt;code&gt;other&lt;/code&gt; directive map introduced in Next.js 16.3 to emit type-safe, non-standard directives directly inside &lt;code&gt;app/robots.ts&lt;/code&gt;, avoiding the need to write custom route handlers or manage raw static text files.&lt;/p&gt;
&lt;p&gt;With this setup in place, your application provides clear, machine-readable preferences for search engines and AI operators while keeping your metadata configuration centralized and maintainable.&lt;/p&gt;
&lt;p&gt;Keep in mind that application-level rules in &lt;code&gt;robots.ts&lt;/code&gt; only take effect if the incoming crawler actually reaches Next.js. If you host on Vercel, automated AI agents from cloud hosting IP ranges may be throttled before this file is ever evaluated — see &lt;a href=&quot;/blog/configure-vercel-firewall-ai-bots-edge-rate-limits&quot;&gt;Configure Vercel Firewall for AI Bots Without 429 Rate Limits&lt;/a&gt; for the companion edge WAF configuration. For multi-site setups, see &lt;a href=&quot;/blog/dynamic-robots-txt-nextjs-multi-tenant&quot;&gt;Dynamic robots.txt in Multi-Tenant Next.js&lt;/a&gt;, and pair this with an &lt;a href=&quot;/blog/implementing-llms-txt-nextjs-15-sanity-cms&quot;&gt;llms.txt route for structured agent discovery&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Let me know in the comments if you have questions, and subscribe for more practical development guides.&lt;/p&gt;
&lt;p&gt;Thanks, Matija&lt;/p&gt;
</content:encoded>
            <link rel="canonical" href="https://www.buildwithmatija.com/blog/content-signals-nextjs-robots-txt"/>
        </item>
    </channel>
</rss>