SSR error - ReferenceError: document is not defined
Hi! π
I'm new to both Nuxt UI and SSR, so maybe I'm just missing something, but...
I'm using Nuxt UI Pro with Inertia and Laravel
I have set up SSR, and I can build the application just fine and also start the SSR server
But! When I try to access a page, I get this error:
The
/bootstrap/ssr/ssr.js
file is the output from the build
The code on line 249: const style = document.createElement("style");
Which is inside this if-statement:
I'm a bit stuck, and don't know what to search for, as my previous attempts gave me no real results
Does anyone know what I should be doing differently or where to go from here? π2 Replies
Hi @Peter Brinck. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
The error
Wrap any code that uses
ReferenceError: document is not defined
occurs because the code is trying to access the document
object during server-side rendering (SSR). In SSR, your code runs in a Node.js environment, which does not have access to browser-specific globals like document
or window
.
In Nuxt's universal rendering mode, you must ensure that any code using browser APIs (like document.createElement
) only runs on the client side. The knowledge sources explain that server and browser environments don't provide the same APIs, and you should use environment checks to separate such code. Nuxt provides import.meta.client
and import.meta.server
to help you determine where your code is running. For example:
You should wrap any code that accesses document
in such a check to prevent it from running during SSR and causing this error. This is a common pattern in Nuxt to avoid hydration and SSR issues when using browser-only APIs. For more details, see the section on universal rendering and environment constraints in the Nuxt documentation: Universal Rendering.
If you are using a third-party library or code that is not SSR-compatible, you may need to import or use it only on the client side, or use Nuxt's client-only components or dynamic imports.
Summary:Wrap any code that uses
document
in an import.meta.client
check to ensure it only runs in the browser, not during SSR. This will resolve the ReferenceError: document is not defined
error you are seeing in your Nuxt SSR setup.
Universal Rendering - Nuxt Docs
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@487938234769211392> Kapa.ai is still learning and improving, please let me know how I did by reacting below.