Search code examples
javascriptstompsveltekit

STOMP WebSocket with Svelte


I'm having trouble with trying to get the stomp client to work with SvelteKit, because of "WebSocket not defined" error. From a bit of research, this seems to because of how Node is involved, but I can't find any help on how to either stop Node from trying to process the module, or get some kind of polyfil so that it will load. Any suggestions?

<script lang="ts">
  import * as Stomp from 'stompjs';
  ...
  const client = Stomp.client(url);
  client.connect(headers, () => { console.log('connected'); })

Getting the error message:

9:17:24 am [vite] page reload src/routes/index.svelte (x5)
WebSocket is not defined
ReferenceError: WebSocket is not defined

Solution

  • Hi I have the same problem and after googled I found a solution:

    WebSocket is a client side specific feature, you have to make sure this code is only executed in the browser (by default the script part is executed both on server and client)

    I wrote my code in onMount and that work's

    <script>
    import { onMount } from 'svelte';
    
    onMount(() => {
        const client = new WebSocket('wss://localhost:5001/rpc');
        //some I/O stuff
    })
    </script>
    

    Source: https://stackoverflow.com/a/69160015/1067045