Code Converter

See how your existing realtime code translates to svelte-realtime.

Before

// Server (server.js) const io = require('socket.io')(server); let history = []; io.on('connection', (socket) => { socket.emit('history', history); socket.on('sendMessage', ({ text }) => { const msg = { id: Date.now(), text }; history.push(msg); io.emit('newMessage', msg); }); }); // Client const socket = io(); socket.on('history', (msgs) => { messages = msgs; }); socket.emit('sendMessage', { text: 'hello' }); socket.on('newMessage', (msg) => { messages = [...messages, msg]; });

Server src/live/*.ts

import { live } from 'svelte-realtime/server'; let history = []; export const sendMessage = live((ctx, { text }) => { const msg = { id: Date.now(), text }; history.push(msg); ctx.publish('chat', 'created', msg); }); export const messages = live.stream('chat', () => history, { merge: 'crud' });

Client +page.svelte

<script> import { messages, sendMessage } from '$live/chat'; </script> <button onclick={() => sendMessage({ text: 'hello' })}> Send </button> {#each $messages ?? [] as msg} <p>{msg.text}</p> {/each}

For a complete walkthrough, see the full Socket.io migration guide.

Was this page helpful?