How to access websocket in svelte?

Viewed 2956
<script>
    const socket = new WebSocket("ws://localhost:8000/chat")
    socket.addEventListener("open", ()=> {
        console.log("Opened")
    })


</script>

I am trying to connect my svelte to my fastapi backend but I am getting this error using svelte kit. I get

WebSocket is not defined
ReferenceError: WebSocket is not defined

error.

How can I fix it ?

1 Answers

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)

You can do the following

let socket
onMount(() => {
  socket = new WebSocket("ws://localhost:8000/chat")
  socket.addEventListener("open", ()=> {
    console.log("Opened")
  })
})

the onMount is only run in the browser so this would be the ideal place to add this code, remember to clean up listeners on destroy if necessary.

Related