Skip to content

fix: error handle cookie operation#2475

Merged
saikumarrs merged 3 commits into
developfrom
feature/sdk-3883-error-handle-cookie-access-during-initialisation
Sep 10, 2025
Merged

fix: error handle cookie operation#2475
saikumarrs merged 3 commits into
developfrom
feature/sdk-3883-error-handle-cookie-access-during-initialisation

Conversation

@saikumarrs

@saikumarrs saikumarrs commented Sep 10, 2025

Copy link
Copy Markdown
Member

PR Description

I have error handled the cookie test operations that are used to determine the top-level domain of the webpage. Without this fix, the SDK would not initialise properly in environments with security restrictions around cookie access.

Linear task (optional)

https://linear.app/rudderstack/issue/SDK-3883/error-handle-cookie-access-during-initialisation

Cross Browser Tests

Please confirm you have tested for the following browsers:

  • Chrome
  • Firefox
  • IE11

Sanity Suite

  • All sanity suite test cases pass locally

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

Summary by CodeRabbit

  • Bug Fixes
    • Improved robustness of cookie handling across domain levels by safely recovering from intermittent errors.
    • Reduced sporadic failures when setting or checking cookies, resulting in more reliable domain resolution.
    • Added best-effort cleanup on failures to lower residual cookie artifacts.
    • Enhanced cross-browser and environment compatibility to reduce tracking interruptions and configuration flakes.

@saikumarrs saikumarrs self-assigned this Sep 10, 2025
@coderabbitai

coderabbitai Bot commented Sep 10, 2025

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Top-level cookie-setting attempts are now wrapped in try/catch: each domain try sets a cookie, checks it, clears the cookie and returns the domain on success; exceptions are swallowed and the loop continues. If no domain succeeds the function returns an empty string.

Changes

Cohort / File(s) Change summary
Top-domain cookie logic
packages/analytics-js/src/services/StoreManager/top-domain/index.ts
Wrapped per-domain cookie set/check/clear inside try/catch; on success clears cookie and returns the domain; on exception swallows error and continues to next domain. Function now returns an empty string when no domain succeeds. No public API signature changes.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Caller as StoreManager.getTopDomain
    participant DomainLoop as DomainLevels (iterable)
    participant CookieAPI as Cookie set/check/clear

    Caller->>DomainLoop: iterate domain levels
    loop per domain
        DomainLoop->>CookieAPI: try set cookie on domain
        alt set/check succeeds
            Note right of CookieAPI#dff0d8: success path
            CookieAPI-->>DomainLoop: cookie set & check true
            DomainLoop->>CookieAPI: clear cookie
            DomainLoop-->>Caller: return domain (done)
        else exception thrown
            Note right of CookieAPI#fbe8e8: error swallowed
            CookieAPI-->>DomainLoop: throws (caught)
            DomainLoop-->>DomainLoop: continue next domain (best-effort cleanup attempted)
        end
    end
    DomainLoop-->>Caller: no domain found (returns "")
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks (1 passed, 1 warning, 1 inconclusive)

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The description includes the summary, context, and a Linear task link as per the template, but the Cross Browser Tests section shows only Chrome marked while Firefox and IE11 remain untested, and both the Sanity Suite and Security confirmations are left unchecked, indicating incomplete required information. Please complete the Cross Browser Tests by verifying Firefox and IE11, ensure all sanity suite tests pass locally, and add the Security confirmation to demonstrate that no new security issues are introduced.
Title Check ❓ Inconclusive The current title “fix: error handle cookie operation” is related to the pull request’s focus on error handling in cookie operations but is phrased awkwardly and lacks specificity about the top‐level domain detection context, making it unclear to readers scanning the change history. Please update the title to a concise, clear sentence that highlights the main change, for example “fix: add error handling for cookie operations in top‐level domain detection.”
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@saikumarrs saikumarrs marked this pull request as ready for review September 10, 2025 09:42
Copilot AI review requested due to automatic review settings September 10, 2025 09:42
@saikumarrs saikumarrs requested a review from a team as a code owner September 10, 2025 09:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds error handling to cookie operations during top-level domain detection to prevent SDK initialization failures in environments with cookie access restrictions.

  • Wraps cookie setting and checking operations in a try-catch block
  • Continues domain level iteration when cookie operations fail instead of crashing
  • Improves SDK robustness across different browser security configurations

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread packages/analytics-js/src/services/StoreManager/top-domain/index.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1)

59-60: Nit: avoid shadowing the function name with domain local

Rename the loop variable to improve readability (e.g., candidateDomain).

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c8f156 and fa134c1.

📒 Files selected for processing (1)
  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/002-javascript-typescript.mdc)

Code must work in browsers AND service workers (no Node.js APIs)

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
packages/*/src/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place all package source code under packages/[package-name]/src/

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
packages/analytics-js/src/**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use @preact/signals-core for reactive state in the core SDK (analytics-js)

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
packages/!(analytics-js-common)/**/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Prefer shared TypeScript types from analytics-js-common across packages

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Adhere to the repository’s ESLint configuration for JavaScript/TypeScript code

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1759
File: packages/analytics-js-cookies/README.md:34-44
Timestamp: 2024-06-25T09:00:22.273Z
Learning: User saikumarrs prefers the current state of the documentation in the README.md of the `analytics-js-cookies` package without merging the blockquote sections or adding example usage for error handling as suggested.
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1759
File: packages/analytics-js-cookies/README.md:34-44
Timestamp: 2024-10-08T15:52:59.819Z
Learning: User saikumarrs prefers the current state of the documentation in the README.md of the `analytics-js-cookies` package without merging the blockquote sections or adding example usage for error handling as suggested.
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1754
File: packages/analytics-js-service-worker/README.md:0-0
Timestamp: 2024-10-08T15:52:59.819Z
Learning: saikumarrs prefers simplified language in documentation, avoiding redundant phrases.
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1754
File: packages/analytics-js-service-worker/README.md:0-0
Timestamp: 2024-06-14T09:50:33.511Z
Learning: saikumarrs prefers simplified language in documentation, avoiding redundant phrases.
📚 Learning: 2024-10-28T08:03:12.163Z
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1902
File: packages/analytics-js-plugins/src/utilities/eventsDelivery.ts:0-0
Timestamp: 2024-10-28T08:03:12.163Z
Learning: In `packages/analytics-js-plugins/src/utilities/eventsDelivery.ts`, the issue regarding inconsistent error handling approaches in `getDMTDeliveryPayload` is no longer valid.

Applied to files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
📚 Learning: 2024-10-08T15:52:59.819Z
Learnt from: MoumitaM
PR: rudderlabs/rudder-sdk-js#1777
File: packages/analytics-js/src/components/configManager/util/validate.ts:0-0
Timestamp: 2024-10-08T15:52:59.819Z
Learning: The function `isTopLevelDomain` in `validate.ts` was renamed to `isWebpageTopLevelDomain` for clarity.

Applied to files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Bundle size checks
  • GitHub Check: Code quality checks
  • GitHub Check: Unit Tests and Lint

Comment thread packages/analytics-js/src/services/StoreManager/top-domain/index.ts Outdated
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@github-actions

github-actions Bot commented Sep 10, 2025

Copy link
Copy Markdown

size-limit report 📦

Name Size Delta Limit check
Load Snippet 780 B 0 B (0% 🟢) 1 KB (✅)
Core - Legacy - NPM (ESM) 48.08 KB 57 B (+0.12% 🔺) 50 KB (✅)
Core - Legacy - NPM (CJS) 48.27 KB -40 B (-0.09% 🟢) 50 KB (✅)
Core - Legacy - NPM (UMD) 48.04 KB -31 B (-0.07% 🟢) 50 KB (✅)
Core - Legacy - CDN 48.13 KB 24 B (+0.05% 🔺) 50 KB (✅)
Core - Modern - NPM (ESM) 27.63 KB -38 B (-0.14% 🟢) 28 KB (✅)
Core - Modern - NPM (CJS) 27.88 KB 28 B (+0.1% 🔺) 28 KB (✅)
Core - Modern - NPM (UMD) 27.7 KB 21 B (+0.08% 🔺) 28 KB (✅)
Core - Modern - CDN 27.9 KB 1 B (+0.01% 🔺) 28 KB (✅)
Core (Bundled) - Legacy - NPM (ESM) 48.08 KB 57 B (+0.12% 🔺) 50 KB (✅)
Core (Bundled) - Legacy - NPM (CJS) 48.26 KB 7 B (+0.02% 🔺) 50 KB (✅)
Core (Bundled) - Legacy - NPM (UMD) 48.04 KB -31 B (-0.07% 🟢) 50 KB (✅)
Core (Bundled) - Modern - NPM (ESM) 40.76 KB -5 B (-0.02% 🟢) 41 KB (✅)
Core (Bundled) - Modern - NPM (CJS) 41.05 KB 42 B (+0.11% 🔺) 41.5 KB (✅)
Core (Bundled) - Modern - NPM (UMD) 40.77 KB -45 B (-0.11% 🟢) 41 KB (✅)
Core (Content Script) - Legacy - NPM (ESM) 47.97 KB 4 B (+0.01% 🔺) 50 KB (✅)
Core (Content Script) - Legacy - NPM (CJS) 48.23 KB 11 B (+0.03% 🔺) 50 KB (✅)
Core (Content Script) - Legacy - NPM (UMD) 47.97 KB -43 B (-0.09% 🟢) 50 KB (✅)
Core (Content Script) - Modern - NPM (ESM) 40.7 KB 27 B (+0.07% 🔺) 41 KB (✅)
Core (Content Script) - Modern - NPM (CJS) 40.96 KB -40 B (-0.1% 🟢) 41 KB (✅)
Core (Content Script) - Modern - NPM (UMD) 40.78 KB 71 B (+0.18% 🔺) 41 KB (✅)

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1)

65-75: Avoid false positives; compare exact unique value and always cleanup in finally

Set a unique test value, verify equality, and move deletion to a finally block so cleanup runs on all paths.

-    try {
-      // Set cookie on domain
-      cookie(cname, 1, opts);
-
-      // If successful
-      if (cookie(cname)) {
-        // Remove cookie from domain
-        cookie(cname, null, opts);
-        return domain;
-      }
-    } catch {
-      // Silently continue to next domain level if cookie access is restricted or setting fails
-      // Best-effort cleanup to avoid leaking the test cookie
-      try {
-        cookie(cname, null, opts);
-      } catch {
-        // Ignore if we are unable to delete the cookie
-      }
-    }
+    try {
+      // Set a unique test value to avoid pre-existing-cookie false positives
+      const testValue = `tld_test.${Date.now()}.${Math.random().toString(36).slice(2)}`;
+      cookie(cname, testValue, opts);
+      // Verify exact value
+      if (cookie(cname) === testValue) {
+        return domain;
+      }
+    } catch {
+      // Silently continue to next domain level if cookie access is restricted or setting fails
+    } finally {
+      // Best-effort cleanup
+      try { cookie(cname, null, opts); } catch {}
+    }
🧹 Nitpick comments (1)
packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1)

65-83: Explicitly set path: '/' in cookie opts for consistent set/delete

Add path: '/' to the opts object in packages/analytics-js/src/services/StoreManager/top-domain/index.ts to ensure the test cookie is always removed successfully, regardless of the current URL path.

 const opts = {
   domain: `${domain.indexOf('localhost') !== -1 ? '' : '.'}${domain}`,
+  path: '/', // ensure consistent set/delete across browsers
 };
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 799dfd6 and 37b6348.

📒 Files selected for processing (1)
  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/002-javascript-typescript.mdc)

Code must work in browsers AND service workers (no Node.js APIs)

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
packages/*/src/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place all package source code under packages/[package-name]/src/

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
packages/analytics-js/src/**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use @preact/signals-core for reactive state in the core SDK (analytics-js)

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
packages/!(analytics-js-common)/**/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Prefer shared TypeScript types from analytics-js-common across packages

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Adhere to the repository’s ESLint configuration for JavaScript/TypeScript code

Files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
🧠 Learnings (4)
📓 Common learnings
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1754
File: packages/analytics-js-service-worker/README.md:0-0
Timestamp: 2024-10-08T15:52:59.819Z
Learning: saikumarrs prefers simplified language in documentation, avoiding redundant phrases.
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1754
File: packages/analytics-js-service-worker/README.md:0-0
Timestamp: 2024-06-14T09:50:33.511Z
Learning: saikumarrs prefers simplified language in documentation, avoiding redundant phrases.
📚 Learning: 2024-10-08T15:52:59.819Z
Learnt from: MoumitaM
PR: rudderlabs/rudder-sdk-js#1777
File: packages/analytics-js/src/components/configManager/util/validate.ts:0-0
Timestamp: 2024-10-08T15:52:59.819Z
Learning: The function `isTopLevelDomain` in `validate.ts` was renamed to `isWebpageTopLevelDomain` for clarity.

Applied to files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
📚 Learning: 2024-06-25T09:00:22.273Z
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1759
File: packages/analytics-js-cookies/README.md:34-44
Timestamp: 2024-06-25T09:00:22.273Z
Learning: User saikumarrs prefers the current state of the documentation in the README.md of the `analytics-js-cookies` package without merging the blockquote sections or adding example usage for error handling as suggested.

Applied to files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
📚 Learning: 2024-11-08T06:58:29.573Z
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1907
File: packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts:172-174
Timestamp: 2024-11-08T06:58:29.573Z
Learning: The function `onError` in `packages/analytics-js/src/services/ErrorHandler/ErrorHandler.ts` is acceptable as currently implemented, and refactoring suggestions are not required unless necessary.

Applied to files:

  • packages/analytics-js/src/services/StoreManager/top-domain/index.ts
🧬 Code graph analysis (1)
packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1)
packages/analytics-js-common/src/component-cookie/index.ts (1)
  • cookie (138-138)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Code quality checks
  • GitHub Check: Bundle size checks
  • GitHub Check: Unit Tests and Lint
🔇 Additional comments (1)
packages/analytics-js/src/services/StoreManager/top-domain/index.ts (1)

76-82: LGTM: descriptive catch and best-effort cleanup

Clear, minimal comment and safe nested cleanup. Matches the PR goal without adding risk.

@saikumarrs saikumarrs merged commit e56acdc into develop Sep 10, 2025
19 of 20 checks passed
@saikumarrs saikumarrs deleted the feature/sdk-3883-error-handle-cookie-access-during-initialisation branch September 10, 2025 13:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants