Unverified Commit fd438464 authored by Artem Zakharchenko's avatar Artem Zakharchenko Committed by GitHub

fix(node-environment-baseline): define `WebSocket` as configurable property (#72079)

## What

The way Next.js re-defines a global `WebSocket` property makes it
non-configurable. No other agents, such as API mocking libraries, are
able to re-defined it. This [causes
issues](https://github.com/mswjs/msw/issues/2339) for Next.js users.

# Why

Because the way the `WebSocket` property descriptor is set in Next.js
doesn't allow that property to be configured anymore (and neither does
it have a setter):


https://github.com/vercel/next.js/blob/de4f197e2fde19526ee019fbebb068e962b58fc0/packages/next/src/server/node-environment-baseline.ts#L11-L15

## How

This can be solved by setting `configurable: true` on the object
descriptor.

Generally, I'd advise against such restrictive descriptors for globals
Next.js doesn't own, like fetch or WebSocket. Try adhering to how such
globals are defined in Node.js—configurable and often with setters:

```
> Object.getOwnPropertyDescriptor(global, 'WebSocket')
{
  get: [Function: get WebSocket],
  set: [Function: set WebSocket],
  enumerable: false,
  configurable: true
}
```
parent d85e2ae0
...@@ -9,8 +9,16 @@ if (typeof (globalThis as any).AsyncLocalStorage !== 'function') { ...@@ -9,8 +9,16 @@ if (typeof (globalThis as any).AsyncLocalStorage !== 'function') {
if (typeof (globalThis as any).WebSocket !== 'function') { if (typeof (globalThis as any).WebSocket !== 'function') {
Object.defineProperty(globalThis, 'WebSocket', { Object.defineProperty(globalThis, 'WebSocket', {
configurable: true,
get() { get() {
return require('next/dist/compiled/ws').WebSocket return require('next/dist/compiled/ws').WebSocket
}, },
set(value) {
Object.defineProperty(globalThis, 'WebSocket', {
configurable: true,
writable: true,
value,
})
},
}) })
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment