Skip to content

[BUG] Centralize localStorage access to prevent SSR hydration errors and improve type safety #410

Description

@abhijit9040

Description

Currently, localStorage is accessed directly passing string literals (e.g., localStorage.getItem("cart")) in over 20+ locations across the codebase (including checkout-card.tsx, nostr-context-provider.tsx, storefront-layout.tsx, etc.).

This architectural pattern introduces a few risks:

  • SSR Hydration Risks: Many of these calls lack a typeof window !== "undefined" guard. Directly reading from the window object during Next.js Server-Side Rendering (SSR) causes hydration mismatches or server crashes.
  • Key Fragmentation: Because keys like "cart", "tokens", or "sf_seller_pubkey" are magic strings scattered across files, they are prone to typos, making debug sessions difficult and creating silent state failures.
  • Boilerplate JSON Logic: Components are constantly reimplementing JSON.parse and JSON.stringify logic, without consistent try/catch fallbacks if the storage data gets corrupted.

Current Behavior

  • localStorage.getItem(...) and localStorage.setItem(...) are called directly inside React functional components and hooks.
  • String literals are hardcoded across multiple files for the same storage keys.
  • Components manually parse JSON without centralized fallback logic or error warning systems.

Expected Behavior

  • All localStorage interactions should pipe through a centralized StorageManager utility.
  • A strongly-typed STORAGE_KEYS object should act as the single source of truth for all storage keys to prevent typos.
  • The wrapper utility should automatically check for the browser environment (typeof window !== "undefined") before attempting to access localStorage, ensuring SSR safety.
  • JSON.parse and JSON.stringify logic should be abstracted into safe wrapper definitions with default boundaries.

Steps to Reproduce

  1. Open the repository locally and navigate to components/utility-components/checkout-card.tsx or utils/nostr/nostr-helper-functions.ts.
  2. Search for the term localStorage.getItem.
  3. Note the inconsistent usage of typeof window !== "undefined" guards and the repeated .setItem("cart", JSON.stringify(...)) logic.

Next.js Version

18.17.0

Operating System

Windows 10

Node.js Version

16.2.3

Browser

Chrome

Screenshots

No response

Additional Context

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions