10
<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 ?

yawad
  • 123
  • 1
  • 6

2 Answers2

11

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.

Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41
5

SvelteKit uses SSR (Server Side Rendering) for the initial load, resulting in your issue. "onMount" works fine, but is only available in components.

This solution is works in more situations:

<script>
import {browser} from '$app/environment';

if (browser) {
    const socket = new WebSocket("ws://localhost:8000/chat")
    socket.addEventListener("open", ()=> {
        console.log("Opened")
    })
}
</script>
Frik
  • 486
  • 6
  • 8