<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anna Carolina on Medium]]></title>
        <description><![CDATA[Stories by Anna Carolina on Medium]]></description>
        <link>https://medium.com/@annacezar?source=rss-e072c71722a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A6zIOCS5oAq78KYJ7Xm36g.jpeg</url>
            <title>Stories by Anna Carolina on Medium</title>
            <link>https://medium.com/@annacezar?source=rss-e072c71722a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:40:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@annacezar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Caching in Next.js: Rendering, Revalidation, and Invalidation]]></title>
            <link>https://medium.com/@annacezar/caching-in-next-js-rendering-revalidation-and-invalidation-5feb8fff3685?source=rss-e072c71722a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5feb8fff3685</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Anna Carolina]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 17:43:58 GMT</pubDate>
            <atom:updated>2026-08-06T17:43:58.974Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4: How Cache Components, static generation, ISR, dynamic rendering, and CDN policies interact while producing and distributing a response.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8L3DHwCk5m48opY7qFsS8w.png" /></figure><p><em>This is Part 4 of &quot;</em><strong><em>Caching Across the Modern Web Stack&quot;</em></strong><em>, a four-part series that follows cached representations from the browser, through client-side state and the CDN, to the Next.js application server. </em><a href="https://accezar.github.io/notes/camadas-de-cache/"><em>Read the complete PT-BR version here.</em></a></p><p><a href="https://medium.com/@annacezar/cache-identity-across-the-modern-web-stack-what-exactly-are-we-reusing-d135b4d9a0cf">Part 1 — Cache Identity Across the Modern Web Stack</a></p><p><a href="https://medium.com/@annacezar/browser-caching-http-cache-service-workers-and-cache-storage-409736a75402">Part 2 — Browser Caching</a></p><p><a href="https://medium.com/@annacezar/2d7367283f3a">Part 3 — From Query Cache to CDN</a></p><p>The previous parts followed reusable representations through the browser, application state, and the CDN. When a request finally reaches the application, reuse can still happen before an HTTP response exists. Next.js may combine cached computations, prerendered output, and request-specific work while constructing that response.</p><h3>Rendering and Caching in Next.js</h3><p>When a request reaches the application, Next.js does not necessarily have to repeat all the work required to assemble the page. It may reuse results that were already produced, generate stable content during the build, and execute only the work that depends on the current request.</p><p>This happens before the HTTP response is created. Stored query results and prerendered regions can be incorporated immediately, while cookies, headers, and data that must reflect the current state are resolved for that access.</p><p>This section uses <strong><em>Next.js 16.3</em></strong><em>, released on August 3, 2026</em>, with <strong>App Router</strong> and <strong>Cache Components</strong> as its reference. The model was introduced in <strong>Next.js 16</strong> and remains explicitly enabled through cacheComponents. With that configuration, reusable results are declared with &quot;use cache&quot;, while uncached data remains tied to the current execution. <a href="https://nextjs.org/blog/next-16-3">Next.js 16.3</a>; <a href="https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents">Next.js — Cache Components</a></p><h4>Identity, Lifetime, and Revalidation in Cache Components</h4><p>&quot;use cache&quot;may be declared in a function, component, or route. The result becomes eligible for reuse, while its arguments and relevant external values distinguish the entries produced. <a href="https://nextjs.org/docs/app/api-reference/directives/use-cache">Next.js — use cache</a></p><p>Instead of scattering unexplained durations across components, the application can define profiles that correspond to different kinds of content:</p><pre>// next.config.ts<br><br>import type { NextConfig } from &quot;next&quot;;<br><br>const nextConfig: NextConfig = {<br> cacheComponents: true,<br>  cacheLife: {<br>   productCatalog: {<br>   stale: 300,<br>   revalidate: 900,<br>   expire: 86_400,<br>  },<br>  campaign: {<br>   stale: 30,<br>   revalidate: 60,<br>   expire: 600,<br>   },<br>  },<br>};<br><br>export default nextConfig;</pre><p>The <strong>productCatalog</strong> profile declares five minutes of reuse in the client router, permits server refresh after fifteen minutes, and limits the maximum period during which the entry may remain stale to one day.</p><p>The component defines how long its result may be reused and adds a tag that can invalidate the entry when the product changes:</p><pre>import { cacheLife, cacheTag } from &quot;next/cache&quot;;<br><br>export async function ProductPresentation({<br>  productId,<br>  locale,<br>}: {<br>  productId: string;<br>  locale: string;<br>}) {<br><br>  &quot;use cache&quot;;<br>  cacheLife(&quot;productCatalog&quot;);<br>  cacheTag(`product:${productId}`);<br><br>  const product = await getProduct(productId, locale);<br><br>  return (<br>    &lt;section&gt;<br>       &lt;h1&gt;{product.name}&lt;/h1&gt; &lt;p&gt;{product.description}&lt;/p&gt; <br>    &lt;/section&gt;<br>  );<br>}</pre><p><strong>Product 123</strong> in <strong><em>pt-BR</em></strong> and the same product in <strong><em>en-US</em></strong> produce different entries because locale changes the output. Both versions may receive the product:123 tag, allowing a product update to reach them without making the tag part of entry lookup. <a href="https://nextjs.org/docs/app/api-reference/functions/cacheTag">Next.js — cacheTag</a></p><p>Identity also incorporates the current application version. Results produced for a previous build are not treated as equivalent to results from newly deployed code. <a href="https://nextjs.org/docs/app/api-reference/directives/use-cache">Next.js — use cache</a></p><p>stale, revalidate, and expire control different parts of the path:</p><ul><li><strong>stale: </strong>How long the client router may reuse the content without consulting the server.</li><li><strong>revalidate: </strong>The point after which the server may refresh the entry while serving the existing value.</li><li><strong>expire:</strong> The limit after which the server must regenerate the content before continuing to use the entry.</li></ul><p>When revalidate and expire are configured together, expire must be greater. <a href="https://nextjs.org/docs/app/api-reference/functions/cacheLife">Next.js — cacheLife</a></p><p>Consider an entry produced at <strong>10:00</strong> with the previous profile.</p><pre>10:00<br>→ entry produced<br><br>until 10:05<br>→ the client router reuses it without consulting the server<br><br>after 10:05<br>→ navigation may return to the server<br><br>after 10:15<br>→ the server may return the existing entry<br>→ a recent version is produced in the background<br><br>after the expire limit<br>→ the next read must wait for a new result</pre><p>Between <strong>10:00</strong> and <strong>10:05</strong>, the router may reuse it without consulting the server. After five minutes, a new navigation may return to the server. That does not mean the data will immediately be fetched again, because the revalidate window has not yet ended.</p><p>After <strong>10:15</strong>, the next request reaching the server may receive the existing version while Next.js starts updating it in the background. Once the new execution finishes, later requests begin using the refreshed result.</p><p>If the entry is not updated before expire, the next request waits for a new result to be produced. This behavior resembles a <em>stale-while-revalidate</em> strategy, but it acts inside the Next.js cache. It is not the same mechanism as the HTTP directive:</p><pre>Cache-Control: stale-while-revalidate=60</pre><p>The HTTP directive guides a browser or CDN handling a response that has already been produced. cacheLife() controls results used by the framework while constructing that response. Both layers may serve previous content while refreshing their entries, but they maintain independent identities and clocks.</p><h4>Static Generation, ISR, and Dynamic Rendering</h4><p>Static generation, ISR, and dynamic rendering describe different moments at which Next.js may produce a representation.</p><p>With static generation, known output is prepared during the build. When the application enters production, that work is already complete and can be reused without a full new render for every access.</p><p>On a dynamic product route, generateStaticParams() can select the pages that should be prepared in advance:</p><pre>// app/products/[productId]/page.tsx<br>export async function generateStaticParams() {<br>  const productIds = await getMostVisitedProductIds();<br>  return productIds.map((productId) =&gt; ({<br>    productId,<br>  }));<br>}</pre><p>A store with one hundred thousand products does not need to render the entire catalog during compilation. It can generate the most frequently accessed items during the build, reducing latency for their first visits, and leave the remaining pages to be produced when accessed. With <strong>Cache Components</strong>, generateStaticParams() identifies values known during prerendering and allows the framework to prepare the corresponding shell. <a href="https://nextjs.org/docs/app/api-reference/functions/generate-static-params">Next.js — generateStaticParams</a></p><p><strong>Incremental Static Regeneration</strong> extends that set after deployment. A route without a concrete version may be produced when first accessed and reused by later requests. An existing page may also be refreshed without rebuilding the entire site. The current documentation distinguishes ISR with Cache Components from the previous model based on segment revalidate or fetch options. <a href="https://nextjs.org/docs/app/getting-started/caching">Next.js — Caching</a></p><p>Dynamic rendering remains necessary when output depends on information that exists only during the request or must not be stored. Session state, headers, cookies, certain parameters, and reads that must reflect the current moment remain outside shared cache scopes.</p><p><strong>Cache Components</strong> allows those behaviors to coexist in the same route. The framework may prerender a shell containing stable content and Suspense fallbacks, while dynamic regions are produced and streamed later. This composition is the model known as <strong>Partial Prerendering</strong>. <a href="https://nextjs.org/docs/app/guides/ppr-platform-guide">Next.js — PPR Platform Guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JLL2700OiJg61xsRkdQHwQ.png" /></figure><h4>Stable Content with Dynamic Data</h4><p>A product page during Black Friday combines information with incompatible lifecycles:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iYIP09hBFOfgaqb0-qITw.png" /></figure><p>Applying the product-specification policy to the entire page would retain price and inventory for too long. Applying the inventory frequency to the whole page would force the server to repeatedly rebuild descriptions, structure, and information that rarely change.</p><p>The campaign may receive its own profile:</p><pre>import { cacheLife, cacheTag } from &quot;next/cache&quot;;<br>export async function CampaignBanner({<br>  campaignId,<br>  region,<br>}: {<br>  campaignId: string;<br>  region: string;<br>}) {<br>  &quot;use cache&quot;;<br>  cacheLife(&quot;campaign&quot;);<br>  cacheTag(`campaign:${campaignId}`);<br>  const campaign = await getCampaign(campaignId, region);<br>  return &lt;Banner campaign={campaign} /&gt;;<br>}</pre><p><strong>campaignId</strong> and <strong>region</strong> distinguish campaigns and regional conditions. The result may be shared among users in the same region without following the catalog’s refresh cycle.</p><p>The route combines those regions with data that remains dynamic:</p><pre>import { Suspense } from &quot;react&quot;;<br>import { ProductPresentation } from &quot;./product-presentation&quot;;<br>import { CampaignBanner } from &quot;./campaign-banner&quot;;<br>import { CurrentOffer } from &quot;./current-offer&quot;;<br>import { Availability } from &quot;./availability&quot;;<br>import { DeliveryEstimate } from &quot;./delivery-estimate&quot;;<br>export default async function Page({<br>  params,<br>}: {<br>  params: Promise&lt;{ productId: string }&gt;;<br>}) {<br>  const { productId } = await params;<br>  return (<br>    &lt;main&gt;<br>       &lt;CampaignBanner campaignId=&quot;black-friday-2026&quot; region=&quot;BR&quot; /&gt;<br>       &lt;ProductPresentation productId={productId} locale=&quot;pt-BR&quot; /&gt; <br>      &lt;Suspense fallback={&lt;OfferSkeleton /&gt;}&gt;<br>         &lt;CurrentOffer productId={productId} /&gt; <br>      &lt;/Suspense&gt;<br>       <br>      &lt;Suspense fallback={&lt;AvailabilitySkeleton /&gt;}&gt;<br>         &lt;Availability productId={productId} /&gt; <br>      &lt;/Suspense&gt;<br>       <br>      &lt;Suspense fallback={&lt;DeliverySkeleton /&gt;}&gt;<br>         &lt;DeliveryEstimate productId={productId} /&gt; <br>      &lt;/Suspense&gt;<br>       <br>    &lt;/main&gt;<br>  );<br>}</pre><p>For products previously selected by generateStaticParams(), Next.js can prepare the shell during the build. That shell contains the reusable regions and the fallbacks for areas that depend on the request. Offer, availability, and delivery are resolved when the page is accessed and reach the browser progressively. <a href="https://nextjs.org/docs/app/api-reference/functions/generate-static-params">Next.js — generateStaticParams</a></p><p>Streaming controls delivery order. It allows the structure and already available content to arrive before slower reads, but it does not automatically turn every Suspense boundary into an independent CDN entry. The CDN continues storing HTTP representations according to the headers and variants it receives.</p><p>Displayed availability is not a reservation, and a displayed price does not complete the transaction. These values guide navigation. Checkout must validate price, inventory, authorization, and commercial conditions again at the source responsible for the transaction.</p><p>This separation allows aggressive reuse of the public portion of the page without assigning transactional authority to a representation produced earlier.</p><h4>Time-Based and Event-Driven Revalidation</h4><p>Time-based revalidation works when the application knows the acceptable staleness but does not receive a reliable event whenever the source changes. Periodically checking a product description or editorial page is often sufficient.</p><p>When the change is known, waiting for the revalidate interval only extends inconsistency. A CMS webhook, an administrative action, or the start of a campaign can immediately mark related entries:</p><pre>import { revalidateTag } from &quot;next/cache&quot;;<br>export async function productUpdated(productId: string) {<br>  revalidateTag(`product:${productId}`, &quot;max&quot;);<br>}</pre><p>revalidateTag(tag, &quot;max&quot;) marks the entries as <em>stale</em>. On the next access, Next.js may serve the previous result while producing another in the background. The API is intended for content where a small window of eventual consistency is acceptable. <a href="https://nextjs.org/docs/app/api-reference/functions/revalidateTag">Next.js — revalidateTag</a></p><p>An update may be triggered by elapsed time or by an event known to the application.</p><blockquote><em>Time-based revalidation</em><br>→ the configured interval ends<br>→ the next read may refresh the entry</blockquote><blockquote><em>Event-driven revalidation</em><br>→ the application learns that the data changed<br>→ the tag is marked stale<br>→ the next read may refresh the entry</blockquote><p>When a person needs to see their own write in the next read, serving the previous value while a new version is produced violates the operation’s expectation. In that case, a Server Action can use updateTag():</p><pre>&quot;use server&quot;;<br>import { updateTag } from &quot;next/cache&quot;;<br>export async function updateProduct(productId: string, input: ProductInput) {<br>  await saveProduct(productId, input);<br>  updateTag(`product:${productId}`);<br>}</pre><p>updateTag() expires associated data immediately, and the next read waits for the updated content. Its use is restricted to Server Actions and supports <em>read your own writes</em> flows. <a href="https://nextjs.org/docs/app/api-reference/functions/updateTag">Next.js — updateTag</a></p><p>revalidatePath() works with a different unit:</p><pre>import { revalidatePath } from &quot;next/cache&quot;;<br>export async function productPageUpdated(productId: string) {<br>  revalidatePath(`/products/${productId}`);<br>}</pre><p>The function invalidates a specific page or layout. A tag follows the data wherever it appears; a path follows the route. A product present in a detail page, category, and recommendation is usually better represented by a tag. An isolated administrative page may be refreshed directly by path. <a href="https://nextjs.org/docs/app/api-reference/functions/revalidatePath">Next.js — revalidatePath</a></p><h4>Builds, Traffic Peaks, and Coordination with the CDN</h4><p>A new build creates another application version and produces known shells again. This is not the same as time-based or tag-based revalidation. A build replaces deployed code; revalidation replaces results inside the version already running.</p><p>During <strong>Black Friday</strong>, that distinction directly affects cold cache behavior. After deployment, pages generated by generateStaticParams() arrive prepared. The others may depend on the first visit to produce a concrete version. If highly visited products are absent from the prerendered set, the first requests during the peak pay simultaneously for data access, rendering, and cache population.</p><p>Warming should prioritize keys with predictable demand. The most visited products, main categories, and active campaign are natural candidates. Generating every combination of product, region, postal code, commercial group, and experiment in advance would only move the cost into the build and retain many entries with no reuse.</p><p>Misses also multiply work across dependencies. One page may query catalog, campaign, price, inventory, and recommendations. If thousands of entries are invalidated at once, each may rebuild that set of data. Broad invalidations need to account for source capacity and the time required to repopulate the most accessed results.</p><p>By default, &quot;use cache&quot; uses in-memory storage. In a deployment with several instances, each process may hold its own entries, and a newly created instance begins with a cold cache. &quot;use cache: remote&quot; allows shared storage through a cache handler, but adds serialization, network access, retention, and coordination. It becomes useful when several instances reuse the same keys and the avoided cost exceeds the remote access overhead. <a href="https://nextjs.org/docs/app/api-reference/directives/use-cache-remote">Next.js — use cache: remote</a>; <a href="https://nextjs.org/docs/app/guides/self-hosting">Next.js — Self-hosting</a></p><p>High-cardinality results usually provide little value in that store. A query unique to a user, postal code, sort order, filters, and experiment may produce an almost disposable entry. The fact that a function can receive &quot;use cache&quot; does not mean there will be enough sharing to justify retention.</p><p>Next.js revalidation also does not automatically remove a response that an external CDN still considers fresh. revalidateTag() may refresh results used by the framework while the CDN continues serving the previous representation until s-maxage ends or a purge arrives.</p><p>The reverse direction is equally incomplete: removing the response from the CDN makes the next request reach the application, but Next.js may still construct that response from an internal entry that was not invalidated. The documentation recommends integrating on-demand revalidation with the provider’s purge mechanism when the update must cross both layers. <a href="https://nextjs.org/docs/app/guides/cdn-caching">Next.js — CDN Caching</a></p><p>A critical change may require:</p><blockquote><em>product changed</em><br> → revalidate tags or paths in Next.js<br> → remove the corresponding responses from the CDN<br> → produce a new representation<br> → populate the shared layer again</blockquote><p>An editorial description may accept the regular revalidation cycle. A campaign with a known start time may be prepared before activation. An incorrectly published price requires a faster, coordinated response.</p><p>Applications without cacheComponents continue using the previous <strong>App Router</strong> model, with fetch options, <strong>Data Cache</strong>, <strong>Full Route Cache</strong>, and segment configuration. The two descriptions should not be combined as though they govern the same route. Before investigating behavior, confirm the Next.js version and whether <strong>Cache Components</strong> is enabled. <a href="https://nextjs.org/docs/app/guides/migrating-to-cache-components">Next.js — Migrating to Cache Components</a></p><p>Next.js completes the stage responsible for producing the response. It may prepare content at build time, generate pages through ISR, reuse functions and components, stream dynamic regions, and replace entries by time or event. Once the response exists, HTTP caches, the CDN, and client-side state again apply their own identities and validity periods.</p><h3>TL;DR</h3><p>Caching works safely when the application treats reuse as a contract over representations rather than as a vague property of data. That contract must identify the content, define who may receive it, establish acceptable staleness, and specify the event that replaces it.</p><p>This changes the architectural question. Instead of asking where to <strong><em>“add cache,”</em></strong> the system locates repeated work and selects the layer capable of avoiding it without widening inconsistency beyond the product’s tolerance. Versioned files benefit from long retention. Public content allows sharing. Personalized content requires isolation. Transactional data must return to the authoritative source before an operation is confirmed.</p><p>Behavior remains predictable when a change has an explicit path to every copy that depends on it. TTL covers updates tolerant to time. Validators reduce transfer. Tags and purge operations bring known changes forward. New URLs make file versions independent. Client-side revalidation reconciles interface state. No mechanism updates all the other layers by itself.</p><p>The target is not the highest possible hit rate. It is the combination of lower latency, less repeated work, and an information age compatible with the product. When identity, scope, freshness, and invalidation are designed together, the browser, Service Worker, CDN, and Next.js stop behaving like competing caches and begin operating as coordinated delivery layers.</p><p><em>This concludes Caching Across the Modern Web Stack. The full Portuguese version, with the entire path in one article, remains available on my blog.</em> <a href="https://accezar.github.io/notes/camadas-de-cache/"><em>Read the complete Portuguese article.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5feb8fff3685" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Query Cache to CDN: Reuse Across Client and Edge]]></title>
            <link>https://medium.com/@annacezar/from-query-cache-to-cdn-reuse-across-client-and-edge-2d7367283f3a?source=rss-e072c71722a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d7367283f3a</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[cdn]]></category>
            <dc:creator><![CDATA[Anna Carolina]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 17:42:20 GMT</pubDate>
            <atom:updated>2026-08-06T17:42:20.231Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3: How client state and shared web caches maintain independent identities, freshness windows, and invalidation rules.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TbkV-72DPmxpJmXrc7x9w.avif" /></figure><p>This is Part 3 of &quot;<strong><em>Caching Across the Modern Web Stack&quot;</em></strong>, a four-part series that follows cached representations from the browser, through client-side state and the CDN, to the Next.js application server. <a href="https://accezar.github.io/notes/camadas-de-cache/"><em>Read the complete PT-BR version here.</em></a></p><p><a href="https://medium.com/@annacezar/cache-identity-across-the-modern-web-stack-what-exactly-are-we-reusing-d135b4d9a0cf">Part 1 — Cache Identity Across the Modern Web Stack</a></p><p><a href="https://medium.com/@annacezar/browser-caching-http-cache-service-workers-and-cache-storage-409736a75402">Part 2 — Browser Caching</a></p><p>Once the browser has delivered an HTTP response and JavaScript has interpreted its body, the application starts working with a different representation. The serialized response becomes an object managed by application state, with its own key, timestamps, observers, and update rules. If that layer decides to fetch again, the request may still be answered by a edge cache before it reaches the application server.</p><h3>Query Cache and Client State</h3><p>After an HTTP response reaches the browser and JavaScript interprets its body, the application begins working with another representation. The JSON returned by /api/products/123, for example, becomes an object associated with the product and may be consumed by several parts of the interface.</p><p>State-management libraries organize these representations in a <strong>query cache</strong>. Each entry combines the returned data, the key identifying the query, its current state, the time of the last update, and the observers interested in that result. Some implementations also associate the <strong>in-flight</strong> operation with the entry, allowing multiple consumers to wait for the same read.</p><p>By default, the <strong>query cache</strong> lives in the JavaScript runtime’s memory, inside an instance maintained by the library. Reloading the page ends that instance; persistence strategies are discussed at the end of this section.</p><p>The key does not need to reproduce the URL used by the request. It describes the query in the application’s vocabulary:</p><pre>[&quot;product&quot;, &quot;123&quot;, { currency: &quot;BRL&quot; }]</pre><p>Product, page, sorting, currency, region, and any other dimension that changes the result need to participate in this identity. An incomplete key may cause incompatible queries to reuse the same object. An excessively specific composition creates nearly unique entries and reduces sharing.</p><p>When several components observe the same key, they all access the same entry. If the query is already in progress, the library may share that operation instead of starting one request for every consumer. The cache therefore centralizes both the data and its update process without requiring every component to hold an independent copy.</p><h4>Freshness, Retention, and Updates</h4><p>Once created, an entry is governed by two separate intervals. The freshness window determines how long the data may be reused without another read. Retention controls how long an entry with no observers remains available before removal.</p><p>When the <strong><em>freshness</em></strong> period ends, the data becomes <strong><em>stale</em></strong> from the library’s perspective, but it does not disappear automatically. The interface may continue displaying the current object while another query runs in the background, replacing it only when a new result becomes available.</p><p>An entry may also lose all consumers without being deleted immediately. Keeping it for a while allows a return navigation to restore the previous state and decide, according to its age, whether it can be reused or whether another read should begin.</p><p>Both clocks belong to the <strong>application cache</strong>. They do not modify <strong>Cache-Control</strong>, Cache Storage entries, or the CDN’s TTL. When the query cache starts a new fetch, it has only initiated another read from the interface’s point of view; the request may still stop before reaching the API.</p><p>An entry can be <strong><em>stale</em></strong> for the library while the HTTP cache or CDN still holds a <strong><em>fresh</em></strong> response. In that case, the query cache performs a <strong>refetch</strong>, but the origin receives no request. The reverse can also happen: the API already has a recent version, while an open tab continues displaying an older object because its freshness window has not ended and no new network access has begun.</p><p><strong>The duration of that window needs to match the product’s tolerance for staleness.</strong> Editorial data, preferences, and catalog information do not necessarily change at the same rate as inventory, price, permissions, or the state of an operation in progress.</p><p>Besides the passage of time, client-side events may trigger another read: mounting an observer, returning focus to the window, reconnecting, periodic refresh, a manual action, or explicit invalidation. The exact behavior differs among libraries and configurations, but the principle remains the same: an existing entry may be reused immediately and updated later when some condition requires it. <a href="https://tanstack.com/query/latest/docs/framework/react/guides/important-defaults">TanStack Query — Important Defaults</a>; <a href="https://redux-toolkit.js.org/rtk-query/usage/cache-behavior">RTK Query — Cache Behavior</a></p><h4>Writes, Invalidation, and Reconciliation</h4><p>A write changes remote state, but the query cache does not automatically know every entry affected by that change. After editing a product, adding an item to the cart, or removing an address, the application needs to coordinate the mutation result with the reads already stored.</p><p>Invalidation normally indicates that an entry is no longer trustworthy. It does not have to remove the data at that moment; observed queries may continue showing the current value while another read fetches the confirmed state.</p><p>When the mutation response already includes the updated data, the application can write directly to the corresponding entry. This avoids another request, but it requires correctly identifying the affected keys and updating detail views, lists, counters, or aggregates that represent the same change.</p><p>An optimistic update anticipates the change before the server confirms it. The cache preserves the previous state, applies the expected result locally, and notifies the components. On success, the response is reconciled with the predicted value. If the operation fails, the previous state must be restored.</p><p>Lists and aggregates make that coordination more delicate. Changing a product may affect its detail page, search results, the cart, recommendations, and counters. Updating all those entries manually requires knowing the dependencies. Invalidating a broad set simplifies consistency, but causes more later reads.</p><p>Real applications usually combine the mechanisms: they update the points required for an immediate response and invalidate or refetch the data that must be confirmed by the authoritative source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bus6rVT4ICnAF4w_cCzgyQ.png" /><figcaption><em>Read and write flows coordinated by a query cache</em></figcaption></figure><h4>Persistence and Isolation</h4><p>Many libraries keep the query cache only in application memory. Without an additional persistence strategy, reloading the page ends that instance and discards its entries.</p><p>Some architectures persist part of the cache in IndexedDB, localStorage, or another local store to accelerate later startup or support offline behavior. Those mechanisms are only the storage substrate used to preserve the data; they do not replace the query cache’s policy. <a href="https://tanstack.com/query/latest/docs/framework/react/plugins/persistQueryClient">TanStack Query — Persisting Query Client</a></p><p>Extending the lifetime of entries also extends the application’s responsibilities. The format may change between releases, data may survive longer than expected, and information associated with one account may reappear after another person signs in on the same device.</p><p>A persisted cache must define expiration, format versioning, and user scope. Logout, account switching, and permission changes should clear or isolate entries that cannot cross those boundaries.</p><p>Local persistence does not turn sensitive data into protected content. Values stored in IndexedDB or localStorage are available to code running under the same origin, so both the content and retention period must be appropriate for that environment.</p><p>The query cache occupies a particular position among these layers. It may answer before any HTTP request exists, share reads among components, and keep the interface populated during an update. When it decides to consult remote state again, it depends on the transport layers already examined.</p><p>If no reusable representation ends the read on the client, the request continues across the network. The next layer expands the scope of sharing: one response can serve different users before reaching the application server.</p><h3>CDN and Shared Caching</h3><p>When the query cache needs a newer version and no local layer can reuse a response, the request leaves the device. Before reaching the application server, however, it may be answered by a CDN that keeps copies of the response at points of presence distributed across the network.</p><p>The defining property of this layer is scope. Entries stored in the browser belong to one client. A response stored by a CDN can serve requests from different users. Public pages, images, and JavaScript files no longer need to travel all the way to the application whenever a compatible, reusable representation exists at the edge.</p><p>This distribution is not a single global cache. A CDN stores copies at different points of presence, and each region may hold its own state for the same entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W4XASTCZ21dmRx0CaC04uQ.png" /><figcaption>Example of global distribution</figcaption></figure><p>A CDN may consult more than one caching tier before reaching the application. If a point of presence does not hold the entry, the request may continue to a regional cache or <strong>origin shield</strong>, which concentrates traffic from several regions and reduces pressure on the origin. <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/origin-shield.html">Amazon CloudFront — Origin Shield</a></p><p>In this context, a CDN cache miss means only that the closest node does not have the copy. The response may still be reused at another CDN tier without requiring a new render or a new call to application services.</p><h4>Distribution, Age, and Shared Policy</h4><p>A response exists independently across the CDN’s layers and locations. The first access in one region may populate the nearest cache, while another region still needs to consult an intermediate cache or the origin. The same URL may therefore produce a hit in one location and a miss in another.</p><p>The Age header exposes the calculated age of a representation inside shared caches:</p><pre>Age: 143</pre><p>That value estimates the time since the response was produced or validated at the origin. It does not show how long ago the data used to generate that response changed. HTML with Age: 20, for example, may still include an old price if the server rendered it from data that was already stale. <a href="https://www.rfc-editor.org/rfc/rfc9111.html">RFC 9111</a></p><p>Browser and CDN policies may also differ:</p><pre>Cache-Control: public, max-age=0, s-maxage=300</pre><p>Here the browser considers the response immediately stale, while the CDN may reuse it for five minutes. The client still starts a network request, but that request can end at the shared layer without reaching the application.</p><p>This is the central point of this stage: the query cache, the browser’s HTTP cache, and the CDN maintain independent freshness clocks. A new read in the client does not necessarily imply new work at the origin.</p><h4>Reusing Stale Responses</h4><p>The end of the freshness window does not require the CDN to discard the stored response immediately. When HTTP policy permits it, a stale representation may continue serving requests while a new version is fetched or while the origin is temporarily unavailable.</p><pre> Cache-Control: public,<br> max-age=0,<br> s-maxage=300,<br> stale-while-revalidate=60,<br> stale-if-error=86400</pre><p>In this example, the CDN may reuse the response normally for the 300 seconds defined by s-maxage. During the following 60 seconds, stale-while-revalidate permits the existing copy to be returned while another request refreshes the entry in the background. <a href="https://www.rfc-editor.org/rfc/rfc5861.html">RFC 5861</a></p><p>The refresh does not necessarily block the current response. One user may receive the previous representation while the CDN fetches another version for later requests. This preserves edge latency during the transition between two entries.</p><p>stale-if-errorcovers another condition. If the layer consulted by the CDN returns an error or remains unavailable, a stale copy may still be used for the configured interval. The mechanism improves continuity, but deliberately extends the time during which an older representation may circulate.</p><p>Whether that policy is appropriate depends on the content’s semantics. An institutional page, an image, or editorial copy may remain useful for some time. Account information, reserved availability, authorization, and operation confirmation require stricter limits.</p><p>Support and execution details vary among providers. Some CDNs apply their own conditions for background revalidation, error responses, and maximum retention. Headers must be checked against the infrastructure’s effective configuration.</p><h4>Concurrency During Expiration</h4><p>Expiration of a heavily accessed entry can concentrate equivalent requests in a short interval. Without coordination, every request would continue to the next layer and could repeatedly trigger the same query or response generation.</p><p>This pattern is known as a <strong>cache stampede</strong> or <strong>thundering herd</strong>. The problem is not one expiration by itself, but the multiplication of work when many requests find the same entry unavailable at once.</p><p>Shared caches may apply <strong>request collapsing</strong>. The first request begins fetching the new representation, while the following requests wait for the same result or receive the stale copy when policy allows it. Instead of forwarding several equivalent operations, the CDN keeps one fetch in progress for that key. <a href="https://www.fastly.com/documentation/guides/concepts/cache/request-collapsing/">Fastly — Request Collapsing</a></p><p>This grouping operates on requests that can share the same entry. It does not prevent different keys from expiring simultaneously and producing independent access to the origin. A catalog with thousands of pages populated at the same moment may still produce a wave of refreshes when all entries reach the same TTL.</p><p>Adding variation to expiration times, refreshing critical content in advance, and permitting controlled use of stale responses reduce that concentration. These decisions need to account for traffic volume, the cost of producing the response, and the amount of staleness the product accepts.</p><h4>Invalidation, Propagation, and Sharing Boundaries</h4><p>TTL naturally ends the reuse window. A <strong>purge</strong> brings that moment forward by removing or invalidating a CDN entry before it expires.</p><p>This is useful when a change must reach the edge earlier than planned, but it depends on correctly identifying every response affected. A product update may require invalidating its page, category listings that include it, and other representations derived from the same content.</p><p>Because the CDN distributes entries across regions and cache tiers, invalidation may take time to propagate. During that interval, one point in the network may use the updated version while another still holds the previous one. The architecture needs to treat this transition as part of its consistency model instead of assuming immediate global replacement.</p><p><a href="https://medium.com/@annacezar/d135b4d9a0cf">The dimensions discussed in Part 1</a> return here as distribution and invalidation cost. Language, region, currency, and commercial segments multiply legitimate entries. Cookies and identifiers that do not change the response only fragment the cache. Content associated with a session, account, or authorization should remain private or be excluded from shared storage.</p><p>CDN invalidation reaches only the copies maintained by that layer. It does not automatically remove data or results stored by the application server. Likewise, updating an internal framework cache does not guarantee that every representation already distributed by the CDN stops being used.</p><p>The CDN controls reuse of the HTTP response that has already been produced.</p><p>If no client or shared cache can serve the request, the application still does not necessarily need to repeat every computation. <strong>Part 4 moves inside Next.js</strong>, where functions, components, routes, and prerendered output can be reused before the HTTP response is created.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d7367283f3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Browser Caching: HTTP Cache, Service Workers, and Cache Storage]]></title>
            <link>https://medium.com/@annacezar/browser-caching-http-cache-service-workers-and-cache-storage-409736a75402?source=rss-e072c71722a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/409736a75402</guid>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Anna Carolina]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 16:12:35 GMT</pubDate>
            <atom:updated>2026-08-05T16:12:35.437Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2: Freshness, revalidation, versioned assets, and the application-controlled cache that lives alongside the browser’s HTTP cache.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1We8dBx0uXIoe80AZ30reg.png" /></figure><p><em>This is Part 2 of &quot;</em><strong><em>Caching Across the Modern Web Stack&quot;</em></strong><em>, a four-part series that follows cached representations from the browser, through client-side state and the CDN, to the Next.js application server. </em><a href="https://accezar.github.io/notes/camadas-de-cache/"><em>Read the complete PT-BR version here.</em></a></p><p>The previous <a href="https://medium.com/@annacezar/cache-identity-across-the-modern-web-stack-what-exactly-are-we-reusing-d135b4d9a0cf"><strong><em>Part 1 — Cache Identity Across the Modern Web Stack: What Exactly Are We Reusing?</em></strong></a> established how caches reconstruct request identity before reusing a stored representation. Once that identity is known, the browser still has to decide whether the response may be stored, how long it remains reusable, and how it should be replaced after it becomes stale.</p><h3>Browser Caching</h3><p>When a response reaches the browser, it may remain available for later requests through two distinct mechanisms. The HTTP cache is managed by the browser itself and reuses responses according to rules defined by the protocol. Cache Storage, by contrast, is controlled by the application and is commonly consulted by a Service Worker while intercepting requests.</p><p>Although both mechanisms reuse responses associated with requests, they do not store the same unit. The HTTP cache preserves responses and metadata under protocol rules. Cache Storage keeps Request and Response pairs accessible to application code, which must decide when each entry is used, updated, or removed.</p><h4>HTTP Cache: Freshness and Revalidation</h4><p>After receiving a response and locating a compatible entry, the browser must decide whether it may reuse that entry without contacting the network. A response remains <strong>fresh</strong> for the interval defined by its policy. Once that interval ends, it becomes <strong>stale</strong>. Stale does not mean that the entry is removed immediately; it means that reuse may require validation or a new response. <a href="https://www.rfc-editor.org/rfc/rfc9111.html">RFC 9111</a></p><p>The from memory cache and from disk cache labels shown in developer tools describe where the browser kept the entry. They do not represent different HTTP policies. Storage location is an internal browser decision influenced by resource size, memory pressure, access frequency, and the lifecycle of the process.</p><p>Reuse conditions are expressed primarily through Cache-Control. A JavaScript file whose URL includes a content hash can receive a long freshness window:</p><pre>Cache-Control: public, max-age=31536000, immutable</pre><pre>/_next/static/chunks/catalog.a81fd2.js</pre><p>While max-age remains valid, the browser may use the response without consulting the network. immutable reinforces that the file will not change during its lifetime. When the content changes, the build process publishes it at a different address. <a href="https://www.rfc-editor.org/rfc/rfc8246.html">RFC 8246</a></p><pre>/catalog.a81fd2.js → /catalog.b72c91.js</pre><p>The two versions become independent resources. The previous file remains valid for documents that still reference it, while newly published pages use the updated URL. This property allows long retention without requiring the browser to discover whether the bytes associated with the old address were replaced.</p><p>Hash-based versioning also affects deployment. A page opened before a new release may request an older chunk later, during navigation or a dynamic import(). If every previous artifact is removed immediately, otherwise valid sessions may fail when they try to load those chunks. A deployment must retain older artifacts for a period compatible with how long pages can remain open.</p><h4>Versioned Assets, On-Demand Loading, and Variants</h4><p>Code splitting changes when each file is requested. Instead of transferring all JavaScript on the first visit, the bundler emits chunks associated with routes, components, and dynamic import boundaries. Navigation, opening a modal, or an import() may request a file that was not needed earlier. On-demand loading reduces the initial JavaScript payload, but it makes the page depend on artifacts from that build for the rest of its lifetime. <a href="https://nextjs.org/docs/app/guides/lazy-loading">Next.js — Lazy Loading</a></p><p>The hash in the filename preserves that relationship. A document loaded before deployment continues to point to the previous chunks; a document published afterward points to the new ones. Late loading determines <strong>when</strong> the file is requested. The versioned URL determines <strong>which version</strong> is retrieved and allows it to receive a long cache lifetime.</p><p>Stylesheets extracted during the build follow the same principle when they are published under versioned names. JavaScript and CSS can remain stored for long periods because a change creates a different address instead of silently replacing the bytes associated with the previous URL. Next.js applies this policy to assets served from /_next/static/, which include a content hash and receive public, max-age=31536000, immutable. <a href="https://nextjs.org/docs/app/guides/cdn-caching">Next.js — CDN Caching</a></p><p>Fonts are HTTP responses as well. With next/font, files are fetched during the build and hosted with the application. Different families, weights, and subsets create different files and increase the number of transferred resources. Preload can bring forward a font required by the initial content, but it does not change the response’s validity: preload controls request priority, while caching remains governed by the URL and response headers. <a href="https://nextjs.org/docs/app/getting-started/fonts">Next.js — Font Optimization</a></p><p>Images require another form of identity. The same source file may produce different representations according to width, quality, and format:</p><p><strong><em>product.jpg</em></strong><br> → 640 px in WebP<br> → 1200 px in WebP<br> → 1200 px in AVIF</p><p>The browser selects a variant according to srcset, the available display space, and supported formats. An image optimizer may generate that response on demand and reuse it for later requests. Each combination produces its own bytes and must be distinguished by the key used by the optimization service or CDN. <a href="https://nextjs.org/docs/app/getting-started/images">Next.js — Image Optimization</a></p><p>Files placed directly in public/ have stable URLs. Because they can be replaced without changing the address, Next.js applies a conservative policy by default. When the application needs long retention for these resources, the filename should include a version or the infrastructure must explicitly control invalidation. <a href="https://nextjs.org/docs/app/api-reference/file-conventions/public-folder">Next.js — Public Folder</a></p><p>Updating the source image does not guarantee that every derived variant disappears immediately. If the change must arrive before expiration, the strategy needs to reach the entries produced by the optimizer or publish the updated image under another URL. The same principle applies to every intermediate transformation: caches store the representation that was produced, not the intention that its source should now be considered different.</p><p><strong>Preload</strong>, <strong>prefetch</strong>, and <strong>lazy loading</strong> are not additional caches. They determine when a request starts. Once it begins, the response still passes through the HTTP cache, Service Worker, and CDN under the rules already described.</p><p>Personalized content requires stricter rules:</p><pre>Cache-Control: private, no-cache</pre><p>private restricts storage to private caches. no-cache allows the response to be retained, but requires validation before it can be reused. When the representation must not remain stored by caches that follow the protocol, use:</p><pre>Cache-Control: no-store</pre><p>no-store does not replace authentication, authorization, or encryption. The directive controls cache retention; the other protections remain responsible for preventing unauthorized access to the resource.</p><p>A single response may also declare different policies for the browser and shared caches:</p><pre>Cache-Control: public, max-age=0, s-maxage=300</pre><p>In the private cache, max-age=0 makes the entry immediately stale, so it should not be reused without validation. s-maxage=300 allows a shared cache to consider the same response fresh for five minutes.</p><p>When a stale entry has a validator, the browser can check whether the stored version is still current without transferring the entire body again. The server may associate an ETag with the response:</p><pre>ETag: &quot;product-v42&quot;</pre><p>On the next request, the browser reports which version it holds:</p><pre>If-None-Match: &quot;product-v42&quot;</pre><p>If the content is still equivalent, the server or an intermediary responds:</p><pre>HTTP/1.1 304 Not Modified</pre><p>A 304 response does not include the body again. The browser reuses the stored bytes and updates the entry’s metadata. The transfer is avoided, although a request still travels to a layer capable of confirming the validator.</p><p>A strong ETag identifies a specific representation. The weak form, marked with W/, accepts semantic equivalence even when the bytes are not identical:</p><pre>ETag: &quot;product-v42&quot;<br>ETag: W/&quot;product-v42&quot;</pre><p>Validation can also use the date of the last modification:</p><pre>Last-Modified: Tue, 04 Aug 2026 12:00:00 GMT</pre><pre>If-Modified-Since: Tue, 04 Aug 2026 12:00:00 GMT</pre><p>Last-Modified depends on a reliable timestamp and offers less precision when several changes happen in quick succession. When the application needs tighter control over the representation version, an ETag is usually the better option because it does not depend on the clock.</p><p>Freshness and revalidation reduce different costs. While max-ageremains valid, the request can be avoided entirely. After that interval, ETag and Last-Modified allow the existing entry to be confirmed before another representation is transferred.</p><h4>Service Worker and Cache Storage</h4><p>A Service Worker is not storage by itself. It is an execution context separate from the page that can intercept requests within its scope. When it receives a fetch event, it may forward the operation, produce a response, or query Cache Storage. <a href="https://www.w3.org/TR/service-workers/">Service Workers</a></p><pre>self.addEventListener(&quot;fetch&quot;, (event) =&gt; {<br> if (event.request.method !== &quot;GET&quot;) return;<br> event.respondWith(resolveRequest(event.request));<br>});<br><br>async function resolveRequest(request) {<br> const cache = await caches.open(&quot;catalog-v1&quot;);<br> const cachedResponse = await cache.match(request);<br> <br> if (cachedResponse) {<br>  return cachedResponse;<br> }<br> <br> const networkResponse = await fetch(request);<br>  if (networkResponse.ok) {<br>    await cache.put(request, networkResponse.clone());<br>  }<br><br>  return networkResponse;<br>}</pre><p>In this example, the Service Worker intercepts only GET requests. It first looks for a matching response in the <strong><em>catalog-v1</em></strong> collection. When an entry exists, it returns the stored copy. Otherwise, it consults the network, stores a copy of the response, and delivers the original result to the page.</p><p>Cache Storage organizes Request and Response objects into named collections, allowing the application to retrieve a response associated with a particular request. Although the stored shape resembles what the HTTP cache holds, the reuse policy is different. The HTTP cache interprets directives such as max-age and no-cache, as well as validators, according to protocol rules. Cache Storage does not automatically apply a freshness policy. An entry remains available until application code replaces or removes it, or until the browser evicts it because of storage limits and space pressure. <a href="https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage">MDN — Cache Storage</a>; <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria">MDN — Storage quotas and eviction</a></p><p>A response stored there may contain:</p><pre>Cache-Control: max-age=60</pre><p>and still be returned after that interval if the Service Worker strategy does not check its age. The presence of the header does not automatically create an expiration policy inside Cache Storage.</p><p>This programmable control makes it possible to add behavior that the HTTP cache cannot provide on its own, including offline navigation, precaching of essential resources, fallback responses during failures, and recovery adapted to unstable networks. In exchange, the application assumes responsibility for deciding when an entry remains usable, how it is updated, and when it should be removed.</p><p>The best-known strategies describe the order between Cache Storage and the network. In <strong>cache-first</strong>, the local copy is checked first; the network participates when no suitable response exists. Versioned resources, fonts, and icons often fit this flow because a change publishes another URL.</p><p><strong>Network-first</strong> prioritizes the network and falls back to local storage after an error, during unavailability, or, depending on the implementation, after a timeout. It is useful for reads that should reflect frequent changes but still need to provide some behavior under unstable conditions.</p><p>In <strong>stale-while-revalidate</strong>, the existing entry is returned immediately while another request updates the cache in parallel. In this context, stale describes the strategy’s willingness to use the current copy before updating it; it does not mean that Cache Storage automatically applied the HTTP cache’s freshness semantics.</p><p><strong>Network-only</strong> ignores Cache Storage for that operation and forwards the request to the network. Reads that require current state, along with mutations such as authentication, payment, or order creation, should not be satisfied with an old response. Offline applications may queue certain writes and retry them later, but that is a separate policy with its own requirements for idempotency, ordering, and reconciliation.</p><p>These names do not complete the implementation. A real strategy must also define which methods and status codes may be stored, how long an entry remains valid, how failures are handled, and whether opaque or authenticated responses are eligible. Without those criteria, “cache-first” tells us only which attempt happens first.</p><p>The Service Worker lifecycle adds another dimension. When the browser finds a new version of the worker file, it installs that version, but the worker normally remains waiting while the previous version still controls open pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o47wlqlBHU9RSP9-gsm5Qw.png" /><figcaption><em>A simplified Service Worker lifecycle from registration to client control.</em></figcaption></figure><p>skipWaiting() allows the new worker to request activation without waiting for every previous client to close. After activation, clients.claim() can make it take control of pages that are already open within its scope. The combination accelerates adoption, but it can also cause an interface loaded with resources from the previous version to be governed by a different policy while it is still running.</p><p>That transition directly affects caching. HTML, JavaScript chunks, and Cache Storage entries may belong to different application versions. A new worker may expect to find <strong><em>catalog-v3</em></strong>, while an older tab still depends on files registered in <strong><em>catalog-v2</em></strong>.</p><p>Updating the Service Worker file does not automatically remove existing collections:</p><pre>catalog-v1<br>catalog-v2<br>catalog-v3 ← current</pre><p>Versioned names help identify which entries belong to each release. Cleanup usually happens during the activate event, when older collections can be removed. That deletion must account for pages that remain open and artifacts that are still requested on demand; immediately deleting every previous version can interrupt valid sessions.</p><p>There is also no automatic benefit in copying into Cache Storage everything that already receives long-lived caching through HTTP. A hash-addressed file can be reused by the HTTP cache and the CDN without introducing a second client-side retention policy. A Service Worker is justified when it adds a concrete capability such as offline operation, precaching, a controlled fallback, or recovery from failures.</p><p>The HTTP cache and Cache Storage may preserve responses related to the same request, but they follow different authorities. In the first, headers and validators determine freshness and revalidation. In the second, application code decides when an entry is used, updated, or discarded.</p><h4>Conclusion</h4><p>Once the response body is interpreted by JavaScript, the application starts managing another representation altogether: an in-memory object with its own identity, freshness window, observers, and invalidation rules. <strong>Part 3 moves from that query cache to the CDN, where reuse expands from one runtime to users across the network.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=409736a75402" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache Identity Across the Modern Web Stack: What Exactly Are We Reusing?]]></title>
            <link>https://medium.com/@annacezar/cache-identity-across-the-modern-web-stack-what-exactly-are-we-reusing-d135b4d9a0cf?source=rss-e072c71722a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d135b4d9a0cf</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Anna Carolina]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 16:12:07 GMT</pubDate>
            <atom:updated>2026-08-05T16:15:06.774Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1: Representations, cache entry identity, and how layers across the frontend stack decide whether a stored response can be reused.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZBvhMroe4O4o0Z0sy2Ckg.avif" /></figure><p><em>This is Part 1 of </em><strong><em>&quot;Caching Across Modern Web Stack&quot;, </em></strong><em>a four-part series following cached representations from the browser, through client-side state and the CDN, to the Next.js application server.</em><strong><em> </em></strong><em>You can also </em><a href="https://accezar.github.io/notes/camadas-de-cache/"><em>read the complete PT-BR version here.</em></a></p><p>When developers talk about caching, they often use the same word to describe mechanisms distributed across very different points in the architecture. In the browser, cache may refer to the mechanism defined by the HTTP protocol — the HTTP cache — or to a response intercepted by a Service Worker. We may also be talking about data retained on the client by a library such as TanStack Query. Once a request crosses the network, a CDN may serve a previously stored page representation before it ever reaches the application server. If the request still needs to proceed, a framework such as Next.js may reuse the results of functions, components, or routes while producing the response.</p><p>As this suggests, “cache” can mean many different things, and the decisions made at each layer follow independent cycles. Consider a price change for a product in a catalog: the new value may already be available from the API while the CDN continues serving previously generated HTML and an open browser tab retains the object it received several minutes earlier. This set of layers produces safe performance gains only <strong>when that lag remains within the limit accepted by the product</strong> and when representations intended for different scopes are not treated as equivalent.</p><p>This series follows that path from the browser to the application server. It focuses on four decisions that recur at every layer: <strong>which representation was stored, how it is identified, how long it may be reused, and how a later version takes its place</strong>.</p><h3>Representations Across Cache Layers</h3><p>Before following a request through the different layers, we need to separate a few concepts that are often mixed together. A <strong>resource</strong> is any content identified and accessed by the application, such as a JavaScript file, an image, an HTML document, or product data. An attempt to obtain it under a specific set of conditions forms a <strong>request</strong>. The <strong>response</strong> is the result of that attempt, composed of a status, headers, and, when applicable, a body. A <strong>representation</strong> is the concrete form that the resource takes when it is produced, delivered, or stored at a particular layer of the architecture.</p><p>In an e-commerce application, consider the following request:</p><pre>GET /api/products/123<br>Accept-Language: pt-BR</pre><p>The <strong>resource</strong> is the product identified by 123. The <strong>request</strong> specifies which resource is being requested and under which conditions, such as language, currency, region, or authentication. To fulfill it, the API may combine the product record and description stored in a catalog database with a price calculated by a separate service. Part of that result may also be temporarily available in a store such as Redis.</p><p>The operation may produce this <strong>response</strong>:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Cache-Control: public, max-age=0, s-maxage=300</pre><pre>{<br>  &quot;id&quot;: &quot;123&quot;,<br>  &quot;name&quot;: &quot;Tênis de corrida&quot;,<br>  &quot;price&quot;: 499.9,<br>  &quot;available&quot;: true<br>}</pre><p>The JSON body is a <strong>representation</strong> of that product’s data, produced for the conditions in the <strong>request</strong>. The same business entity — product 123 — may appear in other representations across the application: embedded in the page HTML, stored as part of an HTTP response in the CDN, or converted into a deserialized object in the browser by a state-management library such as TanStack Query, SWR, or RTK Query. These representations refer to the same product, but they have different formats, identities, and lifecycles.</p><h4>How the Layers Relate</h4><p>The request in the example may cross several layers, and the <strong>response</strong> it produces may be stored on the way back. The position of each representation depends on the architecture and the strategies defined for the application. Projects do not all use the same technologies or share the same requirements, so different types of <strong>resource</strong> may follow different paths.</p><p>The diagram below shows one possible path for an HTTP response, not a fixed flow that every resource in the application must follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-24U5FrNBid6bHEfhYzrQ.png" /><figcaption><em>A possible request path through local, shared, and server-side cache layers.</em></figcaption></figure><p>The general behavior remains the same: during a request, each mechanism checks whether it holds a representation capable of satisfying the current request. A <strong>cache hit</strong> ends the path at that point. If there is no compatible entry — a <strong>cache miss</strong> — the operation continues to the next layer. When a new response has to be produced, it travels back through the path and may be stored according to the rules of each cache.</p><p>To decide whether a compatible entry exists, each layer must reconstruct the identity of the current request and compare it with the entries it retains. The URL is usually the starting point, but it does not cover every case: the method, parameters, headers, language, region, cookies, and authentication may also change the representation that is produced.</p><p>The set of request attributes used to distinguish these representations forms the <strong>cache key.</strong></p><h3>The Identity of a Cache Entry</h3><p>Before reusing a response, a cache must determine whether the stored entry corresponds to the current request. That comparison depends on an identity formed by the method, the resource address, and the conditions that alter the representation being produced.</p><p>There is no single key shared by every layer. The browser’s HTTP cache and the CDN begin with the HTTP request; the query cache uses an identity defined by the application; Next.js distinguishes the results of functions, components, and routes. This section focuses on the identity of HTTP responses, which will be reused by the browser and CDN layers later in the series.</p><p>Consider two requests to the same route:</p><pre>GET /products?page=2&amp;sort=price</pre><pre>GET /products?page=2&amp;sort=rating</pre><p>The <strong><em>path</em></strong> is the same, but the <strong><em>sort</em></strong> parameter changes the order of the products. If both requests were treated as equivalent, the cache could return a response produced for a different sorting criterion.</p><p>As a mental model, the identity can be represented as:</p><pre>method + URI + relevant variants</pre><p>The concrete composition depends on the cache and its configuration, but the principle remains the same: two requests may share an entry only when every difference capable of changing the response has been considered.</p><h4>Method, URL, and Query Parameters</h4><p>In an HTTP cache, the method and URI form the basis of the identity. For reads performed with GET, the path and query parameters normally distinguish different representations:</p><pre>GET /products?category=shoes&amp;page=2<br><br>GET /products?category=shoes&amp;page=3</pre><p>In this case, category and page participate in the response and must remain visible to the cache. Not every parameter, however, changes the content being returned:</p><pre>GET /products?category=shoes&amp;utm_source=newsletter</pre><p>If the CDN considers the entire query string, every combination of <strong><em>utm_source</em></strong>, <strong><em>utm_campaign</em></strong>, and <strong><em>gclid</em></strong> may create a separate entry for the same page. The response remains equivalent, but the cache becomes fragmented across keys that are rarely reused.</p><p>The configuration may normalize the URL and separate functional parameters from those used only for tracking:</p><blockquote><em>Change the response:</em><br><strong>category, page, sort, currency</strong></blockquote><blockquote><em>Do not change the response:</em><br><strong>utm_source, utm_campaign, gclid</strong></blockquote><p>This normalization must follow the route’s contract. Ignoring <strong><em>currency=BRL</em></strong>, for example, would be incorrect if the currency changes the prices being displayed. Parameter order must also be handled consistently:</p><pre>/products?page=2&amp;sort=price<br>/products?sort=price&amp;page=2</pre><p>Both URLs may express the same query to the application. They will share the same entry only if the cache normalizes the order or if the infrastructure already treats the two combinations as equivalent.</p><p>The method is also part of the identity. A read performed with GET and a write performed with POST against the same path represent different operations. HTTP caches normally concentrate reuse on methods defined as safe by the protocol; responses to other methods require explicit support and rules.</p><h4>Variants of the Same Response</h4><p>Some differences are not present in the address. The same URL may produce distinct responses according to headers sent by the client:</p><pre>GET /products<br>Accept-Language: pt-BR<br>Accept-Encoding: br</pre><p>If language and compression change the representation, the server can declare that variation:</p><pre>Vary: Accept-Encoding, Accept-Language</pre><p>The entry no longer corresponds only to /products and instead has variants:</p><pre>/products + pt-BR + br<br>/products + pt-BR + gzip<br>/products + en-US + br</pre><p>The <strong><em>Vary</em></strong> header should include only the fields that actually affect the result. Using a high-cardinality field such as User-Agent can produce thousands of variants and reduce sharing. When the application needs to adapt the response to the device, a controlled classification is usually more predictable:</p><pre>device-class = mobile | tablet | desktop</pre><p>Region, currency, and commercial group may also alter the response. These dimensions must appear somewhere observable in the request or in the cache configuration:</p><pre>/br/products/123<br>/us/products/123<br><br>or:<br><br>/products/123?region=BR<br>/products/123?region=US</pre><p>Ignoring a relevant dimension may cause the cache to reuse a price, currency, language, or availability produced for a different context.</p><p><strong><em>Cookies</em></strong> require the same care. A request may carry several values:</p><pre>session=abc<br>theme=dark<br>experiment=B<br>analytics_id=xyz</pre><p>If only the <strong><em>experiment</em></strong> changes the content, using the entire <strong>Cookie</strong> header as part of the identity creates unnecessary variants for session, theme, and tracking. A more precise configuration extracts only the dimension that participates in the response:</p><pre>experiment=B</pre><p>The identity should reflect the conditions that alter the representation, not every piece of data that accompanies the request.</p><h4>Cardinality and the Limits of Sharing</h4><p>Every additional dimension multiplies the number of possible entries. A page that varies by language, region, currency, and commercial group may produce several legitimate representations for the same route.</p><p>That growth is necessary when the differences are real. The problem begins when the key includes values that do not alter the result or that turn each request into a unique variant.</p><p>Consider an authenticated page:</p><pre>GET /account<br>Cookie: session=user-a</pre><p>Storing the response only under /account would allow another session to reuse data belonging to the first user. Including the account identifier would prevent incorrect sharing, but it would create a unique entry for every user.</p><pre>/account + user-id</pre><p>The entry would be isolated, but it would offer almost no shared reuse. Responses of this kind normally remain in private caches or are excluded from shared storage.</p><p>The balance can be summarized as follows:</p><blockquote><em>Too few dimensions</em><br><strong>→ incompatible responses may share the same entry<br>→ incorrect content or leakage between contexts</strong></blockquote><blockquote><em>Too many dimensions</em><br><strong>→ many variants with little reuse<br>→ lower hit rate and more traffic to the origin</strong></blockquote><p>The correct key includes every difference that changes the response and excludes those that merely accompany the request.</p><h4>Conclusion</h4><p>With identity defined, the browser still has to decide whether the response may be stored, how long it remains reusable, and how it will be updated once it becomes stale. Those decisions belong to the HTTP cache and to the policies implemented with Service Workers and Cache Storage. <a href="https://medium.com/@annacezar/browser-caching-http-cache-service-workers-and-cache-storage-409736a75402"><strong>Part 2 follows that decision inside the browser.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d135b4d9a0cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to recover Cursor chat history after renaming or moving a project folder]]></title>
            <link>https://medium.com/@annacezar/how-to-recover-cursor-chat-history-after-renaming-or-moving-a-project-folder-23bc0b925b98?source=rss-e072c71722a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/23bc0b925b98</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[agentic-development]]></category>
            <dc:creator><![CDATA[Anna Carolina]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 17:04:45 GMT</pubDate>
            <atom:updated>2026-07-21T17:20:19.826Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to remap a Cursor workspace on macOS when a folder rename causes your local chats to disappear.</em></p><figure><img alt="A notebook with browser window opened on Cursor official webpage" src="https://cdn-images-1.medium.com/max/1024/1*FefaiyJo8Doc5rzkV-Cwsg.avif" /></figure><p><a href="https://accezar.github.io/notes/recuperando-historico-cursor-renomear-projetos/"><em>Read the Portuguese version here.</em></a></p><p>I recently renamed a Cursor project folder to match the project’s new name. When I reopened the project, my entire chat history was gone. <strong><em>**classic**</em></strong></p><p>These were not conversations I was willing to discard. They contained implementation plans, architectural decisions, bug investigations, code snippets, and a large amount of context accumulated during development. Some of that material existed only inside Cursor.</p><p>My first assumption was that the data had been deleted. After inspecting Cursor’s local files and SQLite databases, however, I found that the conversations were still on my computer. Cursor had simply stopped associating them with the project I had opened.</p><p>There are already community tools that can export, inspect, or migrate Cursor conversations, and for many people one of them will be the fastest option. I wanted to understand what Cursor was doing with the project path, which records linked a chat to a workspace, and <strong><em>why copying a workspace database restored a few tabs but not the complete history.</em></strong></p><p>This article documents that investigation, the limits of the recovery process, and the script I now use to remap chats whenever I rename or move a project on macOS. It is intended for anyone who would rather understand and audit the migration than rely on a tool without knowing what it changes.</p><blockquote><strong>Tested with:</strong> Cursor 3.12.x on macOS 26.6, July 2026. Cursor’s local storage format is undocumented and may differ in later builds.</blockquote><h3>What happens when a folder is renamed</h3><p>Cursor inherits the concept of per-workspace storage from VS Code. Each folder opened in the editor receives a directory under:</p><pre>~/Library/Application Support/Cursor/User/workspaceStorage/</pre><p>The structure looks roughly like this:</p><pre>Cursor/User/<br>├── globalStorage/<br>│   └── state.vscdb<br>└── workspaceStorage/<br>    ├── 13961fd3.../<br>    │   ├── workspace.json<br>    │   └── state.vscdb<br>    └── da3bc2a6.../<br>        ├── workspace.json<br>        └── state.vscdb</pre><p>Each directory name is a workspace identifier. The corresponding workspace.json file records the folder associated with that storage:</p><pre>{<br>  &quot;folder&quot;: &quot;file:///Users/you/Projects/project-a&quot;<br>}</pre><p>Cursor derives a workspace identity from the folder and its workspace context, but that identifier should not be treated as a hash that can be safely recomputed from the path alone. The same path may be associated with more than one local workspace identifier, and the IDs I inspected did not consistently match common hashes of the folder URI.</p><p>When a folder is moved or renamed, Cursor may create another workspace for the new location:</p><pre>/Projects/project-a<br>    → old workspace: 13961fd3...<br>/Projects/new-project-a<br>    → new workspace: da3bc2a6...</pre><h3>Where the conversations are stored</h3><p>In current versions of Cursor, two databases serve different purposes.</p><p>The database inside each workspace, located at workspaceStorage/&lt;id&gt;/state.vscdb, stores local state for that window: selected chats, open tabs, panels, layout information, and other UI references.</p><p>The global database, located at globalStorage/state.vscdb, stores the general conversation index and the data used to reconstruct those conversations. In Cursor 3.x, the association between a chat and its workspace was centralized in this database. The editor reads the headers, filters conversations by workspaceIdentifier, and then loads the corresponding content.</p><p>Depending on the Cursor version or the stage of an internal migration, this index may appear in two forms:</p><pre>ItemTable<br>└── composer.composerHeaders<br><br>or<br><br>composerHeaders<br>├── composerId<br>├── workspaceId<br>└── value</pre><p>In my installation, I found a normalized table named composerHeaders. We also need to check for the JSON-based format stored inside ItemTable, because it may still exist in different builds and migration states.</p><p>Message content is associated with keys such as:</p><pre>composerData:&lt;composerId&gt;<br>bubbleId:&lt;composerId&gt;:&lt;bubbleId&gt;<br>checkpointId:&lt;composerId&gt;:&lt;checkpointId&gt;<br>composer.content.&lt;hash&gt;</pre><p>In my case, those records were still intact. The problem was in the index: approximately 191 conversations still pointed to the old workspace identifier and the old folder path.</p><p>This also explains why, when I tried to copying only the old workspace’s state.vscdb I got a few tabs back but not the full history. The tabs came from the workspace’s local UI state, while the complete conversation list depended on the global index.</p><p>Cursor also keeps transcripts under:</p><pre>~/.cursor/projects/</pre><p>Those files are useful as auxiliary records, but copying only the transcripts does not guarantee that conversations will reappear in the interface. Cursor still depends on its databases and indexes to locate and group them.</p><h3>The limits of this procedure</h3><p>This process addresses a specific case:</p><ul><li>A local folder was renamed or moved.</li><li>Cursor created a new workspace for the new path.</li><li>Existing conversations still point to the old workspace.</li><li>The conversation data is still present in the global database.</li></ul><p>It should not be treated as a universal solution for every case of missing history. Recent Cursor versions include surfaces that may rely on different storage mechanisms. Sessions started from the Agents Window, Remote Control, cloud agents, or other workflows may not exist in the same local index.</p><p>There are also grouping bugs in which conversations are correctly stored in the database but appear under a ghost workspace. In some cases, changing the Agents sidebar grouping to <strong>Updated</strong> or <strong>Status</strong> is enough to make the history accessible without modifying any database.</p><p><strong>Before making any changes, take three precautions:</strong></p><ol><li>Close Cursor completely with Cmd+Q. From the terminal, you can request a normal shutdown with osascript -e &#39;quit app &quot;Cursor&quot;&#39;. Use forced process termination only as a last resort, after confirming that Cursor has not exited normally.</li><li>Back up the databases before modifying anything.</li><li>Confirm that the problem is actually caused by a changed workspace ID.</li></ol><h3>The recovery process</h3><p>The procedure I use now is straightforward.</p><p>First, I open the newly named folder in Cursor at least once. This causes Cursor to create the new directory inside workspaceStorage.</p><p>Then I close the application completely. Closing only the project window is not enough: Cursor processes may remain active and keep database connections open. Before modifying the SQLite files, I confirm that Cursor has exited and that no process from Cursor.app is still using them.</p><p>With Cursor closed, the script:</p><ol><li>Finds the old and new workspaces by reading their workspace.json files.</li><li>Creates backups of the databases, WAL files, and recovery copies.</li><li>Updates conversation headers that still point to the old workspace.</li><li>Replaces old paths inside workspaceIdentifier and trackedGitRepos.</li><li>Remaps auxiliary references for tabs and inline diffs.</li><li>Optionally transfers the old workspace’s local UI state to the new one.</li></ol><p>The conversation content itself is not rewritten. The script mainly changes the references Cursor uses to locate and group the chats.</p><h3>How to run it</h3><p>Save the script as:</p><pre>~/bin/cursor-remap-chats.py</pre><p>Optionally make it executable:</p><pre>chmod +x ~/bin/cursor-remap-chats.py</pre><p>Open the new folder in Cursor at least once, close Cursor with Cmd+Q, and run:</p><pre>python3 ~/bin/cursor-remap-chats.py \<br>  --old &quot;/Users/you/Projects/project-a&quot; \<br>  --new &quot;/Users/you/Projects/new-project-a&quot;</pre><p>To also restore open tabs and other workspace-local state:</p><pre>python3 ~/bin/cursor-remap-chats.py \<br>  --old &quot;/Users/you/Projects/project-a&quot; \<br>  --new &quot;/Users/you/Projects/new-project-a&quot; \<br>  --also-copy-workspace-state</pre><h3>How to confirm that it worked</h3><p>After running the script, open Cursor using the exact new path:</p><pre>cursor &quot;/Users/you/Projects/new-project-a&quot;</pre><p>Then inspect the complete chat-history list. Do not use only the open tabs as your criterion.</p><p>Tabs represent local window state and may return even when part of the global conversation index is still incorrect. The expected result is that the old conversations appear under the new workspace and can be opened normally.</p><p>If they do not appear:</p><ol><li>Check the script output and see how many headers were remapped.</li><li>Verify that the paths passed through --old and --new are correct.</li><li>Confirm that the new folder was opened in Cursor before the script was executed.</li><li>Change the Agents sidebar grouping to <strong>Updated</strong> or <strong>Status</strong>.</li><li>Confirm whether the conversation belongs to the local editor or to another Cursor surface.</li><li>Do not run the script repeatedly without first inspecting the backups and databases.</li></ol><p>If the script reports that no headers were found, stop. That usually means the problem does not match the case described in this article.</p><h3>Why the script copies the WAL and SHM files</h3><p>Cursor’s databases use SQLite’s write-ahead logging mode. Recent transactions may still exist in state.vscdb-wal before they are incorporated into the main state.vscdb file. The accompanying state.vscdb-shm file is a shared-memory index used while the WAL database is active and can normally be reconstructed by SQLite.</p><p>The timestamped raw backup preserves the main database, WAL, SHM, and any existing state.vscdb.backup for recovery and forensic completeness. The workspace-state transfer itself uses SQLite’s backup API, which creates a consistent logical snapshot of the database without requiring the WAL or SHM files to be copied into the destination.</p><p>This distinction matters: the auxiliary files are retained in the backup so that the original state is not lost, while the new workspace receives a clean and internally consistent SQLite database.</p><h3>Where the backups are stored</h3><p>The backups are created inside:</p><pre>~/Library/Application Support/Cursor/User/globalStorage/</pre><p>The directory name looks like this:</p><pre>_backup_chat_remap_20260721_142530/</pre><p>The script may also update Cursor’s existing state.vscdb.backup after the remapping is committed. This is separate from the timestamped backup created before any modification. The original backup file is preserved inside that timestamped directory first; the internal Cursor backup is then synchronized with the remapped database so that Cursor does not restore an older workspace association over the new one.</p><p>These files may include prompts, responses, local paths, filenames, hostnames, and other project context. Do not commit the backup directory to a public repository or share its contents without reviewing them first.</p><h3>How to roll back the changes</h3><p>If Cursor fails to open correctly, the conversations remain inconsistent, or the result is not what you expected, close Cursor completely before restoring any files.</p><p>Use the timestamped backup directory created by the script:</p><pre>~/Library/Application Support/Cursor/User/globalStorage/<br>└── _backup_chat_remap_&lt;timestamp&gt;/<br>    ├── globalStorage/<br>    ├── old_workspace/<br>    └── new_workspace/</pre><p>Restore the original files from the corresponding directories:</p><ul><li>restore the files from globalStorage/ to Cursor’s globalStorage/;</li><li>restore old_workspace/ to the old workspace directory;</li><li>restore new_workspace/ to the new workspace directory.</li></ul><p>Restore the main database together with the matching WAL and SHM files when they exist. Do not mix database files from before and after the remapping.</p><p>After restoring them, open Cursor again using the intended project path.</p><h3>Linux and Windows</h3><p>The underlying logic is the same on other operating systems, but the base directory changes.</p><p>On Linux:</p><pre>~/.config/Cursor/User/</pre><p>On Windows:</p><pre>%APPDATA%\Cursor\User\</pre><p>The process-detection logic must also be adapted. On macOS, the script uses pgrep. On Windows, it could use tasklist or a cross-platform library such as psutil.</p><p>The macOS and Linux paths described here also appear in community tools that inspect Cursor’s local databases.</p><h3>Conclusion</h3><p>Renaming a project folder should be an ordinary operation. In my case, it revealed that a meaningful part of my development process depended on an internal Cursor mechanism I did not know existed.</p><p>Similar recovery and migration tools already exist in the Cursor community, including cursor-chat-recovery and a Linux workspace-path migration script. The script below was written for the storage layout I inspected on macOS and takes a different approach: it discovers the workspace identifiers already recorded in workspace.json and remaps the relevant entries in Cursor’s global database, rather than attempting to calculate workspace hashes or only copying workspace databases.</p><h3>Full script</h3><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;Remap local Cursor chats after renaming or moving a project folder. <br>Usage, with Cursor completely closed:<br> <br> python3 cursor-remap-chats.py \<br>    --old /path/to/old-project \<br>    --new /path/to/new-project<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br>import argparse<br>import json<br>import shutil<br>import sqlite3<br>import subprocess<br>import sys<br>from datetime import datetime<br>from pathlib import Path<br>from urllib.parse import quote, unquote, urlparse<br>def die(message: str, code: int = 1) -&gt; None:<br>    print(f&quot;ERROR: {message}&quot;, file=sys.stderr)<br>    raise SystemExit(code)<br>def cursor_running() -&gt; bool:<br>    commands = (<br>        [&quot;pgrep&quot;, &quot;-x&quot;, &quot;Cursor&quot;],<br>        [&quot;pgrep&quot;, &quot;-f&quot;, &quot;Cursor.app/Contents/MacOS/Cursor&quot;],<br>    )<br>    for command in commands:<br>        try:<br>            if subprocess.check_output(command, text=True).strip():<br>                return True<br>        except (subprocess.CalledProcessError, FileNotFoundError):<br>            pass<br>    return False<br>def file_uri(path: str) -&gt; str:<br>    return &quot;file://&quot; + quote(path, safe=&quot;/&quot;)<br>def uri_to_path(value: str) -&gt; str | None:<br>    parsed = urlparse(value)<br>    if parsed.scheme != &quot;file&quot;:<br>        return None<br>    return unquote(parsed.path)<br>def find_workspace_id(<br>    workspace_storage: Path,<br>    folder_path: str,<br>) -&gt; str | None:<br>    target = str(Path(folder_path).expanduser().resolve())<br>    for workspace_json in workspace_storage.glob(&quot;*/workspace.json&quot;):<br>        try:<br>            data = json.loads(<br>                workspace_json.read_text(encoding=&quot;utf-8&quot;)<br>            )<br>        except (OSError, json.JSONDecodeError):<br>            continue<br>        value = data.get(&quot;folder&quot;) or data.get(&quot;workspace&quot;)<br>        if not isinstance(value, str):<br>            continue<br>        decoded = uri_to_path(value)<br>        if (<br>            decoded<br>            and str(Path(decoded).expanduser().resolve()) == target<br>        ):<br>            return workspace_json.parent.name<br>    return None<br>def rewrite_composer_value(<br>    raw: str,<br>    old_id: str,<br>    new_id: str,<br>    old_path: str,<br>    new_path: str,<br>) -&gt; str:<br>    old_uri = file_uri(old_path)<br>    new_uri = file_uri(new_path)<br>    try:<br>        data = json.loads(raw)<br>    except json.JSONDecodeError:<br>        return (<br>            raw.replace(old_id, new_id)<br>            .replace(old_uri, new_uri)<br>            .replace(old_path, new_path)<br>        )<br>    workspace = data.get(&quot;workspaceIdentifier&quot;)<br>    if isinstance(workspace, dict):<br>        workspace[&quot;id&quot;] = new_id<br>        uri = workspace.get(&quot;uri&quot;)<br>        if isinstance(uri, dict):<br>            uri[&quot;fsPath&quot;] = new_path<br>            uri[&quot;path&quot;] = new_path<br>            uri[&quot;external&quot;] = new_uri<br>    repos = data.get(&quot;trackedGitRepos&quot;)<br>    if isinstance(repos, list):<br>        for repo in repos:<br>            if (<br>                isinstance(repo, dict)<br>                and isinstance(repo.get(&quot;repoPath&quot;), str)<br>            ):<br>                repo[&quot;repoPath&quot;] = repo[&quot;repoPath&quot;].replace(<br>                    old_path,<br>                    new_path,<br>                )<br>    text = json.dumps(<br>        data,<br>        ensure_ascii=False,<br>        separators=(&quot;,&quot;, &quot;:&quot;),<br>    )<br>    return (<br>        text.replace(old_id, new_id)<br>        .replace(old_uri, new_uri)<br>        .replace(old_path, new_path)<br>    )<br>def table_exists(<br>    connection: sqlite3.Connection,<br>    table: str,<br>) -&gt; bool:<br>    row = connection.execute(<br>        &quot;&quot;&quot;<br>        SELECT 1<br>        FROM sqlite_master<br>        WHERE type=&#39;table&#39; AND name=?<br>        &quot;&quot;&quot;,<br>        (table,),<br>    ).fetchone()<br>    return row is not None<br>def backup_sqlite_files(<br>    source_dir: Path,<br>    destination_dir: Path,<br>) -&gt; None:<br>    destination_dir.mkdir(parents=True, exist_ok=True)<br>    names = (<br>        &quot;state.vscdb&quot;,<br>        &quot;state.vscdb-wal&quot;,<br>        &quot;state.vscdb-shm&quot;,<br>        &quot;state.vscdb.backup&quot;,<br>    )<br>    for name in names:<br>        source = source_dir / name<br>        if source.exists():<br>            shutil.copy2(<br>                source,<br>                destination_dir / name,<br>            )<br>def sqlite_backup(<br>    source: Path,<br>    destination: Path,<br>) -&gt; None:<br>    &quot;&quot;&quot;Create a consistent SQLite copy, including WAL content.&quot;&quot;&quot;<br>    with sqlite3.connect(source) as source_connection:<br>        with sqlite3.connect(destination) as destination_connection:<br>            source_connection.backup(destination_connection)<br>def remap_normalized_headers(<br>    connection: sqlite3.Connection,<br>    old_id: str,<br>    new_id: str,<br>    old_path: str,<br>    new_path: str,<br>    backup_dir: Path,<br>) -&gt; int:<br>    if not table_exists(connection, &quot;composerHeaders&quot;):<br>        return 0<br>    columns = {<br>        row[1]<br>        for row in connection.execute(<br>            &quot;PRAGMA table_info(composerHeaders)&quot;<br>        ).fetchall()<br>    }<br>    required = {<br>        &quot;composerId&quot;,<br>        &quot;workspaceId&quot;,<br>        &quot;value&quot;,<br>    }<br>    if not required.issubset(columns):<br>        print(<br>            &quot;  warning: composerHeaders exists, &quot;<br>            &quot;but its schema is not recognized&quot;<br>        )<br>        return 0<br>    rows = connection.execute(<br>        &quot;&quot;&quot;<br>        SELECT composerId, value<br>        FROM composerHeaders<br>        WHERE workspaceId=?<br>        &quot;&quot;&quot;,<br>        (old_id,),<br>    ).fetchall()<br>    backup_file = (<br>        backup_dir<br>        / &quot;composerHeaders_old_workspace.json&quot;<br>    )<br>    backup_file.write_text(<br>        json.dumps(<br>            [<br>                {<br>                    &quot;composerId&quot;: composer_id,<br>                    &quot;value&quot;: value,<br>                }<br>                for composer_id, value in rows<br>            ],<br>            ensure_ascii=False,<br>        ),<br>        encoding=&quot;utf-8&quot;,<br>    )<br>    for composer_id, value in rows:<br>        connection.execute(<br>            &quot;&quot;&quot;<br>            UPDATE composerHeaders<br>            SET workspaceId=?, value=?<br>            WHERE composerId=?<br>            &quot;&quot;&quot;,<br>            (<br>                new_id,<br>                rewrite_composer_value(<br>                    value,<br>                    old_id,<br>                    new_id,<br>                    old_path,<br>                    new_path,<br>                ),<br>                composer_id,<br>            ),<br>        )<br>    return len(rows)<br>def remap_itemtable_headers(<br>    connection: sqlite3.Connection,<br>    old_id: str,<br>    new_id: str,<br>    old_path: str,<br>    new_path: str,<br>) -&gt; int:<br>    if not table_exists(connection, &quot;ItemTable&quot;):<br>        return 0<br>    row = connection.execute(<br>        &quot;&quot;&quot;<br>        SELECT value<br>        FROM ItemTable<br>        WHERE key=&#39;composer.composerHeaders&#39;<br>        &quot;&quot;&quot;<br>    ).fetchone()<br>    if not row:<br>        return 0<br>    try:<br>        headers = json.loads(row[0])<br>    except (TypeError, json.JSONDecodeError):<br>        return 0<br>    changed = 0<br>    new_uri = file_uri(new_path)<br>    for composer in headers.get(&quot;allComposers&quot;, []):<br>        if not isinstance(composer, dict):<br>            continue<br>        workspace = composer.get(&quot;workspaceIdentifier&quot;) or {}<br>        uri = workspace.get(&quot;uri&quot;) or {}<br>        fs_path = (<br>            uri.get(&quot;fsPath&quot;)<br>            or uri.get(&quot;path&quot;)<br>            or &quot;&quot;<br>        )<br>        belongs_to_old_workspace = (<br>            workspace.get(&quot;id&quot;) == old_id<br>            or old_path in fs_path<br>        )<br>        if not belongs_to_old_workspace:<br>            continue<br>        composer[&quot;workspaceIdentifier&quot;] = {<br>            &quot;id&quot;: new_id,<br>            &quot;uri&quot;: {<br>                &quot;$mid&quot;: 1,<br>                &quot;fsPath&quot;: new_path,<br>                &quot;external&quot;: new_uri,<br>                &quot;path&quot;: new_path,<br>                &quot;scheme&quot;: &quot;file&quot;,<br>            },<br>        }<br>        repos = composer.get(&quot;trackedGitRepos&quot;)<br>        if isinstance(repos, list):<br>            for repo in repos:<br>                if (<br>                    isinstance(repo, dict)<br>                    and isinstance(repo.get(&quot;repoPath&quot;), str)<br>                ):<br>                    repo[&quot;repoPath&quot;] = repo[&quot;repoPath&quot;].replace(<br>                        old_path,<br>                        new_path,<br>                    )<br>        changed += 1<br>    if changed:<br>        connection.execute(<br>            &quot;&quot;&quot;<br>            UPDATE ItemTable<br>            SET value=?<br>            WHERE key=&#39;composer.composerHeaders&#39;<br>            &quot;&quot;&quot;,<br>            (<br>                json.dumps(<br>                    headers,<br>                    ensure_ascii=False,<br>                    separators=(&quot;,&quot;, &quot;:&quot;),<br>                ),<br>            ),<br>        )<br>    return changed<br>def main() -&gt; int:<br>    parser = argparse.ArgumentParser(<br>        description=(<br>            &quot;Remap Cursor chats after renaming &quot;<br>            &quot;or moving a project folder&quot;<br>        )<br>    )<br>    parser.add_argument(<br>        &quot;--old&quot;,<br>        required=True,<br>        help=&quot;Absolute path of the old project folder&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--new&quot;,<br>        required=True,<br>        help=&quot;Absolute path of the new project folder&quot;,<br>    )<br>    parser.add_argument(<br>        &quot;--also-copy-workspace-state&quot;,<br>        action=&quot;store_true&quot;,<br>        help=(<br>            &quot;Copy the old workspace&#39;s local state &quot;<br>            &quot;to the new workspace&quot;<br>        ),<br>    )<br>    args = parser.parse_args()<br>    old_path = str(<br>        Path(args.old).expanduser().resolve()<br>    )<br>    new_path = str(<br>        Path(args.new).expanduser().resolve()<br>    )<br>    if cursor_running():<br>        die(<br>            &quot;Cursor is still running. &quot;<br>            &quot;Close it with Cmd+Q and run the script again.&quot;<br>        )<br>    support = (<br>        Path.home()<br>        / &quot;Library/Application Support/Cursor/User&quot;<br>    )<br>    workspace_storage = support / &quot;workspaceStorage&quot;<br>    global_storage = support / &quot;globalStorage&quot;<br>    global_db = global_storage / &quot;state.vscdb&quot;<br>    if not global_db.is_file():<br>        die(<br>            f&quot;Global database not found: {global_db}&quot;<br>        )<br>    old_id = find_workspace_id(<br>        workspace_storage,<br>        old_path,<br>    )<br>    new_id = find_workspace_id(<br>        workspace_storage,<br>        new_path,<br>    )<br>    if not old_id:<br>        die(<br>            &quot;No workspaceStorage entry was found &quot;<br>            f&quot;for the old path: {old_path}&quot;<br>        )<br>    if not new_id:<br>        die(<br>            &quot;No workspaceStorage entry was found &quot;<br>            f&quot;for the new path: {new_path}\n&quot;<br>            &quot;Open the new folder in Cursor once, &quot;<br>            &quot;close the application, and run the script again.&quot;<br>        )<br>    if old_id == new_id:<br>        die(<br>            &quot;The old and new paths point to the same &quot;<br>            &quot;workspace ID. There is nothing to remap.&quot;<br>        )<br>    print(<br>        f&quot;old: {old_path}\n&quot;<br>        f&quot;  workspace={old_id}&quot;<br>    )<br>    print(<br>        f&quot;new: {new_path}\n&quot;<br>        f&quot;  workspace={new_id}&quot;<br>    )<br>    stamp = datetime.now().strftime(<br>        &quot;%Y%m%d_%H%M%S&quot;<br>    )<br>    backup_dir = (<br>        global_storage<br>        / f&quot;_backup_chat_remap_{stamp}&quot;<br>    )<br>    backup_sqlite_files(<br>        global_storage,<br>        backup_dir / &quot;globalStorage&quot;,<br>    )<br>    old_workspace = workspace_storage / old_id<br>    new_workspace = workspace_storage / new_id<br>    backup_sqlite_files(<br>        old_workspace,<br>        backup_dir / &quot;old_workspace&quot;,<br>    )<br>    backup_sqlite_files(<br>        new_workspace,<br>        backup_dir / &quot;new_workspace&quot;,<br>    )<br>    if args.also_copy_workspace_state:<br>        old_state = old_workspace / &quot;state.vscdb&quot;<br>        new_state = new_workspace / &quot;state.vscdb&quot;<br>        if not old_state.is_file():<br>            die(<br>                &quot;The old workspace database &quot;<br>                f&quot;was not found: {old_state}&quot;<br>            )<br>        for suffix in (<br>            &quot;&quot;,<br>            &quot;-wal&quot;,<br>            &quot;-shm&quot;,<br>            &quot;.backup&quot;,<br>        ):<br>            target = Path(str(new_state) + suffix)<br>            if target.exists():<br>                target.unlink()<br>        sqlite_backup(<br>            old_state,<br>            new_state,<br>        )<br>        images = old_workspace / &quot;images&quot;<br>        if images.is_dir():<br>            destination = new_workspace / &quot;images&quot;<br>            destination.mkdir(exist_ok=True)<br>            shutil.copytree(<br>                images,<br>                destination,<br>                dirs_exist_ok=True,<br>            )<br>        print(<br>            &quot;→ copied workspace state &quot;<br>            &quot;(tabs and UI); preserved the new workspace.json&quot;<br>        )<br>    with sqlite3.connect(global_db) as connection:<br>        connection.execute(<br>            &quot;PRAGMA busy_timeout=5000&quot;<br>        )<br>        try:<br>            connection.execute(<br>                &quot;PRAGMA wal_checkpoint(TRUNCATE)&quot;<br>            )<br>        except sqlite3.Error as error:<br>            print(<br>                f&quot;  checkpoint warning: {error}&quot;<br>            )<br>        normalized = remap_normalized_headers(<br>            connection,<br>            old_id,<br>            new_id,<br>            old_path,<br>            new_path,<br>            backup_dir,<br>        )<br>        cached = remap_itemtable_headers(<br>            connection,<br>            old_id,<br>            new_id,<br>            old_path,<br>            new_path,<br>        )<br>        if table_exists(connection, &quot;ItemTable&quot;):<br>            old_glass = (<br>                &quot;cursor/glass.tabs.v2/&quot;<br>                f&quot;{old_id}/state.json&quot;<br>            )<br>            new_glass = (<br>                &quot;cursor/glass.tabs.v2/&quot;<br>                f&quot;{new_id}/state.json&quot;<br>            )<br>            old_glass_exists = connection.execute(<br>                &quot;&quot;&quot;<br>                SELECT 1<br>                FROM ItemTable<br>                WHERE key=?<br>                &quot;&quot;&quot;,<br>                (old_glass,),<br>            ).fetchone()<br>            if old_glass_exists:<br>                new_glass_exists = connection.execute(<br>                    &quot;&quot;&quot;<br>                    SELECT 1<br>                    FROM ItemTable<br>                    WHERE key=?<br>                    &quot;&quot;&quot;,<br>                    (new_glass,),<br>                ).fetchone()<br>                if new_glass_exists:<br>                    connection.execute(<br>                        &quot;&quot;&quot;<br>                        DELETE FROM ItemTable<br>                        WHERE key=?<br>                        &quot;&quot;&quot;,<br>                        (old_glass,),<br>                    )<br>                else:<br>                    connection.execute(<br>                        &quot;&quot;&quot;<br>                        UPDATE ItemTable<br>                        SET key=?<br>                        WHERE key=?<br>                        &quot;&quot;&quot;,<br>                        (<br>                            new_glass,<br>                            old_glass,<br>                        ),<br>                    )<br>                print(<br>                    &quot;→ remapped glass tabs&quot;<br>                )<br>        inline_diffs = 0<br>        if table_exists(connection, &quot;cursorDiskKV&quot;):<br>            rows = connection.execute(<br>                &quot;&quot;&quot;<br>                SELECT key<br>                FROM cursorDiskKV<br>                WHERE key LIKE ?<br>                &quot;&quot;&quot;,<br>                (<br>                    f&quot;inlineDiff:{old_id}:%&quot;,<br>                ),<br>            ).fetchall()<br>            for (key,) in rows:<br>                new_key = key.replace(<br>                    f&quot;inlineDiff:{old_id}:&quot;,<br>                    f&quot;inlineDiff:{new_id}:&quot;,<br>                    1,<br>                )<br>                already_exists = connection.execute(<br>                    &quot;&quot;&quot;<br>                    SELECT 1<br>                    FROM cursorDiskKV<br>                    WHERE key=?<br>                    &quot;&quot;&quot;,<br>                    (new_key,),<br>                ).fetchone()<br>                if already_exists:<br>                    connection.execute(<br>                        &quot;&quot;&quot;<br>                        DELETE FROM cursorDiskKV<br>                        WHERE key=?<br>                        &quot;&quot;&quot;,<br>                        (key,),<br>                    )<br>                else:<br>                    connection.execute(<br>                        &quot;&quot;&quot;<br>                        UPDATE cursorDiskKV<br>                        SET key=?<br>                        WHERE key=?<br>                        &quot;&quot;&quot;,<br>                        (<br>                            new_key,<br>                            key,<br>                        ),<br>                    )<br>            inline_diffs = len(rows)<br>        print(<br>            &quot;→ remapped normalized headers: &quot;<br>            f&quot;{normalized}&quot;<br>        )<br>        print(<br>            &quot;→ remapped composer.composerHeaders cache: &quot;<br>            f&quot;{cached}&quot;<br>        )<br>        print(<br>            &quot;→ remapped inlineDiff entries: &quot;<br>            f&quot;{inline_diffs}&quot;<br>        )<br>        if normalized == 0 and cached == 0:<br>            die(<br>                &quot;No chats associated with the old workspace &quot;<br>                &quot;were found. This may be a different case: &quot;<br>                &quot;an archived chat, an Agents Window session, &quot;<br>                &quot;a corrupted index, or a storage format that &quot;<br>                &quot;this script does not support.&quot;<br>            )<br>        connection.commit()<br>        try:<br>            connection.execute(<br>                &quot;PRAGMA wal_checkpoint(TRUNCATE)&quot;<br>            )<br>        except sqlite3.Error as error:<br>            print(<br>                &quot;  final checkpoint warning: &quot;<br>                f&quot;{error}&quot;<br>            )<br>    cursor_backup = (<br>        global_storage / &quot;state.vscdb.backup&quot;<br>    )<br>    if cursor_backup.exists():<br>        shutil.copy2(<br>            global_db,<br>            cursor_backup,<br>        )<br>        print(<br>            &quot;→ synchronized the existing &quot;<br>            &quot;state.vscdb.backup file&quot;<br>        )<br>    print()<br>    print(<br>        f&quot;Done. Backup created at: {backup_dir}&quot;<br>    )<br>    print(<br>        &quot;Open Cursor using this exact path: &quot;<br>        f&quot;{new_path}&quot;<br>    )<br>    print(<br>        &quot;Check the complete chat history &quot;<br>        &quot;and the open tabs.&quot;<br>    )<br>    return 0<br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><p><em>Hope it helps. 👋</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23bc0b925b98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Security: Mapping the Boundaries Between the Browser, CDN, and Backend]]></title>
            <link>https://medium.com/@annacezar/frontend-security-mapping-the-boundaries-between-the-browser-cdn-and-backend-341cd681fb6c?source=rss-e072c71722a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/341cd681fb6c</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Anna Carolina]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 18:32:03 GMT</pubDate>
            <atom:updated>2026-07-14T19:04:44.430Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical look at how security context breaks down across the browser, third-party scripts, caching layers, service workers, and backend authorization.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAjUhFcqs8ApJwajO3M7gw.avif" /></figure><p><a href="https://accezar.github.io/notes/seguranca-no-frontend/"><em>Read the Portuguese version here</em></a><em>.</em></p><p>Frontend applications now account for a meaningful part of a digital product’s security surface. Code running in the browser does more than render screens: it maintains state, executes scripts, communicates with other origins, and crosses authentication, caching, and authorization boundaries.</p><p>Security problems often emerge at the boundaries between these layers. Each layer reads a different part of the request, interprets fields according to its own rules, and frequently assumes that the previous layer has already validated the required security context. Failures rarely reside in a single form field or an isolated API endpoint. They tend to emerge at the boundaries between architectural components.</p><p>For example, when the browser trusts something the backend does not revalidate, the application may create paths to client-side bypasses, <a href="https://owasp.org/Top10/2021/A01_2021-Broken_Access_Control/">Broken Access Control</a>, <a href="https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html">IDOR</a>, or <a href="https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/">BOLA</a>. When a CDN reuses a sensitive response outside its intended context, the problem may surface as a caching error, a <a href="https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws">cache key composition flaw</a>, or <a href="https://portswigger.net/web-security/web-cache-deception">web cache deception</a>. When an external script receives too much authority, the risk of a <a href="https://cheatsheetseries.owasp.org/cheatsheets/Third_Party_JavaScript_Management_Cheat_Sheet.html">supply chain attack</a> or <a href="https://owasp.org/www-community/attacks/xss/">script injection</a> increases. And when the interface automatically treats data produced within the product as inherently trusted, it creates openings for <a href="https://portswigger.net/web-security/cross-site-scripting/stored">Stored XSS</a>, <a href="https://portswigger.net/web-security/cross-site-scripting/dom-based">DOM-based XSS</a>, or <a href="https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/03-Testing_for_HTML_Injection">HTML injection</a>.</p><p>In practice, I have seen these failures emerge from small, everyday decisions. For frontend engineers, security can easily become too abstract. Under pressure to simplify the product and ship quickly, teams often do not discuss these boundaries in enough depth. Frontend security should begin by mapping them and building a shared understanding of their responsibilities: where does the browser enforce rules? Where does the application delegate authority? Where must the backend revalidate the context?</p><h3>Browser</h3><p>For many people, the browser is simply where a web page is displayed. But it actively participates in the application’s security decisions. It determines which cookies accompany a request and when, whether a script may execute, and whether an external resource may be embedded. It also controls communication between documents and limits which APIs are available to each page or frame.</p><p>The first boundary the browser uses to organize these privileges is the <strong>origin</strong>. In browser terms, an origin is the combination of <em>scheme</em>, <em>host</em>, and <em>port</em>. For example, https://app.example.com and https://admin.example.com do not belong to the same origin. Neither do http://app.example.com and https://app.example.com. This separation establishes the browser’s basic privilege boundary.</p><p>The browser applies security policies to define these scopes. The Same-Origin Policy, for example, restricts how documents and scripts from one origin may access resources from another and establishes the default isolation between different origins. As a result, a page at https://app.example.com cannot freely read, inside the browser, a response from https://api.example.com.</p><p><strong>CORS</strong> — Cross-Origin Resource Sharing — allows that isolation to be relaxed by letting the server declare which origins may access a cross-origin response. The distinction is essential because <strong>CORS</strong> does not authorize the API operation; it only determines whether JavaScript from another origin may access the response body.</p><figure><img alt="Browser request lifecycle diagram showing external systems, browser security mechanisms, HTTP caching, service workers, code execution, state, and rendering." src="https://cdn-images-1.medium.com/max/1024/1*3kA70_YBAFh-JQBD96HB8Q.png" /><figcaption>A simplified illustration of a browser request flow, including the security mechanisms and layers involved.</figcaption></figure><h3>Cookies, SameSite, and CSRF</h3><p>Origin and site are not the same concept. https://app.example.com and https://api.example.com are different origins, but rules such as SameSite may treat them as the same site when they share the same scheme and registrable domain. This distinction matters because CORS may prevent a script from reading a response without preventing every way in which a cross-site request can be sent.</p><p>The server also defines part of the session security policy through attributes sent in the Set-Cookie header:</p><pre>Set-Cookie: session=...; Path=/; Secure; HttpOnly; SameSite=Lax</pre><p>In this cookie, Secure restricts transmission to HTTPS connections, HttpOnly prevents JavaScript from reading it, and SameSite limits the cross-site contexts in which the browser includes the credential. These attributes reduce the attack surface, but SameSite should be treated as an additional defense rather than complete protection against <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF"><strong>CSRF — Cross-Site Request Forgery</strong></a>.</p><p>Operations that change server-side application state may still require an anti-forgery token, validation of the Origin header, or the use of Fetch Metadata, depending on the flow. The boundary remains the same: the browser decides when to send the cookie; the backend decides whether the operation is valid in that context.</p><p>In applications that use iframes, popups, widgets, and microfrontends, the browser also mediates communication across domains, products, and teams. postMessage, window.opener, cookies, storage, and API permissions stop being implementation details and become entry points for exchanging data, changing state, and triggering authenticated actions. The recipient of a message must therefore validate its origin, shape, command type, and scope before changing state or calling an API.</p><h3>Third-Party Scripts</h3><p>Web applications execute both their own code and third-party code. Analytics, A/B testing tools, chats, maps, players, federated authentication, microfrontends — MFEs — and support tools may run in the same document or inside iframes with specific permissions. When a third-party script runs under the same origin as the application, it inherits part of the application’s authority: it can read the DOM, observe events, modify the page, and initiate requests.</p><p>The HttpOnly attribute prevents JavaScript from reading the session cookie, but it does not prevent the browser from including that cookie in requests to the application. A script running under the same origin therefore does not need to extract the token to act on the user’s behalf: it can call authenticated endpoints and take advantage of the session the browser already sends.</p><p>The reach of that code depends on where it executes. A script loaded into the main document can observe events, access the DOM, and modify the page; an isolated iframe operates under tighter restrictions; a service worker may intercept requests within its scope; and a microfrontend may, depending on the architecture, share session state, routing, storage, and event channels with the rest of the application.</p><p>Several controls can reduce this surface:</p><p><strong>CSP — Content Security Policy.</strong> Defines which scripts, styles, images, fonts, and other resources the browser may load and execute. With a nonce or hash, the page authorizes specific scripts instead of allowing any script delivered from a domain.</p><p><strong>Trusted Types.</strong> Requires sensitive browser APIs to receive values created through approved policies. This reduces the chance that an ordinary string will be inserted as HTML, script, or a browser-interpretable URL.</p><p><strong>SRI — Subresource Integrity.</strong> Makes the browser compare the hash of an external file with the hash declared by the page. If a file delivered by a CDN or another domain has been modified, the browser blocks it.</p><p><strong>Permissions-Policy.</strong> Controls which browser APIs may be used by the page and its iframes, including camera, microphone, geolocation, fullscreen, and sensors.</p><p><strong>COOP, COEP, and CORP.</strong> Cross-Origin Opener Policy, Cross-Origin Embedder Policy, and Cross-Origin Resource Policy reduce coupling between documents and resources from different origins. They help isolate pages, windows, iframes, and loaded resources when the application requires stricter separation.</p><p>These controls operate primarily when code is loaded and executed inside the browser. Dependencies incorporated into the bundle during the build cross a different boundary in the software construction and distribution process — the <a href="https://cheatsheetseries.owasp.org/cheatsheets/Software_Supply_Chain_Security_Cheat_Sheet.html"><strong>software supply chain</strong></a>. At that stage, lockfiles, dependency review, artifact provenance verification, package analysis, and pipeline protection must act before publication. SRI, for example, verifies the integrity of a file loaded at runtime; it does not validate a dependency that has already been bundled into the application’s JavaScript.</p><h3>XSS (Cross-Site Scripting)</h3><p>XSS occurs when content that should be treated only as text is instead interpreted by the browser as executable code or HTML markup. In modern applications, this risk appears mainly at points where dynamic content is incorporated, such as WYSIWYG editors, previews, embeds, innerHTML, srcdoc, server-side rendering with hydration, external widgets, and exceptions to the framework’s default escaping behavior.</p><p>Frameworks such as React, Angular, and Svelte escape text by default during rendering. For example, if a property such as comment.text contains &lt;b&gt;hello&lt;/b&gt;, the framework does not pass it to the browser as a &lt;b&gt; element. It renders the characters on the screen. The user sees something like &lt;b&gt;hello&lt;/b&gt;, rather than a bold word created from that text.</p><p>The risk appears when the component changes this relationship and <strong>passes a string to the browser to be interpreted as HTML</strong>. This often happens when the product needs to display external content such as a CMS block, a formatted comment, or an embed. At that point, the developer is no longer rendering text inside a paragraph and is instead rendering HTML inside the page. The browser then creates elements, attributes, and DOM relationships based on that string.</p><p>In React, dangerouslySetInnerHTML writes raw HTML into the DOM. In Svelte, {@html ...} performs the same kind of insertion. In Angular, [innerHTML] goes through the framework’s sanitization process, but exceptions created through DomSanitizer, such as bypassSecurityTrustHtml, remove the value from the normal protection path. Angular’s own <a href="https://angular.dev/api/platform-browser/DomSanitizer"><strong>documentation</strong></a> recommends using these APIs carefully and sparingly.</p><p>A useful Angular example is <a href="https://github.com/angular/angular/security/advisories/GHSA-g93w-mfhg-p222"><strong>CVE-2026–32635</strong></a>, which involved sensitive attributes such as href and src combined with internationalization through i18n-&lt;attribute&gt;. In that case, the combination could bypass sanitization. The lesson is that even a framework with context-aware sanitization may contain special paths that change how a value reaches the DOM. In Svelte, <a href="https://github.com/sveltejs/svelte/security/advisories/GHSA-f7gr-6p89-r883"><strong>CVE-2026–27121</strong></a> affected server-side rendering (SSR). Versions up to 5.51.4 could include event properties in server-generated HTML when the application used attribute spreading.</p><p>A spread applies all properties of an object to an element at once. In &lt;article {...externalAttrs} /&gt;, for example, each key in externalAttrs may become an attribute on the element. If the object contains { class: &quot;card&quot;, title: &quot;Article&quot; }, the expected result is equivalent to &lt;article class=&quot;card&quot; title=&quot;Article&quot;&gt;.</p><p>The problem appeared when that object came from an external source and contained keys capable of changing the element’s behavior, such as href, src, style, srcdoc, or event properties. If externalAttrs contained { class: &quot;card&quot;, onmouseover: &quot;alert(&#39;XSS&#39;)&quot; }, for example, a vulnerable version could treat class and onmouseover in the same way, producing server-side HTML equivalent to &lt;article class=&quot;card&quot; onmouseover=&quot;alert(&#39;XSS&#39;)&quot;&gt;. In that process, onmouseover would stop being only an object property and become an event attribute in the page document, allowing the browser to execute the code stored in it.</p><p>In this scenario, the risk lies not only in the value assigned to a property, but also in the property name and how it is interpreted. A key can determine which attribute will be created and turn external data into active behavior in the document. Because this content is produced on the server, the HTML may reach the browser already containing dangerous code, before the application completes rendering or hydration. This case extends the discussion beyond {@html ...}: XSS may also appear when an application transforms an external object into multiple attributes without explicitly restricting which keys are allowed.</p><p>In summary, prevention starts by keeping text as text. When a product needs to render HTML, the code should make it explicit where that HTML originates, which component transforms the content, which tags and attributes are accepted, and which component receives the result. In the browser, <strong>Trusted Types</strong> reduces accidental string-based HTML creation at sensitive DOM sinks. <strong>CSP</strong> limits execution paths when a flaw reaches the browser. Neither replaces the primary decision: content coming from a user or external provider should not reach dangerouslySetInnerHTML, {@html ...}, [innerHTML], srcdoc, href, or src without a sanitization policy appropriate for that destination.</p><h3>HTTP Protocol</h3><p>HTTP defines the format of the messages exchanged between the browser, infrastructure, and backend. Each request carries a URL, a method, headers, cookies, and, in some cases, a body. For the browser, these fields determine how the request is assembled: which address is accessed, which action is performed, which cookies accompany the request, and which additional information is sent in the headers.</p><p>The same format also shapes how the response is interpreted later. A route such as /dashboard may return a public page to a visitor and an authenticated page to a signed-in user. The difference between those responses may depend on a cookie, tenant, language, or permission. If one layer uses only /dashboard to identify the response, it may treat responses produced in different contexts as equivalent. The problem occurs when the meaning carried by the request is lost as the response is stored or reused.</p><pre>GET /dashboard HTTP/1.1<br>Host: app.example.com<br>Cookie: session=user-a<br>Accept-Language: en-US</pre><p>In this example, the backend uses the session cookie to build the dashboard for user-a. If the CDN’s <strong>cache key</strong> considers only the /dashboard path, the response may be stored as though it were valid for every request to that route. A later request to /dashboard from another user could receive HTML generated for the previous session. The browser does not validate this semantic relationship. It receives the response and renders the content.</p><p>Several years ago, Omer Gil described a <a href="https://omergil.blogspot.com/2017/02/web-cache-deception-attack.html">web cache deception vulnerability in PayPal</a>. The same URL was classified differently by two layers. The server treated the request as an authenticated route and returned private content, while the caching layer interpreted the URL as a static resource and could store that response. The report illustrates how a private response may escape its intended scope when the backend and the <strong>cache key</strong> of an intermediary layer do not represent the route in the same way.</p><p>The same dependence on interpretation between layers appears in headers that represent the application’s public address. Host, X-Forwarded-Host, and X-Forwarded-Proto can influence the generation of redirects, callbacks, and links sent to the user. The Host header comes from the original HTTP request, while X-Forwarded-Host and X-Forwarded-Proto are commonly set by proxies, gateways, or CDNs to tell the backend which domain and protocol the user accessed before the request was forwarded internally.</p><pre>GET /login HTTP/1.1<br>Host: app.example.com<br>X-Forwarded-Host: attacker.example<br>X-Forwarded-Proto: https</pre><p>In the example above, the risk appears when the backend trusts these headers as though they had been defined by the infrastructure, even though they were passed through from the client’s request. If the application uses X-Forwarded-Host to construct a callback or redirect, it may generate a URL pointing to a domain supplied through that header. The same flow that should produce https://app.example.com/reset?... may instead produce <a href="https://attacker.example/reset?....">https://attacker.example/reset?....</a></p><p>The defense must be applied at the boundary between infrastructure and application. The CDN, proxy, or gateway should remove forwarding headers received from the client and replace them with values derived from the connection it actually received before calling the backend. The backend should not accept arbitrary hosts either: domains used in callbacks, redirects, and links sent to users should come from known configuration or an explicit allowlist defined in the application or infrastructure.</p><h3>Authorization and Identifiers</h3><p>Another boundary appears when the frontend sends resource IDs, such as the ID of an invoice, order, user, or organization. The interface may hide links, block routes, or remove buttons based on the user’s known permissions, but these controls only shape what the user can see and do in the interface. They do not prove that the authenticated user may access or modify the requested resource.</p><pre>GET /api/tenants/tenant-b/invoices/8472 HTTP/1.1<br>Host: api.example.com<br>Cookie: session=user-a</pre><p>In this example, the URL identifies both the tenant-b organization and invoice 8472. If the API trusts only those values, changing either one may allow the user to access an invoice that belongs to another organization.</p><p>Every endpoint that receives an ID from the frontend must therefore verify again who the authenticated user is, which organization they belong to, which resource they are trying to access, and whether they are allowed to perform that action. Random or hard-to-guess IDs make enumeration more difficult, but they do not replace <strong>authorization</strong> over the resource. This is the boundary between a rule applied in the interface and the prevention of Broken Access Control, IDOR, or <a href="https://owasp.org/API-Security/editions/2023/en/0xa1-broken-object-level-authorization/"><strong>BOLA</strong></a> in the backend.</p><p>After the backend authorizes the operation and produces the response, another decision must be preserved end to end: where may that content be stored? A page that varies according to the user’s session, permissions, or organization should not receive the same caching policy as a public page. When the response must not be stored, that restriction should be declared explicitly:</p><pre>Cache-Control: no-store</pre><p>The no-store directive tells private caches, such as the browser cache, and shared caches, such as a CDN, not to store the response. Combining it with private would be redundant.</p><p>The private directive is useful in a different scenario: when the response may remain in the user’s own cache but must not be reused by a CDN or another shared cache. If that content may remain stored in the browser but must be revalidated with the server before every reuse, one possible policy is:</p><pre>Cache-Control: private, no-cache</pre><p>When a response is cacheable, Vary helps the cache distinguish between different versions of the same content by indicating which request headers influenced the result. It does not, however, replace the decision to prevent authenticated content from being stored and shared by a CDN.</p><p>Private routes require an explicit bypass rule or directives compatible with the intended behavior, according to the <a href="https://www.rfc-editor.org/rfc/rfc9111.html"><strong>HTTP caching semantics</strong></a>. As with forwarding headers, the context that made a response private must be preserved all the way to the browser, without allowing it to be treated as public content or reused for other users.</p><h3>Service Worker</h3><p>A service worker is a script the browser registers for an application and starts when it needs to handle specific events, separately from the page and its rendering cycle. It may be terminated when idle and restarted when a new event occurs. Its role includes intercepting requests, responding with cached content, synchronizing data, and making the application more resilient when connections are unstable or unavailable.</p><p>Once registered and activated, the service worker operates within an origin and a specific scope. That scope determines which pages it can control. A worker registered at /app/ only affects pages below that path. A worker registered at / may reach most of the application. This difference matters because, when the worker intercepts a request, it becomes part of the path between the page and the network.</p><pre>self.addEventListener(&quot;fetch&quot;, (event) =&gt; {<br>  if (event.request.method !== &quot;GET&quot;) return;<br><br>  event.respondWith(<br>    caches.open(&quot;runtime&quot;).then(async (cache) =&gt; {<br>      const cached = await cache.match(event.request);<br>      if (cached) return cached;<br><br>      const response = await fetch(event.request);<br>      await cache.put(event.request, response.clone());<br><br>      return response;<br>    })<br>  );<br>});</pre><p>This example registers a handler for the fetch event. Whenever a page controlled by the service worker makes a GET request, the worker looks for a matching response in Cache Storage. If it finds one, it returns the stored response. Otherwise, it sends the request to the network, stores a copy of the response, and returns it to the page.</p><p>This implementation looks convenient, but it treats every GET request as cacheable. An asset, a public page, and a response from /api/me all follow the same path. Cache Storage stores request-response pairs; it does not independently determine whether a response depends on session state, authorization, or tenant context. That classification must be explicit in the worker’s code.</p><p><a href="https://nvd.nist.gov/vuln/detail/CVE-2024-1554"><strong>CVE-2024–1554</strong></a> in Firefox illustrates the risk of a cache key that does not fully represent the request context. In that case, requests made through fetch() and navigation between pages could share the same cache entry because certain optional fetch() headers did not participate in cache key composition. The result was a form of local cache poisoning: an attacker could prepare a response for a given URL and, during a later visit to that URL, cause the browser to reuse that response instead of the correct one.</p><p>A <a href="https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Guides/Caching">service worker caching strategy</a> is not the same as HTTP caching. In HTTP caching, the browser and intermediary caches follow headers such as Cache-Control and Vary. In a service worker, application code decides whether a request goes through the cache, the network, or a combination of both. <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching">MDN</a> describes strategies such as cache first, where the worker checks the cache before the network, and network first, where it tries the network first and uses the cache as a fallback.</p><p>The worker’s update cycle is also part of this security surface. An older version may remain active until a new one is installed, activated, and begins controlling open pages. If a fix changes caching rules, routes, or session handling, the new version must remove old caches during the activate event and take control of clients in a coordinated way. Otherwise, a rule already fixed in code may continue to produce effects through caches created by the previous version.</p><h3>CDN</h3><p>A CDN is an external infrastructure layer that sits between the browser and the application and makes decisions before a request reaches the backend. Depending on its configuration, it may respond directly to the request, modify headers, apply rewrites, or execute functions within its own infrastructure.</p><p>The first concern is to classify traffic according to the actual behavior of each route, rather than only by the shape of its URL. That separation must be represented in the CDN rules:</p><pre>/assets/app.8f31a.js     → versioned asset<br>/pricing                 → public page<br>/dashboard               → authenticated page<br>/api/me                  → per-user response</pre><p>A broad rule such as <em>“cache everything ending in </em><em>.css or </em><em>.js”</em> may misclassify a request. Likewise, a rule based only on prefixes may continue to affect routes whose behavior changed after a product update. Because the CDN makes decisions before the origin, its configuration must evolve alongside architectural changes and application versions.</p><p>Rewrites and functions executed by the CDN require the same care. If a CDN rule changes the path, headers, cookies, or origin, the backend receives a request different from the one originally sent by the browser. These transformations must be captured in observability systems because they affect routing, authentication, and authorization.</p><p>A public incident that demonstrates the reach of this layer occurred at <a href="https://blog.cloudflare.com/incident-report-on-memory-leak-caused-by-cloudflare-parser-bug/">Cloudflare</a>. It was caused by a bug in the HTML parser used by features such as Email Obfuscation, Server-side Excludes, and Automatic HTTPS Rewrites. In certain HTTP responses, the company’s servers returned fragments of memory that could contain cookies, authentication tokens, POST request bodies, and other sensitive data.</p><p>Some of this content was stored by the normal crawling and caching mechanisms of search engines, extending the exposure even after the CDN-side flaw had been stopped. The incident response also required locating and removing copies that had already been distributed.</p><p>Invalidation is the other side of this control. If a page changes from public to authenticated, a caching rule is corrected, or a sensitive response is stored by mistake, publishing a new frontend version does not automatically remove content already distributed by the CDN. Invalidation must accompany the change.</p><p>Directives such as stale-while-revalidate, stale-if-error, or equivalent provider settings must also be applied according to the route. They may be appropriate for public routes and assets, but they intentionally extend response reuse and do not replace invalidation. The CDN configuration should make it explicit which routes may be served from the edge, for how long, and under which conditions.</p><h3>Conclusion</h3><p>In summary, the security of a web application depends on consistency across the browser, HTTP, CDN, BFF, and APIs. Each boundary must define what it accepts, transforms, stores, and revalidates.</p><p>The role of frontend architecture is to trace data across this path: understand where it comes from, who may access it, which transformations it undergoes, where it remains stored, which browser policies apply to it, and which layer has the authority to decide the next action. When designing an application, a frontend engineer must look beyond interface flows and understand how each component participates in these security decisions.</p><p>A sound frontend architecture can answer questions such as:</p><ul><li>Which origins may open, embed, read, or send messages to the application?</li><li>Which scripts execute under the same origin as the product?</li><li>Which data remains in cookies, in-memory state, sessionStorage, localStorage, IndexedDB, and Cache Storage?</li><li>Which headers are sent by the client, and which are defined by the infrastructure?</li><li>Which routes vary by session, authorization, tenant, language, or feature flag?</li><li>Which state-changing operations use session cookies, and how does the backend validate the request context?</li><li>Which APIs receive identifiers from the frontend?</li><li>Where are the user, resource, action, and tenant revalidated?</li><li>Which components transform text into HTML, attributes, URLs, or other browser-interpretable content?</li></ul><h3>TL;DR</h3><ul><li>The frontend participates in security because it executes code, maintains state, calls APIs, and composes resources from multiple origins.</li><li>The browser controls origins, cookies, CORS, CSP, storage, permissions, and communication between documents, but CORS and visual controls do not replace backend authorization or CSRF protection.</li><li>XSS appears when content that should remain text is interpreted as HTML, an attribute, a URL, or executable DOM behavior.</li><li>IDs, tenants, and other identifiers sent by the frontend must have their authorization revalidated in the backend for each user, resource, and action.</li><li>Service workers must explicitly classify what may be stored because Cache Storage does not independently understand session or authorization context.</li><li>HTTP and CDN layers must preserve response semantics: private content must not become shareable because of a caching error, header handling, or an edge rule.</li><li>A secure architecture makes it explicit where each piece of data enters, who transforms it, where it remains stored, and at which layer trust is revalidated.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=341cd681fb6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>