Skip to content

fix: add isBrowser check for SSR#3254

Merged
ogzhanolguncu merged 1 commit intomainfrom
ENG-1793
May 14, 2025
Merged

fix: add isBrowser check for SSR#3254
ogzhanolguncu merged 1 commit intomainfrom
ENG-1793

Conversation

@ogzhanolguncu
Copy link
Contributor

@ogzhanolguncu ogzhanolguncu commented May 13, 2025

What does this PR do?

Add isBrowser check and prevent localStorage failing silently during SSR.
Fixes #3249

If there is not an issue for this, please create one first. This is used to tracking purposes and also helps use understand why this PR exists

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Make sure saved queries work in audit or some log page else

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • Refactor
    • Improved saved filter management for bookmarks, resulting in more consistent and reliable behavior across browser sessions.
    • Enhanced performance and stability by reducing unnecessary local storage access and ensuring safer handling in different environments.

@linear
Copy link

linear bot commented May 13, 2025

@changeset-bot
Copy link

changeset-bot bot commented May 13, 2025

⚠️ No Changeset found

Latest commit: 9fb0d25

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented May 13, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 13, 2025 11:00am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 13, 2025 11:00am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 13, 2025

📝 Walkthrough

Walkthrough

The useBookmarkedFilters hook was refactored to use React state for managing saved filters instead of reading from localStorage on every render. Helper functions were introduced to safely access localStorage, including checks for browser environments. All localStorage interactions are now centralized and guarded, and filter data normalization was improved.

Changes

File(s) Change Summary
apps/dashboard/components/logs/hooks/use-bookmarked-filters.ts Refactored hook to use React state for filters, added helper functions for localStorage access with environment checks, and improved data normalization.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant useBookmarkedFilters
    participant LocalStorage

    Component->>useBookmarkedFilters: Mount/use
    useBookmarkedFilters->>LocalStorage: getLocalStorage (if browser)
    useBookmarkedFilters-->>useBookmarkedFilters: Set state with saved filters

    Component->>useBookmarkedFilters: Add/Toggle bookmark
    useBookmarkedFilters->>LocalStorage: setLocalStorage (if browser)
    useBookmarkedFilters-->>useBookmarkedFilters: Update React state

    useBookmarkedFilters-->>Component: Return normalized savedFilters
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent ReferenceError: localStorage is not defined in /audit (#3249)

Suggested reviewers

  • perkinsjr

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@github-actions
Copy link
Contributor

github-actions bot commented May 13, 2025

Thank you for following the naming conventions for pull request titles! 🙏

@vercel vercel bot temporarily deployed to Preview – dashboard May 13, 2025 11:00 Inactive
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: 1

🧹 Nitpick comments (4)
apps/dashboard/components/logs/hooks/use-bookmarked-filters.ts (4)

24-31: Prefer lazy useState initialisation to avoid SSR → CSR “flicker”

The first paint on the client always starts with an empty array and then re-hydrates once the useEffect runs.
Initialising the state with the value that will be read from localStorage prevents that extra render and keeps UI in sync from the very first paint.

-const [savedFilters, setSavedFilters] = useState<SavedFiltersGroup<QuerySearchParams>[]>([]);
+const [savedFilters, setSavedFilters] = useState<SavedFiltersGroup<QuerySearchParams>[]>(() =>
+  JSON.parse(getLocalStorage(localStorageName)) as SavedFiltersGroup<QuerySearchParams>[],
+);

Because getLocalStorage already returns "[]" during SSR, this approach is still safe to render on the server.


61-65: Avoid shadowing the savedFilters state variable

const savedFilters = … re-uses the same identifier as the React state declared above, which can be confusing while reading the effect.
Simply rename the local constant to something like storedSavedFilters to improve readability.

-const savedFilters = JSON.parse(
+const storedSavedFilters = JSON.parse(
     getLocalStorage(localStorageName),
-) as SavedFiltersGroup<QuerySearchParams>[];
+) as SavedFiltersGroup<QuerySearchParams>[];

139-163: Sync bookmarks across tabs & avoid stale closures

toggleBookmark reads from localStorage, mutates, then calls setSavedFilters.
If the user has the dashboard open in multiple tabs, changes in one tab will not propagate to the others and can be overwritten.

  1. Listen to the global "storage" event to keep local React state in sync:
useEffect(() => {
  const handler = (e: StorageEvent) => {
    if (e.key === localStorageName && e.newValue) {
      setSavedFilters(JSON.parse(e.newValue));
    }
  };
  window.addEventListener("storage", handler);
  return () => window.removeEventListener("storage", handler);
}, [localStorageName]);
  1. Inside toggleBookmark, derive the next state from the current state to avoid a stale closure:
-setSavedFilters(updatedFilters);
+setSavedFilters(() => updatedFilters);

165-174: Normalise the since field alongside startTime / endTime

since is treated as a date filter in earlier logic but is not normalised here, leading to possible NaN issues when re-hydrating filters.

...,
since: Number.isNaN(Number(filter.filters.since))
  ? null
  : Number(filter.filters.since),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dc052cf and 9fb0d25.

📒 Files selected for processing (1)
  • apps/dashboard/components/logs/hooks/use-bookmarked-filters.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/dashboard/components/logs/hooks/use-bookmarked-filters.ts (1)
apps/dashboard/lib/utils.ts (1)
  • isBrowser (8-8)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/dashboard/components/logs/hooks/use-bookmarked-filters.ts (1)

75-84: crypto.randomUUID() may not exist in older runtimes

Although most modern browsers and recent Node versions support crypto.randomUUID, older environments (or JS runtimes locked down for CSP reasons) may not.
If supporting such environments matters, consider:

const uuid = typeof crypto?.randomUUID === "function"
  ? crypto.randomUUID()
  : Math.random().toString(36).slice(2); // fallback

At minimum, please verify target browser support.

@mcstepp mcstepp self-assigned this May 13, 2025
Copy link
Collaborator

@mcstepp mcstepp left a comment

Choose a reason for hiding this comment

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

the safari incognito quirk isn't a blocking issue, but we should be diligent about our supported browsers overall.

Copy link
Contributor Author

Yeah. I agree i'll run a sweep tomorrow for safari

@ogzhanolguncu ogzhanolguncu added this pull request to the merge queue May 14, 2025
Merged via the queue into main with commit ab2e620 May 14, 2025
32 checks passed
@ogzhanolguncu ogzhanolguncu deleted the ENG-1793 branch May 14, 2025 09:25
@coderabbitai coderabbitai bot mentioned this pull request Jul 11, 2025
18 tasks
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.

Investigate ReferenceError: localStorage is not defined in /audit

2 participants