Webclat / Martech Practice
Webclat / Martech Practice  /  qa  /  hotjar

What's the correct way to load the Hotjar snippet in a Next.js/Nuxt app without SSR/window errors?

Answer in brief

Hotjar's snippet references window and document directly and must only execute in the browser. In Next.js, load it via the next/script component with strategy="afterInteractive" - never inline it in a component body that runs during server rendering. In Nuxt, load it inside a client-only plugin or a lifecycle hook guarded by process.client, never in universal or server-rendered code paths.

Why this happens

Next.js and Nuxt both render your app's initial HTML on the server by default, where window and document do not exist - any code referencing them unconditionally at module scope or during render throws a reference error during server-side rendering, even though the exact same code works fine once hydrated in the browser.

Hotjar's official snippet assumes a traditional client-only page load, so pasting it directly into a component's render output, rather than through a framework-aware script-loading mechanism, is the most common way this breaks specifically in SSR frameworks while working fine on a plain static HTML page.

Fix it

  1. In Next.js: import Script from next/script in your root layout, set strategy="afterInteractive" so the script loads after the page is interactive and safely client-only, and place the Hotjar initialization inside the Script component's body or onLoad callback, not as a raw inline script tag in JSX.
  2. In Nuxt: create a client-only plugin file (a filename ending .client.ts in your plugins/ directory, which Nuxt automatically excludes from server rendering) and initialize Hotjar exactly as its snippet specifies inside it.
  3. If you need to reference Hotjar elsewhere in the app - for example an hj("stateChange", ...) call on route change - guard those calls with a check for process.client or typeof window !== "undefined" before referencing window.hj.

How to verify it worked

Run a production build (next build && next start, or nuxt build && nuxt start) rather than only the dev server - SSR-specific errors often do not surface identically in dev mode. Confirm no "window is not defined" or "document is not defined" error appears in server logs, and confirm the Hotjar script tag appears in the rendered page's network requests once loaded in a real browser.

Still Seeing This After Trying the Fix?

Send us what you are seeing - the console error, the Network tab, the Live View output. We trace tracking implementations for a living and can usually tell you what is actually happening in one look.

Ask An Engineer