#WebSocket is undefined in SolidJS component

6 messages · Page 1 of 1 (latest)

blissful orchid
#

If you create a solidjs component where you define the WebSocket in the body of a function, AstroJS (or more specifically NodeJS) complains that WebSocket is undefined.

const Demo: Component = () => {
  const ws = new WebSocket("ws://localhost:8080"); // error: WebSocket is not defined
  ...
}

However, you can get it to build properly when you define the websocket within the onMount function:

const Demo: Component = () => {
  let ws: WebSocket; // not an issue with the language server

  onMount(() => {
    ws = new WebSocket("ws://localhost:8080"); // no error
    ...
   });
}

Why is the context inside the body of the component function considered to be NodeJS but is a browser inside the component methods? Is this a problem with how the components hydrate?

Issue happens when I run both yarn run dev and visit the page or when I run yarn run build. Here is the build error:

 error   WebSocket is not defined
  File:
    /home/joemoe/path/to/my/project/node_modules/solid-js/dist/server.js:349:15
  Code:
    348 |     setHydrateContext(nextHydrateContext());
    > 349 |     const r = Comp(props || {});
          |               ^
      350 |     setHydrateContext(c);
      351 |     return r;
      352 |   }

AstroJS version: 3.2.3
SolidJS version: 1.4.3

I will test again once I have time to update those packages.

nimble berry
#

I believe It's because the WebSocket global isn't available yet in Node

#

When using it in onMount it's only run on the browser

#

Otherwise it would also run in the server when not using the client:only directive

blissful orchid
#

But the code is supposed to be run in the browser only. Thats how SolidJS works. There is no server specific code here so I don't really understand why the component is being run under both contexts.

I guess I am confused how AstroJS and SolidJS work together.

nimble berry
#

Astro does SSR of solid components when you're not using client:only using https://www.solidjs.com/docs/latest/api#rendertostringasync (or similar I'm not sure)
So client side rendering isn't the only story for solid 😄

Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.