Skip to content

Fix: TypeError in Node.js 22 SSR environment due to global.navigator access #144

@mcprp

Description

@mcprp

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Issue Description

I encountered an error when using @juggle/resize-observer in a Nuxt 3 + TypeScript + Naive UI project running on Node.js 22:

ERROR [request error] [unhandled] [GET] http://localhost:3000/

ℹ Error: Cannot read properties of undefined (reading 'userAgent')

⁃ (node_modules/@juggle/resize-observer/lib/algorithms/calculateBoxSize.js:12:94)

The error occurs when the library tries to detect IE browser by checking global.navigator.userAgent. In Node.js 22, global.navigator is undefined, causing the error.

It's worth noting that:

  1. Everything works fine in Node.js 20
  2. The error only occurs during server-side rendering of frontend pages
  3. This issue affects many frameworks using SSR with Node.js 22

Solution

I've used patch-package to fix this issue by checking if we're in a browser environment before attempting to access navigator:

diff --git a/node_modules/@juggle/resize-observer/lib/algorithms/calculateBoxSize.js b/node_modules/@juggle/resize-observer/lib/algorithms/calculateBoxSize.js
index 9a828e7..3f39270 100644
--- a/node_modules/@juggle/resize-observer/lib/algorithms/calculateBoxSize.js
+++ b/node_modules/@juggle/resize-observer/lib/algorithms/calculateBoxSize.js
@@ -7,7 +7,9 @@ import { global } from '../utils/global';
 var cache = new WeakMap();
 var scrollRegexp = /auto|scroll/;
 var verticalRegexp = /^tb|vertical/;
-var IE = (/msie|trident/i).test(global.navigator && global.navigator.userAgent);
+var IE = typeof window === 'undefined'
+    ? false
+    : (/msie|trident/i).test(global.navigator && global.navigator.userAgent);
 var parseDimension = function (pixel) { return parseFloat(pixel || '0'); };
 var size = function (inlineSize, blockSize, switchSizes) {
     if (inlineSize === void 0) { inlineSize = 0; }

This simple change makes the library compatible with Node.js environments by setting IE to false when in a non-browser context, which is a reasonable default since IE detection is only needed for client-side rendering.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions