How to get SSR to work with fluentui /Remix run?

Viewed 356

How to install fluent UI react with remix run? I believe this is important enough to be addressed here, as it is a stumbling block in the adoption of office-UI-fabric-react in the community.

1 Answers

After digging around FluentUI and Remix's documentation and some github issues, this is the approach that worked.

  1. Edit root.tsx. Add {typeof document === "undefined" ? "__STYLES__" : null} to the head tag. Add {typeof document === "undefined" ? "__SCRIPTS__" : null} before the closing body tag.
  2. Edit entry.server.tsx to include:
import { renderToString } from "react-dom/server"
import { RemixServer } from "remix"
import type { EntryContext } from "remix"
import { resetIds, Stylesheet } from "@fluentui/react"

const sheet = Stylesheet.getInstance()

export default function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  remixContext: EntryContext
) {
  resetIds()
  let markup = renderToString(
    <RemixServer context={remixContext} url={request.url} />
  )

  markup = markup.replace(
    "__STYLES__",
    `<style data-merge-styles="true">${sheet.getRules(true)}</style>`
  )

  markup = markup.replace(
    "__SCRIPTS__",
    `<script type="text/javascript">
      window.FabricConfig = window.FabricConfig || {};
      window.FabricConfig.serializedStylesheet = ${sheet.serialize()};
    </script>`
  )

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

  return new Response("<!DOCTYPE html>" + markup, {
    status: responseStatusCode,
    headers: responseHeaders,
  })
}
  1. Restart your remix app

References:
https://remix.run/docs/en/v1/guides/styling#css-in-js-libraries https://github.com/microsoft/fluentui/wiki/Server-side-rendering-and-browserless-testing#nextjs-setup https://github.com/microsoft/fluentui/issues/11411

If you would like to load fluentui icons as well, import initializeIcons into your pages and call it outside any function

Related