Skip to content

Unhandled QuotaExceededError in CookieStore.persist() can crash request handling #2750

Description

@sulthonzh

Description

CookieStore.persist() calls localStorage.setItem() without a try/catch. If the storage quota is exceeded (common in long-running test suites or CI), the unhandled exception propagates up through storeResponseCookieshandleRequest, crashing the entire request handling pipeline.

Context

  • File: src/core/utils/cookieStore.ts:82-95
  • Component: Cookie persistence in browser environments

Current Behavior

private persist(): void {
  if (
    typeof localStorage === "undefined" ||
    typeof localStorage.setItem !== "function"
  ) {
    return
  }

  // ... build data array ...

  localStorage.setItem(this.#storageKey, JSON.stringify(data)) // Can throw QuotaExceededError
}

When localStorage is full, setItem throws a DOMException with QuotaExceededError. This is not caught, so it bubbles up through:

  1. cookieStore.setCookie() → calls this.persist()
  2. storeResponseCookies() → calls cookieStore.setCookie()
  3. handleRequest() → calls storeResponseCookies()

This means a full localStorage kills all subsequent request handling.

Expected Behavior

Cookie persistence failure should be graceful — cookies should still work in-memory for the current session, and a console warning should be emitted.

Suggested Fix

  private persist(): void {
    if (
      typeof localStorage === "undefined" ||
      typeof localStorage.setItem !== "function"
    ) {
      return
    }

    const data: Array<SerializedCookie> = []
    const { idx } = this.#memoryStore

    for (const domain in idx) {
      for (const path in idx[domain]) {
        for (const key in idx[domain][path]) {
          data.push(idx[domain][path][key].toJSON())
        }
      }
    }

-   localStorage.setItem(this.#storageKey, JSON.stringify(data))
+   try {
+     localStorage.setItem(this.#storageKey, JSON.stringify(data))
+   } catch (error) {
+     // Gracefully handle storage quota errors.
+     // Cookies remain available in-memory for this session.
+     console.warn(
+       \`[msw] Failed to persist cookies to localStorage: \${error}\`
+     )
+   }
  }

Impact

  • Severity: Medium — Affects long-running browser test suites where localStorage fills up over many test runs
  • Current workaround: manually clear localStorage between tests, but this defeats the purpose of cookie persistence

Environment

  • Browser environments with limited localStorage (~5MB)
  • Long-running test suites with many cookie-heavy scenarios

Positively — happy to submit a PR if this is welcome.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions