Skip to content
jshacks.dev
Browser

The Storage Access API and Third-Party Cookies

How the Storage Access API lets embedded iframes request cookie and storage access: hasStorageAccess, requestStorageAccess, prompts and browser differences.

8 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the Google Chrome, JSON Web Tokens, OpenSSL and Let's Encrypt logos.

A page you visit can embed content from another site: a video player, a comment widget, a payment form, a map or a sign-in frame. When that embedded content runs in an iframe, it is a third party, and what it can store and read depends on the browser's privacy rules. Safari blocks third-party cookies by default and Firefox partitions them, and Chrome has changed its plans several times, keeping third-party cookies available with user controls rather than removing them for everyone. Whatever the default, the direction is the same: a site embedded as a third party is increasingly cut off from the cookies and storage it uses when visited directly as a first party. A comment widget that remembers who you are, or a payments frame that knows your saved cards, breaks. The Storage Access API is the standard way for such embedded content to ask for the access it needs, with the user's involvement. This post explains how the Storage Access API works: what it unlocks and why, document.hasStorageAccess() and document.requestStorageAccess(), the requirements around user interaction and prior first-party use, how permission prompts and grants behave, the newer requestStorageAccess({ all: true }) style options and Sec-Fetch-Storage-Access, how it differs from partitioned cookies with CHIPS, and how to build a flow with a fallback. It is documented on MDN. It is supported in current Safari, Firefox and Chromium browsers, with differences in prompts and rules, so test in each.

What is blocked and what the API changes

In a third-party context, browsers can block or partition cookies, localStorage, sessionStorage, IndexedDB, the Cache API and other storage. Partitioned means the storage still works but is keyed by the top-level site, so the same iframe embedded on two sites sees two separate jars, and cannot recognize the user across them. That protects privacy and breaks "log in once and be recognized everywhere" designs.

The Storage Access API gives an embedded document a way to ask for unpartitioned access, the same cookies and storage it has as a first party. If granted, the iframe's requests carry its first-party cookies, and its storage APIs see the first-party data, until the grant ends. The embedder does not get access to the data, and the grant applies to that embedded site on that top-level site.

Checking for access

document.hasStorageAccess() returns a promise for a boolean that says whether the current document already has unpartitioned access.

check.jsJavaScript
async function hasAccess() {
  if (!document.hasStorageAccess) return true;

  try {
    return await document.hasStorageAccess();
  } catch {
    return false;
  }
}

hasAccess().then((granted) => console.log("storage access:", granted));
Text
storage access: false

The first line treats a browser without the API as "no restriction known", which is the right default, since a browser that lacks the API is usually one that does not block third-party storage. In a first-party context, the call resolves to true. In a third-party iframe, it resolves to false until access is granted, though some browsers return true when cookies are not blocked at all.

Requesting access

document.requestStorageAccess() asks for access, and returns a promise that resolves if granted and rejects if not. It must be called from a user gesture, such as a click inside the iframe, because the browser wants evidence that the user is engaging with the embedded content, and because a prompt may appear.

request.jsJavaScript
const button = document.querySelector("#sign-in");

button.addEventListener("click", async () => {
  try {
    await document.requestStorageAccess();
    console.log("access granted: reload with cookies");
    location.reload();
  } catch (error) {
    console.log("denied:", error.name);
  }
});
Text
access granted: reload with cookies

After a grant, requests from the frame include its first-party cookies, and so a reload or a fresh fetch() with credentials: "include" shows the signed-in state. A denial rejects with a NotAllowedError, and you should show a fallback, such as a link that opens the sign-in in a top-level window.

fallback.jsJavaScript
async function connect(button) {
  if (!document.requestStorageAccess) {
    return signIn();
  }

  if (await document.hasStorageAccess()) {
    return signIn();
  }

  try {
    await document.requestStorageAccess();
    return signIn();
  } catch {
    button.textContent = "Continue in a new window";
    button.onclick = () => window.open("/auth/popup", "_blank", "popup,width=480,height=640");
  }
}

function signIn() {
  console.log("signing in with first-party cookies");
}
Text
signing in with first-party cookies

The popup fallback is the standard escape route: a top-level window runs in a first-party context for the embedded site, can set cookies there and communicate the result back with postMessage().

When the browser grants it

The rules differ by browser, and they are the part to test. In Safari, the iframe's site must have been interacted with as a first party recently, meaning that the user visited it directly and did something there, and the request needs a user gesture in the frame. If so, Safari shows a prompt on the first request and remembers the choice. In Firefox, the request needs a gesture, and a prompt asks the user, with automatic grants for sites that the user has interacted with in some cases and after some number of previous grants. Chromium browsers show a prompt, and automatically grant access for sites within the same First-Party Set, and for sites where the embedded site is related, in some configurations. The consistent requirement in all of them is the user gesture. Calling requestStorageAccess() on load, with no click, is rejected without any prompt.

The iframe also needs the right permissions from the embedder. A sandboxed iframe needs the allow-storage-access-by-user-activation token in its sandbox attribute, along with allow-scripts and allow-same-origin, and the embedder can restrict the feature with the storage-access Permissions Policy.

embed.htmlHTML
<iframe
  src="https://widgets.example/comments"
  sandbox="allow-scripts allow-same-origin allow-storage-access-by-user-activation"
  allow="storage-access"
></iframe>
Text
(the embedded widget may request storage access after a click inside it)

The Permissions API

The storage-access permission can be queried, so the frame can know in advance whether a request will show a prompt, be granted silently or be denied.

permission.jsJavaScript
async function storageAccessState() {
  try {
    const status = await navigator.permissions.query({ name: "storage-access" });
    return status.state;
  } catch {
    return "unsupported";
  }
}

storageAccessState().then((state) => console.log(state));
Text
prompt

The values are granted, denied and prompt. Use it to tailor the interface: when the state is granted, call requestStorageAccess() straight away, with no extra button, since a grant does not require another gesture in browsers that remember it, though some still ask for one. Listen for the change event on the status object to react if the user changes the setting.

Access to storage beyond cookies

By default, a grant gives access to cookies and, in current implementations, to the iframe's unpartitioned storage through a handle. Chromium and the specification added document.requestStorageAccess({ localStorage: true, indexedDB: true }) forms and the requestStorageAccess() result that gives a StorageAccessHandle, from which the frame reads the unpartitioned localStorage, sessionStorage, indexedDB, caches and BroadcastChannel. Support for this is newer, so check the compatibility table before using it.

handle.jsJavaScript
async function openSharedStorage() {
  if (!document.requestStorageAccess) return null;

  try {
    const handle = await document.requestStorageAccess({ localStorage: true });
    return handle.localStorage;
  } catch {
    return null;
  }
}

openSharedStorage().then((storage) => {
  console.log(storage ? storage.getItem("theme") : "no access");
});
Text
light

The handle is a way of reaching the first-party storage without switching the whole frame over to unpartitioned mode.

Headers

For requests that happen before any script runs, such as the HTML document of the iframe itself, there is a header. The browser sends Sec-Fetch-Storage-Access with values none, inactive or active: inactive means the frame has permission to use unpartitioned cookies but has not activated it, and active means it did. A server can respond with Activate-Storage-Access: retry; allowed-origin="https://app.example" to ask the browser to activate access and repeat the request, and Activate-Storage-Access: load to activate it on this response, which lets a frame with a prior grant get its cookies on the first request, avoiding the flash of a signed-out state.

headers.txtText
Sec-Fetch-Storage-Access: inactive

Activate-Storage-Access: retry; allowed-origin="https://app.example"
Text
(the browser retries the request with unpartitioned cookies, if the permission is already granted)

This is for server-rendered embedded content that needs cookies on the first load. It is available in Chromium, and so it is an enhancement to a flow that must work without it.

Partitioned cookies as the alternative

Not every embedded widget needs a cross-site identity. A chat widget that remembers a conversation on one site, a payment frame that keeps a session for the current visit, or a map with preferences, can work with state that is isolated per top-level site. For those, partitioned cookies, with the Partitioned attribute known as CHIPS, give the embedded site a cookie that is keyed to the embedding site, and works without a prompt.

cookie.txtText
Set-Cookie: session=abc123; Secure; SameSite=None; Partitioned; Path=/
Text
(the cookie is available to this embedded site only when it is embedded by the same top-level site that set it)

Choose by need. If the embedded site must recognize the user across the sites that embed it, or must read the cookies the user has when they visit it directly, such as a signed-in session on the provider's own site, use the Storage Access API. If it only needs a per-embedder state, use partitioned cookies and the iframe's own partitioned storage, which needs no user interaction.

A complete flow

A sign-in widget for a service embedded in other sites would proceed like this: on load, check hasStorageAccess(). If it is true, fetch the signed-in state with credentials. If not, query the permission, and if the state is granted, call requestStorageAccess() immediately and continue. Otherwise render a "Sign in" button, and on click call requestStorageAccess(), and on success reload the frame's state. On failure, open a popup for the first-party login and listen for a postMessage that signals completion, then call requestStorageAccess() again from the next click. Show a clear explanation of what the request is for, because a browser prompt without context is more likely to be declined.

Testing

Test in each browser, with default privacy settings and with the settings that block third-party cookies, since behavior without a block is different. Use two domains, not two subdomains of the same site, because same-site frames are not third-party. Chromium's DevTools lets you simulate third-party cookie blocking in the Application panel, and Safari and Firefox have their own settings. Test the denied path as well as the granted one.

Pitfalls

Calling requestStorageAccess() without a user gesture. Forgetting the sandbox token for sandboxed frames. Assuming a grant lasts forever or applies on other sites. Testing with same-site domains. Ignoring the denied case. Not providing a first-party popup fallback. Relying on the API for cross-site tracking, which the browsers' policies are designed to prevent. And depending on the newer handle and header features without checking support.

Also inAPIs
Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.