How to solve the ReferenceError Document is not defined issue?

1. The situation

The other day I was working in a project that had a few requirements:

2. The problem

But just after I installed and configured everything, I run npm run dev and...

I just saw an error message with:

text
ReferenceError: document is not defined

Mantine uses in several places the document element, which obviously is only available in the browser.

And while with Next.js it is very easy to make it work with SSR, and even with React Router it is... it seems it is not that easy when also adding the Cloudflare Workers to the equation.

3. The solution

After lurking lots of sites and Discord communities for a while with not much luck, I found a way to make it work, we just need to add some extra configuration to our SSR config in the vite.config.ts file, so our Cloudflare Workers doing the SSR know what to do:

text
...the rest of your config file
  ssr: {
    target: "webworker",
    noExternal: true,
    resolve: {
      conditions: ["worker", "workerd", "browser"],
    }
}
...the rest of your config file

That easy! But since I spent too much time trying to solve this, I decided to create this small post just in case anyone else faces the same issue (or maybe also for myself in the future).