You open an online store, drop sneakers into your cart, head to checkout, and change the size or remove the item. Then you hit the browser's Back button to return to the catalog. The page appears instantly without a flicker, yet the cart icon in the header still shows the old count. You open the DevTools Network tab, and it's empty. Not a single request went to the server.
This isn't a layout bug or a stuck proxy. The browser didn't reload the page at all. It pulled a ready-made snapshot from RAM using bfcache (Back/Forward Cache) and unfroze it along with the old JavaScript state. It's a powerful feature enabled by default in Chrome (since version 96), Firefox, and Safari, but it can trip up UI state, authentication, and analytics. Let's walk through how this cache works, why pages get evicted from it, and how to handle it properly based on the web.dev bfcache guide maintained by Chrome engineers Philip Walton and Barry Pollard.
A RAM Snapshot Instead of Another Network Trip
When a user leaves a page via a link, the browser normally destroys it to free memory. With bfcache, it skips destruction and pauses JavaScript execution instead. When the user hits Back or Forward, the page becomes visible again and code resumes right where it left off. People navigate browser history much more often on phones than on desktops, so mobile traffic sees the biggest gains.
Share of Back/Forward Navigations Among All Chrome Navigations
The chart shows how often users hit Back and Forward in everyday browsing. Without bfcache, every return triggers a fresh load cycle: the browser revalidates resources, parses HTML, and runs scripts again. With bfcache, the network stays untouched and mobile data isn't wasted.
It's easy to confuse bfcache with the regular HTTP cache, though they work very differently. The HTTP cache stores responses for individual network requests like images, styles, and scripts. On a real site, you can rarely assemble an entire page from the HTTP cache without hitting the server, and JavaScript still has to be parsed and executed from scratch. bfcache holds a complete in-memory snapshot of the page, including the DOM tree and the JavaScript heap (all live objects, variables, and app state). That's why a bfcache restore always beats even a tuned HTTP cache.
What happens to running timers and async code? If setTimeout() was ticking or a Promise was pending, the browser pauses almost all tasks in JavaScript queues while the tab sits in the cache. Once the user returns, timers and promises pick up again. For ordinary code animating elements or updating the local DOM, freezing is harmless. Trouble starts when code holds shared resources like an IndexedDB database, which we'll cover shortly.
Embedded iframe elements and single-page applications (SPAs) have their own rules. An iframe by itself doesn't enter bfcache: if you click links inside a frame and hit Back, the browser loads the previous frame URL normally. However, when the main page enters bfcache, embedded iframe elements freeze with it and restore in the exact same state. There's a catch here: if a script inside a third-party iframe uses something incompatible with bfcache, it can disqualify the entire parent page. To prevent that, isolate external frames with the sandbox attribute or a Permissions-Policy header.
SPAs follow different mechanics too. A client-side router updates the URL and re-renders components without reloading the document, so bfcache isn't involved in those soft navigations. But if a user leaves your SPA for an external site and then hits Back, bfcache restores the whole app from memory instantly—no need to re-download the bundle or re-run initialization.
How to Catch a Restore and Refresh a Stale Cart
Back to our online store. The user went to checkout, removed a couple of items, and hit Back. The catalog page woke up from bfcache with its old JavaScript heap, where the cart variable still holds the deleted items. To avoid showing phantom items, you need to catch the exact moment the page restores and sync the data.
Browsers provide two standard page transition events for this: pageshow and pagehide. The pageshow event fires in two cases: right after load on the initial visit, and every time the page is restored from bfcache. You tell them apart with the boolean event.persisted property. If it's true, the page came from bfcache.
// Refresh the cart if the page was restored from bfcache
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
refreshCart().catch(showCartError);
}
});
// Protect private data after logout on a shared computer
window.addEventListener('pageshow', (event) => {
const hasSession = document.cookie.match(/my-cookie/);
if (event.persisted && !hasSession) {
// Reloading clears the screen while preserving navigation history
location.reload();
}
});
The first handler fixes the stale UI on the spot by calling the cart API and pulling fresh numbers without a full reload. The second snippet closes a much bigger security hole. Picture a shared computer in an office or library: someone logs out of their account and closes the tab or leaves the page, and the next user hits Back. If the profile page was stored in bfcache, the browser will happily display private data from RAM. Checking the session cookie in pageshow and forcing location.reload() wipes the snapshot without breaking navigation history (unlike some redirect flows, though an explicit redirect to login can be safer for strict auth).
The same pattern helps publishers and media sites with ad banners. It's tempting to slap Cache-Control: no-store on pages so banners always refresh when a user hits Back. That disables bfcache and slows down your whole site. It's far better to leave the cache alone and refresh only the ad slots inside pageshow. Major ad libraries like Google Publisher Tag (GPT) even do this automatically on restore.
To track when a page leaves for the cache, attach a listener to pagehide. It also has event.persisted, though its meaning is subtler than in pageshow.
// Track when the user leaves the page
window.addEventListener('pagehide', (event) => {
if (event.persisted) {
console.log('The page might enter bfcache.');
} else {
console.log('The page is unloading and will be destroyed.');
}
});
If pagehide reports persisted: false, you can be sure the page will not enter bfcache. By contrast, persisted: true is an intent rather than a guarantee. The engine plans to save the snapshot in RAM, but it might still bail out on the next step due to low memory or a hidden blocker.
Chromium browsers also offer another pair of events from the Page Lifecycle API: freeze and resume. freeze fires right after pagehide (when persisted === true), and resume fires right before pageshow on restore. The difference is that freeze and resume fire both for bfcache and when the browser freezes a background tab to save CPU. If you only want to refresh stale data after any pause, resume works (keeping in mind Firefox and Safari don't support it). If you're measuring your actual bfcache hit rate, rely on pageshow with event.persisted.
Try the interactive model below to see how the cart, network requests, and event.persisted behave under different combinations of blockers and handlers.
Navigation Model: Cart, Blockers, and bfcache Behavior
With all checkboxes off, the return is instant, but the header shows the stale number. Turn on pageshow syncing, and the page still wakes up from RAM in fractions of a millisecond while the cart immediately pulls the latest count. Check any blocker, and the browser discards the snapshot and fetches the entire document over the network again.
Top Cache Killers: unload, beforeunload, and Cache-Control: no-store
Even if you handle pageshow properly, your page might never enter bfcache at all. The biggest culprit is an old acquaintance: the unload event. The web.dev rule here is uncompromising—never use unload.
The problem is historical. unload predates bfcache, and older sites assumed the page would always die after it and that the event would fire on every exit. Both assumptions are broken today. Desktop Chrome and Firefox simply disable bfcache for any page with an unload listener. Mobile Chrome and Safari still try to cache the page and just skip firing unload on exit, meaning your code never runs there. Firefox on all platforms (except iOS, which runs WebKit and behaves like Safari) marks pages with unload as ineligible for bfcache.
Still life with two signal toggle switches illustrating the replacement of deprecated unload with safe pagehide
The replacement is straightforward: move your logic to pagehide. It fires in every case unload used to cover, plus when a page enters bfcache. Chrome is moving toward deprecating unload altogether, and Lighthouse has a dedicated no-unload-listeners audit that flags these listeners even inside third-party widgets and trackers.
What if your own code is clean, but a legacy ad script or browser extension attaches unload to window and ruins your speed? Your server can block those registrations with the Permissions-Policy HTTP header.
# Block any scripts or extensions from registering unload listeners
Permissions-Policy: unload=()
That single response header blocks unload registration for the document and any embedded iframe elements. A third-party script or extension trying to attach it gets denied, and your page enters bfcache cleanly.
Its neighbor, beforeunload, is gentler. Modern browsers no longer kick a page out of bfcache just for using it, though it used to break caching and remains unreliable on mobile. Still, beforeunload has a legitimate job: stopping a user who filled out a long form from accidentally closing the tab. The trick is not to attach it permanently on load, but to add it only when unsaved edits exist and remove it as soon as changes are saved.
// Show the system warning about unsaved data
function beforeUnloadListener(event) {
event.preventDefault();
return (event.returnValue = 'Are you sure you want to exit?');
}
// Attach the listener only when the form has unsaved changes
onPageHasUnsavedChanges(() => {
window.addEventListener('beforeunload', beforeUnloadListener);
});
// Remove it as soon as everything is saved
onAllChangesSaved(() => {
window.removeEventListener('beforeunload', beforeUnloadListener);
});
While the user is just reading or after they hit Save, there is no beforeunload listener on window. The browser skips extra checks, and accidental-close protection only kicks in when needed.
The third common cache killer is Cache-Control: no-store. Servers usually send it on sensitive pages like bank statements or profile settings so the browser won't save the response in the HTTP cache. Historically, when no-store is on the HTML document itself (it doesn't affect images or scripts inside), browsers refuse to store the page in bfcache either. Chrome is gradually relaxing this for cases with no privacy risk, but it's safer not to guess: reserve Cache-Control: no-store strictly for pages that must never be cached anywhere.
What if a page is public, but its content changes often, like a news feed or product catalog? Use Cache-Control: no-cache or Cache-Control: max-age=0. They force the HTTP cache to revalidate freshness with the server without blocking bfcache. There is one subtlety: when a page restores from bfcache, the browser pulls it from RAM and bypasses the HTTP cache, so no-cache and max-age=0 are ignored at that moment. Usually that's a win—the snapshot lives briefly in memory and opens instantly. If prices or stock change every minute, just fetch a fresh JSON snippet in pageshow, just like we did for the cart.
Hidden Code Blockers: window.opener and Open Connections
Sometimes your code has neither unload nor no-store, yet the page still refuses to enter bfcache. Check two less obvious areas: cross-window links and active network or storage connections.
The first trap is a non-null window.opener reference. If one page opened another via window.open() or an old target="_blank" link without rel="noopener", the new tab keeps a direct reference to its parent window. Besides being a security risk, it stops the browser from safely freezing either tab: one of them might call a method or post a message to the other at any moment. Modern browsers apply noopener behavior to target="_blank" links by default, but if you intentionally open a child window with window.open() and talk to it via window.postMessage() or a direct window reference, both tabs drop out of bfcache.
The second trap involves APIs shared across multiple tabs on the same origin. As long as JavaScript only touches the local DOM, pausing it hurts nobody. Imagine your page opens an IndexedDB transaction or acquires a Web Locks lock, and the browser freezes it mid-flight. Every other open tab on your site would hang waiting for the database to unlock. To prevent deadlocks, browsers refuse to cache pages with open IndexedDB connections, in-flight fetch() or XMLHttpRequest calls, or active WebRTC and WebSocket connections.
With WebSocket, things recently shifted. Starting in Chrome 149, "Disconnect WebSockets on bfcache entry" is live (Safari already does something similar): when a page enters bfcache, the browser cleanly closes the active WebSocket, and on restore it fires error and close events so your normal reconnect logic brings the socket back up. In other browsers, an open WebSocket still blocks the cache, and IndexedDB and WebRTC remain blockers everywhere.
The most reliable cross-browser recipe is simple: close connections and observers in pagehide (or freeze) and reopen them in pageshow (or resume). Here is how that looks for IndexedDB:
let dbPromise;
function openDB() {
if (!dbPromise) {
dbPromise = new Promise((resolve, reject) => {
const req = indexedDB.open('my-db', 1);
req.onupgradeneeded = () => {
req.result.createObjectStore('keyval');
};
req.onerror = () => reject(req.error);
req.onsuccess = () => resolve(req.result);
});
}
return dbPromise;
}
// Close the connection when leaving the page
window.addEventListener('pagehide', () => {
if (dbPromise) {
dbPromise.then((db) => db.close());
dbPromise = null;
}
});
// Reopen on normal load and on bfcache restore
window.addEventListener('pageshow', () => openDB());
Notice the if (!dbPromise) guard inside openDB(). If you listen to multiple events (like pageshow, resume, and an automatic reconnect on close or error), it's easy to open two parallel connections to the same database or socket by accident. A simple flag or cached promise prevents duplicates.
Here is a cheat sheet of the main failure reasons so you can audit your project quickly.
| Blocker | Why It Breaks bfcache | How to Fix |
|---|---|---|
unload event listener | Desktop Chrome and Firefox disable cache; Safari and mobile Chrome skip firing the handler | Move logic to pagehide and block third-party scripts with Permissions-Policy: unload=() |
Unconditional beforeunload | Historically blocked cache and remains unreliable on mobile | Attach only when unsaved edits exist and remove right after saving |
Cache-Control: no-store on HTML | Restricts document caching for privacy reasons | Keep only for strictly private pages; use no-cache or max-age=0 plus pageshow refresh for public content |
window.opener references | Linked tabs can't be frozen safely without risking broken postMessage() calls | Use rel="noopener" and avoid direct window-to-window links when possible |
Open IndexedDB, Web Locks, WebRTC, active fetch/XHR | Freezing could lock out other tabs on the same origin | Close connections in pagehide / freeze and reopen in pageshow / resume |
Open WebSocket | Blocks cache in browsers other than Chrome 149+ and Safari | Close in pagehide and reconnect in pageshow (Chrome 149+ triggers standard reconnect on error/close) |
Once you clear these blockers, pages usually start hitting bfcache reliably. Next, you need to verify that nothing slipped through—neither in your code nor in third-party scripts.
How to Test in DevTools and Catch Failures on Real Users
Testing bfcache blindly by clicking Back and Forward by hand is slow and tells you little. Chrome already includes a built-in test bench: the Back/forward cache panel in Chrome DevTools. Open your page, go to Application -> Back/forward cache, and click Run Test. DevTools navigates to a blank page and back, checking whether your document restores from cache.
Back/forward cache panel in Chrome DevTools with the Run Test button (Source: web.dev)
If everything passes, you'll see a green Restored from back/forward cache status. If it fails, DevTools lists the exact reason and points to the frame causing trouble. The most useful entries carry an Actionable badge—these are issues you can fix directly in your code or headers, like a forgotten unload listener in the main frame.
Chrome DevTools report showing an Actionable bfcache failure caused by an unload handler (Source: web.dev)
For automated CI or pre-release checks, use Lighthouse: since version 10.0, it includes bf-cache and no-unload-listeners audits. They catch the same blockers, including cases where an ad script or chat widget sneaks in an unload listener.
Still, a local DevTools test only checks your browser and your flow. Real traffic brings browser extensions, odd form states, and third-party iframe elements. To see what happens in the field (RUM — Real User Monitoring), Chrome 123+ provides the NotRestoredReasons API. The notRestoredReasons property lives right on the navigation entry in PerformanceNavigationTiming (see the MDN documentation).
// Collect bfcache failure reasons from real users
const [navEntry] = performance.getEntriesByType('navigation');
if (navEntry?.notRestoredReasons) {
// Returns a frame tree with reasons, children, id, and name
console.log(navEntry.notRestoredReasons);
}
The API returns a tree with reasons, children, id, and name, showing whether the main document or a same-origin child frame blocked the cache. For privacy, the browser hides details of cross-origin iframe elements and only reports that an external frame blocked it. Watch out for one subtle trap: notRestoredReasons returning null does not mean the page came from bfcache. It's also null on a normal initial load. Always measure your true hit rate with pageshow and event.persisted.
If you don't want to build custom telemetry right away, check CrUX (the Chrome User Experience Report, a public dataset of real-world Chrome performance). It breaks down metrics by navigation type, including back_forward_cache, so you can see your domain's instant-restore share without writing a line of code.
Quick Pre-Launch Page Checklist
- Run the page through Chrome DevTools (
Application -> Back/forward cache -> Run Test) and verify there are noActionableerrors. - Check the Lighthouse
no-unload-listenersaudit and addPermissions-Policy: unload=()on the server if needed. - Add a
pageshowlistener checkingevent.persistedto refresh the cart, stock counts, and session cookie. - Switch
beforeunloadto conditional mode, attaching it only when the form has unsaved edits. - Close
IndexedDBandWebRTCconnections inpagehideand reopen them inpageshowwithout duplicates.
Once every item is green, pages pop back from RAM instantly. The surprises aren't over yet, though: right after launch, your analytics and speed dashboards might look strangely worse.
The Analytics Trap and the Core Web Vitals Paradox
Suppose you fixed everything and pages are flying into bfcache. A week later, you open your analytics dashboard and panic. Page views are down, while average load time and the 75th percentile crept up as if the site got slower. Relax: your site is faster, but your analytics and metrics fell into a statistical trap.
Let's start with page views. Popular analytics libraries fire page_view once when the script loads. When someone hits Back and the page restores from bfcache, the script doesn't re-run, so that visit isn't counted. In fact, you're probably already missing some views from Safari and Firefox. To count restores accurately and measure your bfcache hit rate, disable automatic page_view in Google Analytics (gtag) and send it manually with the navigation type.
// Disable automatic page_view so we can attach navigation_type
gtag('config', 'TAG_ID', { send_page_view: false });
const navEntry = performance.getEntriesByType('navigation')[0];
gtag('event', 'page_view', {
navigation_type: navEntry ? navEntry.type : 'navigate',
});
// Send a view on every bfcache restore
window.addEventListener('pageshow', (event) => {
if (event.persisted) {
gtag('event', 'page_view', {
navigation_type: 'back_forward_cache',
});
}
});
Comparing navigation_type: 'back_forward_cache' events against regular back_forward events gives you your real hit rate. Don't expect 100%, though—it's technically impossible. The browser won't restore from bfcache if the user restarted the browser, duplicated a tab, or reopened a closed tab (and some browsers still label those navigation.type values as back_forward). Older snapshots also get evicted from RAM over time. The goal of monitoring is simple: spot specific page templates where the hit rate is abnormally low due to code bugs.
Now for the main paradox: why loading-speed charts can look worse after enabling bfcache. It comes down to sample bias. Back and Forward navigations are repeat visits by definition. Before bfcache, they ran as full page loads with a warm HTTP cache, making them some of the fastest rows in your dataset. Once bfcache kicked in, those fast visits stopped triggering full loads and vanished from the report. What remained in the sample were mostly cold first visits with an empty cache—pushing the overall median and p75 up even though real users saw pages open instantly.
Vector graphic illustration of the Core Web Vitals statistical paradox when fast cache restores are excluded
The fix depends on which metric you're looking at. For server and technical metrics like TTFB (Time to First Byte), segment data by navigation.type: view navigate, reload, back_forward, and prerender separately. You'll see right away that the server didn't slow down; the traffic mix just changed. Don't confuse Navigation Timing's back_forward type with bfcache—Navigation Timing only records full page loads, whereas bfcache reuses an already loaded document.
For user-facing Core Web Vitals (LCP for main content rendering, INP for responsiveness, CLS for layout stability), bfcache restores should count as full visits. Users don't care whether a cache fired: they clicked Back and saw the screen immediately. CrUX already counts bfcache restores this way.
There are no separate browser APIs for measuring CWV after a cache restore, so tools approximate them using standard APIs:
- LCP is measured as the time between
pageshowand the next rendered frame (on abfcacherestore, the whole screen paints at once, so LCP equals FCP). - INP continues collecting via the same
PerformanceObserver, resetting its accumulated value to0on restore. - CLS likewise resets to
0onPerformanceObserverso old layout shifts don't penalize the new view.
You don't have to write that math from scratch: the official web-vitals library handles it out of the box. Inside its onLCP, onINP, and onCLS helpers, internal functions onBFCacheRestore and getBFCacheRestoreTime reset counters on pageshow and tag measurements with navigationType: 'back-forward-cache'. Upgrade to the latest version, and your field Core Web Vitals charts will finally reflect the speed users actually feel.



