Package Exports
- sveltesocket
- sveltesocket/server
Readme
SvelteSocket
Real-time library for SvelteKit inspired by Laravel Livewire/Echo. Enable automatic UI updates across pages and components with WebSocket or Server-Sent Events.
✨ Features
- 🚀 Real-time UI Updates - Components update automatically when data changes
- 🔄 Cross-page Synchronization - Changes on one page reflect instantly on others
- 🌐 Multiple Transports - WebSocket (primary) and SSE (fallback)
- 🎯 Channel-based Broadcasting - Subscribe to specific channels
- ⚡ Svelte Reactive - Native integration with Svelte stores
- 🔧 Auto-reconnection - Handles network interruptions gracefully
- 📱 TypeScript Support - Full type safety
- 🛠️ SvelteKit Integration - Server-side broadcasting hooks
📦 Installation
npm install sveltesocket
# or
pnpm add sveltesocket
# or
bun add sveltesocket
# or
deno add npm:sveltesocket🚀 Quick Start
Client-side Usage
<script>
import { useChannel, useBroadcast } from 'sveltesocket';
// Create reactive store for products
const products = useChannel('products', {
initialValue: []
});
const { broadcast } = useBroadcast();
async function addProduct(name, price) {
await broadcast('products', { name, price }, 'create');
}
</script>
<!-- UI updates automatically -->
{#each $products as product}
<div>{product.name} - ${product.price}</div>
{/each}Server-side Broadcasting (SvelteKit)
// hooks.server.ts
import { createWebSocketHandle } from 'sveltesocket/server';
export const handle = createWebSocketHandle({
path: '/ws',
heartbeat: true
});// +page.server.ts
import { broadcast } from 'sveltesocket/server';
export const actions = {
updateProduct: async ({ request }) => {
const data = await request.formData();
const product = await updateProductInDatabase(data);
// Broadcast to all clients
broadcast({
channel: 'products',
event: 'update',
data: product
});
return { success: true };
}
};📚 API Reference
Composables
useChannel<T>(channel, options?)
Creates a reactive store that auto-updates when messages arrive on the channel.
<script>
const products = useChannel('products', {
initialValue: [],
event: 'update', // optional: filter by event type
transform: (data) => data // optional: transform incoming data
});
</script>useRealtime<T>(channel, options?)
Similar to useChannel but for single values instead of arrays.
<script>
const userCount = useRealtime('stats', {
initialValue: 0,
event: 'user-count'
});
</script>
<p>Online users: {$userCount}</p>useBroadcast()
Returns broadcast function for sending messages.
<script>
const { broadcast } = useBroadcast();
async function sendMessage() {
await broadcast('chat', { text: 'Hello!' });
}
</script>usePresence(channel)
Track online users in a channel.
<script>
const onlineUsers = usePresence('chat-room');
</script>
<p>Online: {$onlineUsers.size} users</p>Server-side Functions
broadcast(options)
Broadcast messages from server actions/loaders.
import { broadcast } from 'sveltesocket';
broadcast({
channel: 'products',
event: 'update',
data: updatedProduct
});createWebSocketHandle(options)
Set up WebSocket server in SvelteKit hooks.
// hooks.server.ts
import { createWebSocketHandle } from 'sveltesocket';
export const handle = createWebSocketHandle({
path: '/ws',
heartbeat: true,
heartbeatInterval: 30000
});🔧 Configuration
Client Configuration
<script>
import { useSvelteSocket } from 'sveltesocket';
// Configure socket connection
const socket = useSvelteSocket({
url: 'ws://localhost:3000/ws',
transport: 'websocket', // 'websocket' | 'sse'
transports: ['websocket', 'sse'], // fallback order
autoConnect: true,
debug: false
});
</script>Transport Types
- WebSocket: Full-duplex, best for real-time bidirectional communication
- SSE: Server-sent events, simpler, good for server-to-client updates only
🎯 Use Cases
Real-time Dashboard
<script>
const metrics = useChannel('dashboard-metrics');
</script>
<div>Active users: {$metrics.activeUsers}</div>
<div>Revenue: ${$metrics.revenue}</div>Live Chat
<script>
const messages = useChannel('chat');
const onlineUsers = usePresence('chat');
</script>
<!-- Messages update in real-time -->
{#each $messages as msg}
<div>{msg.user}: {msg.text}</div>
{/each}Collaborative Editing
<script>
const document = useRealtime('doc-123');
</script>
<textarea bind:value={$document.content}></textarea>🔄 Message Events
The library handles these standard events automatically:
create- Add item to arrayupdate- Update existing itemdelete- Remove item from arrayreplace- Replace entire array
Custom events work too:
broadcast({ channel: 'notifications', event: 'new-message', data: message });🚀 Development
# Install dependencies
npm install
# Start dev server
npm run dev
# Build library
npm run build
# Run tests
npm test📄 License
MIT
🤝 Contributing
Contributions welcome! Please feel free to submit a Pull Request.