This is a small websocket plugin for SvelteKit. It uses ws under the hood.
pnpm i @ubermanu/sveltekit-websocket -D
Use the patched node-adapter
in svelte.config.js
:
import adapter from '@ubermanu/sveltekit-websocket'
const config = {
kit: {
adapter: adapter(),
},
}
export default config
Use the websocket dev server in vite.config.js
:
import { sveltekit } from '@sveltejs/kit/vite'
import { websocket } from '@ubermanu/sveltekit-websocket/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [sveltekit(), websocket()],
})
Create your websocket handler in src/hooks.server.js
:
/** @type {import('@ubermanu/sveltekit-websocket').HandleWebsocket} */
export function handleWebsocket({ socket }) {
socket.on('message', () => {
socket.send('something')
})
}
Connect to the endpoint using any websocket client:
<script>
import { browser } from '$app/environment'
import { page } from '$app/state'
const socket = browser ? new WebSocket(`ws://${page.url.host}`) : null
let connected = $state(false)
socket?.addEventListener('open', () => (connected = true))
socket?.addEventListener('close', () => (connected = false))
</script>
<p>
Websocket connection status: {connected ? '🟢' : '🔴'}
</p>