서버사이드 렌더링 스타일링 이슈

문제

스타일드 컴포넌트로 스타일링된 컴포넌트가 브라우저에 렌더링 된 후 스타일이 적용됨

접근

Styled-componet가 css파일을 서버 렌더링 과정에서 생성하고 이를 브라우저로 별개로 전송한다 판단.

예상흐름 서버에서 자원 생성 → html 먼저 렌더링 → 렌더링 후 css 요청 → css 도착 파싱 후 리렌더링

해결

서버에서 스타일 컴포넌트가 별개의 파일로 분리되지 않고 렌더링된 HTML에 적용하여 이를 head 태그에 삽입되는 방식 발견

static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet();
    // eslint-disable-next-line testing-library/render-result-naming-convention
    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();
    }
  }