Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent cookie storage engine options init by default #2077

Conversation

saikumarrs
Copy link
Member

@saikumarrs saikumarrs commented Mar 3, 2025

PR Description

I have fixed an issue with the cookie storage engine where options are initialised by default causing crashes on Next.js server-side imports.

The default cookie storage options are set once it is configured in RudderAnalytics class's constructor.

Linear task (optional)

https://linear.app/rudderstack/issue/SDK-3071/prevent-initialising-cookie-module-by-default

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.

@saikumarrs saikumarrs self-assigned this Mar 3, 2025
Copy link
Contributor

coderabbitai bot commented Mar 3, 2025

📝 Walkthrough

Walkthrough

This pull request updates the CookieStorage class by changing its options property from required to optional. The default initialization of options is now deferred to the configure method. If options is not set when configure is called, it will be initialized using the getDefaultCookieOptions() function.

Changes

File Path Change Summary
packages/analytics-js/.../CookieStorage.ts Updated options property to optional. Removed default initialization from the constructor and added a conditional check in configure to set defaults.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant CS as CookieStorage
    participant GO as getDefaultCookieOptions

    C->>CS: new CookieStorage() (options not provided)
    C->>CS: configure()
    CS->>CS: Check if options is undefined
    alt options undefined
        CS->>GO: getDefaultCookieOptions()
        GO-->>CS: return default options
        CS->>CS: Set options property with default options
    else options defined
        CS->>CS: Use provided options
    end
Loading

Possibly related PRs

Suggested reviewers

  • koladilip
✨ Finishing Touches
  • 📝 Generate Docstrings

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Mar 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 61.55%. Comparing base (21ec079) to head (72867f9).
Report is 1 commits behind head on hotfix/prevent-import-execution.

Additional details and impacted files
@@                       Coverage Diff                        @@
##           hotfix/prevent-import-execution    #2077   +/-   ##
================================================================
  Coverage                            61.55%   61.55%           
================================================================
  Files                                  478      478           
  Lines                                16447    16448    +1     
  Branches                              3264     3256    -8     
================================================================
+ Hits                                 10124    10125    +1     
+ Misses                                5117     5089   -28     
- Partials                              1206     1234   +28     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (2)

26-38: Consider adding safeguard in other methods that use this.options.

While the configure method now safely initializes options when needed, other methods like setItem that use this.options directly could still be called before configure. Consider adding a safeguard mechanism to ensure options is always initialized before use.

setItem(key: string, value: Nullable<string>): boolean {
+   // Ensure options are initialized
+   if (!this.options) {
+     this.configure();
+   }
    cookie(key, value, this.options, this.logger);
    this.length = Object.keys(cookie()).length;
    return true;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 33-33: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


22-24: Update constructor documentation to clarify options initialization behavior.

Since the initialization behavior of options has changed from immediate to deferred, it would be helpful to update the constructor's JSDoc to explain that options will be lazily initialized when configure is called.

/**
 * A storage utility to persist values in cookies via Storage interface
 */
class CookieStorage implements IStorage {
  logger?: ILogger;
  options?: ICookieStorageOptions;
  isSupportAvailable = true;
  isEnabled = true;
  length = 0;

+  /**
+   * Creates a new CookieStorage instance
+   * @param logger Optional logger instance
+   * Note: Cookie options are not initialized in the constructor but are lazily 
+   * initialized when configure() is called.
+   */
  constructor(logger?: ILogger) {
    this.logger = logger;
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c59400 and 72867f9.

📒 Files selected for processing (1)
  • packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Security and code quality checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Bundle size checks
🔇 Additional comments (3)
packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (3)

17-17: Appropriate type improvement: Making options optional aligns with deferred initialization.

The change from required to optional type properly reflects that options may not be initialized immediately upon class instantiation.


27-29: Good implementation of lazy initialization for cookie options.

The added conditional ensures that default options are only set when needed, which aligns with the PR objective to prevent cookie storage engine options initialization by default.


41-41:

❓ Verification inconclusive

Verify that options is available before use in setItem method.

The setItem method uses this.options directly without checking if it's defined. If setItem is called before configure, this could potentially lead to runtime errors.


🏁 Script executed:

#!/bin/bash
# Search for any direct usages of the CookieStorage.setItem method without prior configure calls

# Find places where CookieStorage is instantiated
echo "Searching for instantiations of CookieStorage..."
rg "new CookieStorage" -A 5 --type ts

# Find places where setItem is called directly
echo "Searching for direct calls to setItem..."
rg "\.setItem\(" --type ts

# Check if there are any test cases testing the behavior
echo "Checking for related test cases..."
rg "CookieStorage" --type test

Length of output: 5638


Action Required: Ensure this.options is initialized before usage in setItem.

The current implementation calls:

cookie(key, value, this.options, this.logger);

without verifying if this.options has been set. If setItem is invoked before the configure method (or any initialization logic that assigns this.options), it may lead to runtime errors. Please add a safeguard to check for (or initialize) this.options—or enforce that configuration always happens before calling setItem.

  • Location: packages/analytics-js/src/services/StoreManager/storages/CookieStorage.ts (around line 41)
  • Recommendation: Either add a conditional guard (e.g., an early-return or error throw when this.options is absent) or ensure that this.options is assigned during construction/configuration.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 3, 2025
@saikumarrs saikumarrs changed the base branch from develop to hotfix/prevent-import-execution March 3, 2025 10:12
@saikumarrs saikumarrs dismissed coderabbitai[bot]’s stale review March 3, 2025 10:12

The base branch was changed.

@saikumarrs saikumarrs marked this pull request as ready for review March 3, 2025 10:12
@saikumarrs saikumarrs requested a review from a team as a code owner March 3, 2025 10:12
Copy link

github-actions bot commented Mar 3, 2025

size-limit report 📦

Name Size (Base) Size (Current) Size Limit Status
Cookies Utils - Legacy - NPM (ESM) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (CJS) 1.75 KB 1.75 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (UMD) 1.53 KB 1.53 KB (0%) 2 KB
Cookies Utils - Modern - NPM (ESM) 1.17 KB 1.17 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (CJS) 1.4 KB 1.4 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (UMD) 1.16 KB 1.16 KB (0%) 1.5 KB
Plugins Module Federation Mapping - Legacy - CDN 332 B 332 B (0%) 512 B
Plugins Module Federation Mapping - Modern - CDN 331 B 331 B (0%) 512 B
Plugins - Legacy - CDN 14.15 KB 14.15 KB (0%) 14.5 KB
Plugins - Modern - CDN 5.65 KB 5.65 KB (0%) 6 KB
Common - No bundling 18.38 KB 18.38 KB (0%) 18.4 KB
Load Snippet 765 B 765 B (0%) 1 KB
Core (v1.1) - NPM (ESM) 30.14 KB 30.14 KB (0%) 32 KB
Core (v1.1) - NPM (CJS) 30.31 KB 30.31 KB (0%) 32 KB
Core (v1.1) - NPM (UMD) 30.16 KB 30.16 KB (0%) 32 KB
Core (Content Script - v1.1) - NPM (ESM) 29.69 KB 29.69 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (CJS) 29.85 KB 29.85 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (UMD) 29.73 KB 29.73 KB (0%) 30.5 KB
Core (v1.1) - Legacy - CDN 32.01 KB 32.01 KB (0%) 32.5 KB
Core (v1.1) - Modern - CDN 30.04 KB 30.04 KB (0%) 32 KB
Service Worker - Legacy - NPM (ESM) 30.3 KB 30.3 KB (0%) 31 KB
Service Worker - Legacy - NPM (CJS) 30.57 KB 30.57 KB (0%) 31 KB
Service Worker - Legacy - NPM (UMD) 30.39 KB 30.39 KB (0%) 31 KB
Service Worker - Modern - NPM (ESM) 25.51 KB 25.51 KB (0%) 26 KB
Service Worker - Modern - NPM (CJS) 25.76 KB 25.76 KB (0%) 26.5 KB
Service Worker - Modern - NPM (UMD) 25.55 KB 25.55 KB (0%) 26 KB
Core - Legacy - NPM (ESM) 47.76 KB 47.8 KB (+0.09% ▲) 48 KB
Core - Legacy - NPM (CJS) 48.09 KB 48.01 KB (-0.16% ▼) 48.2 KB
Core - Legacy - NPM (UMD) 47.79 KB 47.79 KB (+0.01% ▲) 48 KB
Core - Legacy - CDN 47.93 KB 47.93 KB (0%) 48 KB
Core - Modern - NPM (ESM) 26.78 KB 26.75 KB (-0.13% ▼) 27 KB
Core - Modern - NPM (CJS) 26.97 KB 26.98 KB (+0.04% ▲) 27.2 KB
Core - Modern - NPM (UMD) 26.81 KB 26.8 KB (-0.04% ▼) 27 KB
Core - Modern - CDN 27.04 KB 27.06 KB (+0.07% ▲) 27.5 KB
Core (Bundled) - Legacy - NPM (ESM) 47.76 KB 47.8 KB (+0.09% ▲) 48 KB
Core (Bundled) - Legacy - NPM (CJS) 48.04 KB 48.04 KB (-0.01% ▼) 48.2 KB
Core (Bundled) - Legacy - NPM (UMD) 47.79 KB 47.79 KB (+0.01% ▲) 48 KB
Core (Bundled) - Modern - NPM (ESM) 38.93 KB 38.92 KB (-0.05% ▼) 39 KB
Core (Bundled) - Modern - NPM (CJS) 39.18 KB 39.19 KB (+0.03% ▲) 39.2 KB
Core (Bundled) - Modern - NPM (UMD) 38.91 KB 38.94 KB (+0.08% ▲) 39 KB
Core (Content Script) - Legacy - NPM (ESM) 47.73 KB 47.67 KB (-0.13% ▼) 48 KB
Core (Content Script) - Legacy - NPM (CJS) 47.91 KB 47.98 KB (+0.15% ▲) 48 KB
Core (Content Script) - Legacy - NPM (UMD) 47.73 KB 47.76 KB (+0.06% ▲) 48 KB
Core (Content Script) - Modern - NPM (ESM) 38.87 KB 38.91 KB (+0.1% ▲) 39 KB
Core (Content Script) - Modern - NPM (CJS) 39.16 KB 39.16 KB (-0.01% ▼) 39.2 KB
Core (Content Script) - Modern - NPM (UMD) 38.92 KB 38.92 KB (0%) 39 KB
All Integrations - Legacy - CDN 95.08 KB 95.08 KB (0%) 95.3 KB
All Integrations - Modern - CDN 90.77 KB 90.77 KB (0%) 91 KB

@saikumarrs saikumarrs merged commit cf0e4d9 into hotfix/prevent-import-execution Mar 3, 2025
14 of 15 checks passed
@saikumarrs saikumarrs deleted the fix.prevent-default-cookie-options-sdk-3071 branch March 3, 2025 10:48
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.

2 participants