Skip to content

Fix: Shadow DOM SSR Hydration Support - #5656

Merged
quantizor merged 9 commits into
styled-components:mainfrom
federico-fiorini:fix/rehydration-shadow-dom
Feb 8, 2026
Merged

quantizor merged 9 commits into
styled-components:mainfrom
federico-fiorini:fix/rehydration-shadow-dom

Conversation

@federico-fiorini

@federico-fiorini federico-fiorini commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor

Fix: Shadow DOM SSR Hydration Support

Problem

Styled-components' SSR hydration does not work in Shadow DOM contexts, causing complete hydration failure and duplicate style injection.

Issue 1: Hardcoded document Search

The rehydrateSheet() function only searches document.querySelectorAll() for server-rendered styles, making it unable to find styles rendered inside Shadow DOM.

Current behavior:

  • Server renders styles with metadata markers inside Shadow DOM
  • Client-side hydration searches only document for these styles
  • Styles are never found, causing complete hydration failure
  • New styles are injected, resulting in duplicate <style> tags

Issue 2: SHOULD_REHYDRATE Flag Prevents Re-rehydration

The global SHOULD_REHYDRATE flag is set to false after the first rehydration attempt, preventing subsequent rehydration when the target changes.

Common pattern that fails:

function MyComponent() {
  const [shadowRoot, setShadowRoot] = useState<ShadowRoot | undefined>(undefined);

  useLayoutEffect(() => {
    const root = hostRef.current.attachShadow({ mode: 'open' });
    setShadowRoot(root);
  }, []);

  return (
    <StyleSheetManager target={shadowRoot}>
      <StyledComponents />
    </StyleSheetManager>
  );
}

What happens:

  1. Initial render: target is undefined → rehydrates from document (finds nothing)
  2. SHOULD_REHYDRATE flag set to false
  3. After useLayoutEffect: target changes to shadowRoot
  4. StyleSheetManager calls reconstructWithOptions({ target: shadowRoot })
  5. Bug: New sheet created but NO rehydration (flag already false)
  6. Result: Duplicate styles injected

Solution

1. Container Detection Helper

Added getRehydrationContainer() helper that extracts the correct container (Document or ShadowRoot) from an InsertionTarget:

export const getRehydrationContainer = (
  target?: InsertionTarget | undefined
): Document | ShadowRoot => {
  if (!target) return document;

  // Check if target is a ShadowRoot
  if (target instanceof ShadowRoot) {
    return target as ShadowRoot;
  }

  // Check if target is an HTMLElement inside a ShadowRoot
  if ('getRootNode' in target) {
    const root = (target as HTMLElement).getRootNode();
    if (root instanceof ShadowRoot) {
      return root as ShadowRoot;
    }
  }

  return document;
};

2. Updated rehydrateSheet() Signature

Simplified to accept only the sheet parameter and extract the target from sheet.options.target:

export const rehydrateSheet = (sheet: Sheet) => {
  const container = getRehydrationContainer(sheet.options.target);
  const nodes = container.querySelectorAll(SELECTOR);
  // ... rehydration logic
};

3. Re-rehydration on Container Change

Updated reconstructWithOptions() to detect when the target's container changes and trigger rehydration:

reconstructWithOptions(options: SheetConstructorArgs, withNames = true) {
  const newSheet = new StyleSheet(
    { ...this.options, ...options },
    this.gs,
    (withNames && this.names) || undefined
  );

  // If we're reconstructing with a new target on the client, check if the container changed
  // This handles the case where StyleSheetManager's target prop changes (e.g., from undefined to shadowRoot)
  // We only rehydrate if the container (Document or ShadowRoot) actually changes
  if (!this.server && IS_BROWSER && options.target !== this.options.target) {
    const oldContainer = getRehydrationContainer(this.options.target);
    const newContainer = getRehydrationContainer(options.target);

    if (oldContainer !== newContainer) {
      rehydrateSheet(newSheet);
    }
  }

  return newSheet;
}

Changes

  • src/sheet/Rehydration.ts: Added exported getRehydrationContainer() helper and updated rehydrateSheet() to use it
  • src/sheet/Sheet.ts: Updated constructor, rehydrate(), and reconstructWithOptions() to use container-based rehydration
  • src/sheet/test/Rehydration.test.tsx: Added 8 tests for Shadow DOM rehydration
  • src/sheet/test/Sheet.test.ts: Added 3 tests for reconstructWithOptions() with target/container changes

Benefits

  • ✅ Shadow DOM SSR hydration now works correctly
  • ✅ Handles delayed shadow root availability
  • ✅ Optimized to only rehydrate when container actually changes
  • ✅ Backward compatible (defaults to document when no target specified)
  • ✅ No duplicate style injection

Testing

All 44 tests passing, including comprehensive Shadow DOM coverage:

Rehydration Tests (8 tests)

  • ✅ Rehydrates from ShadowRoot when target is a ShadowRoot
  • ✅ Rehydrates from ShadowRoot when target is an HTMLElement inside a ShadowRoot
  • ✅ Falls back to document when target is undefined
  • ✅ Falls back to document when target is a regular HTMLElement
  • ✅ Handles multiple ShadowRoots independently
  • ✅ Rehydrates styles with correct group IDs
  • ✅ Removes server-rendered style tags after rehydration
  • ✅ Preserves style order during rehydration

Sheet Tests (3 tests)

  • ✅ Rehydrates when target's container changes (e.g., from document to ShadowRoot)
  • ✅ Does not rehydrate when target remains the same
  • ✅ Does not rehydrate when target changes within same container (optimization test)

@changeset-bot

changeset-bot Bot commented Jan 29, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1791950

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
styled-components Patch

Not sure what this means? Click here to learn what changesets are.

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

@federico-fiorini
federico-fiorini marked this pull request as ready for review January 30, 2026 11:32
quantizor and others added 2 commits February 7, 2026 22:08
- Pass insertion target to removeGlobalStyleTag so it queries the correct
  container (ShadowRoot or document) when cleaning up SSR-rendered global
  style tags on unmount
- Use tag.getRootNode() in getSheet fallback so the Firefox quirk path
  checks the shadow root's styleSheets instead of only document.styleSheets
- Add tests for both fixes and getSheet/makeStyleTag in shadow DOM

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@quantizor

Copy link
Copy Markdown
Contributor

@federico-fiorini thank you for this!

@quantizor
quantizor merged commit f84f3fa into styled-components:main Feb 8, 2026
5 checks passed
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