Next.js, Styled-components and Yandex Metrica Session Replay

1.7k Views Asked by At

I'm working in a project using Next.js and styled-components. In my file [slug].tsx:

export default function ProductDetails({ product }: IProductDetailsProps) {
  const router = useRouter();

  if (router.isFallback) {
    return (
      <LoadingContainer>
        <ReactLoading color="#000" type="bubbles" />
      </LoadingContainer>
    );
  }

  return (
    <>
      {product._id ? (
        <>
          <Header />

          <Container>
            <ProductPath>
              <Link href="/">Home</Link>

              <Link href="/shop">Shop</Link>

              {product.categoryId && (
                <Link href={`/shop/${product.categoryId.slug}`}>
                  {product.categoryId.name}
                </Link>
              )}

              <span>{product.name}</span>
            </ProductPath>

            <ProductInfo product={product} />
          </Container>
        </>
      ) : (
        <Error>An unexpected error has occurred.</Error>
      )}
    </>
  );
}

Most of the tags are from styled-components, for example:

export const LoadingContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
`;

export const Error = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
`;

export const Container = styled.div``;

export const ProductPath = styled.p`
  display: block;
  padding: 22px 32px;
  font-size: 14px;
  background-color: #f1f1f1;

  a {
    text-decoration: none;
    color: #09c;

    transition: color 0.2s;

    &:hover {
      color: #fcb800;
    }
  }

  a + a::before,
  a + span::before {
    content: '/';
    color: #000;
    cursor: auto;
    margin: 0 10px;
  }
`;

I've followed styled-components docs for Next.js (https://styled-components.com/docs/advanced#nextjs), my .babelrc:

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

_document.tsx:

import Document, { DocumentContext } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}

This project requires that Yandex Session Replay work, but when my app loads in production, there are no errors in console and Yandex Session Replay does not render the CSS:

session replay not rendering CSS

Any suggestions?

Thanks.

1

There are 1 best solutions below

0
On

try to add the render function inside _document component like that:

import Document, {
  Html,
  Head,
  Main,
  NextScript,
  DocumentContext
} from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }

  render() {
    return (
      <Html lang="en">
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}