Skip to content

styled-components fails in Facebook and TikTok browser #5144

@marianzburlea

Description

@marianzburlea

What version of Remix are you using?

1.11.0

Steps to Reproduce

  • run npx create-remix@latest project-name
  • select: basic, typescript, netlify and n so we can run yarn
  • run yarn add styled-components
  • run yarn add -D @types/styled-components
  • create a basic styled component
import styled from 'styled-components'

const H1 = styled.h1`
  border: 1px solid red;
`

export default function Index() {
  return (
    <div>
      <H1>test</H1>
    </div>
  )
}

update entry.server.tsx with:

import { renderToString } from "react-dom/server";
import { RemixServer } from "@remix-run/react";
import type { EntryContext } from "@remix-run/node"; // or cloudflare/deno
import { ServerStyleSheet } from "styled-components";

export default function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  remixContext: EntryContext
) {
  const sheet = new ServerStyleSheet();

  let markup = renderToString(
    sheet.collectStyles(
      <RemixServer
        context={remixContext}
        url={request.url}
      />
    )
  );
  const styles = sheet.getStyleTags();
  markup = markup.replace("__STYLES__", styles);

  responseHeaders.set("Content-Type", "text/html");

  return new Response("<!DOCTYPE html>" + markup, {
    status: responseStatusCode,
    headers: responseHeaders,
  });
}

inside root.tsx file update the head tag to include styles:

    <head>
        <Meta />
        <Links />
        {typeof document === "undefined"
          ? "__STYLES__"
          : null}
    </head>

and deploy to netlify.

Here is an example project that replicates the issue:
https://github.com/marianzburlea/test-sc

and here is an example of the styled component receiving a red border.
https://steady-pixie-99fc00.netlify.app/

Expected Behavior

actual styles to be displayed

image

Actual Behavior

hydration fails and no styles are applied, when I click on a link from Facebook and Tiktok.

The BIG problem is not facebook messenger, it's how people that click paid ads see the website.

This is the same way users that click on an ad, end up on the website, with no styles.

image

image

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions