superjson icon indicating copy to clipboard operation
superjson copied to clipboard

fix: Prevent crash when global URL constructor is not defined

Open wearzdk opened this issue 6 months ago • 3 comments

The Problem

Currently, superjson's internal isURL check (payload instanceof URL) will throw a TypeError: Right-hand side of 'instanceof' is not an object in JavaScript environments where the global URL constructor is not available.

This issue occurs in environments like:

  • WeChat Mini Programs
  • Other non-standard JavaScript runtimes

This prevents users in these growing ecosystems from using superjson without applying workarounds like global polyfills or custom configuration overrides.

The Solution

This PR adds a guard clause (typeof URL !== 'undefined') before the instanceof check. By leveraging short-circuiting, this ensures that instanceof URL is only evaluated when the URL constructor actually exists.

  • In standard environments (Browsers, Node.js): The behavior is completely unchanged.
  • In environments without URL: The check now correctly and safely returns false instead of crashing.

This is a minimal, non-breaking change that significantly improves the library's robustness and compatibility.

wearzdk avatar Sep 02 '25 06:09 wearzdk

Hi, I've just added a test following your suggestion to simulate an environment without URL. It no longer throws errors now. Looking forward to your review!

wearzdk avatar Sep 02 '25 13:09 wearzdk

uh-oh, could you take a look at the linter?

Skn0tt avatar Sep 02 '25 13:09 Skn0tt

Okay, I've fixed the lint issues.

wearzdk avatar Sep 03 '25 03:09 wearzdk