Packages

@surfjs/svelte

Svelte stores and actions for Surf — local commands, reactive state, and Surf Live

@surfjs/svelte

Svelte integration for Surf, wrapping @surfjs/web. Register local command handlers, sync state via stores, and connect to Surf Live. Supports Svelte 4 and 5.

Installation#

bash
npm install @surfjs/svelte

@surfjs/web is included as a dependency — no separate install needed.

surfCommands

Register local handlers that execute in the browser:

svelte
<script>
import { surfCommands } from '@surfjs/svelte'
 
surfCommands({
'theme.toggle': {
mode: 'local',
run: () => {
document.documentElement.classList.toggle('dark')
return { ok: true }
}
},
'canvas.clear': {
mode: 'local',
run: () => {
canvasStore.clear()
return { ok: true }
}
}
})
</script>

Handlers are registered immediately and cleaned up via onDestroy.

surfState

Reactive Svelte store synced from Surf Live events:

svelte
<script>
import { surfState } from '@surfjs/svelte'
 
const metrics = surfState('metrics', { users: 0, events: 0 })
</script>
 
<div>Online: {$metrics.users}</div>

Returns a Svelte writable store that auto-updates when the server sends surf:state or surf:patch events for the given key.

surfExecute

Convenience wrapper around window.surf.execute():

svelte
<script>
import { surfExecute } from '@surfjs/svelte'
 
async function search(query) {
const result = await surfExecute('search', { query })
console.log(result)
}
</script>

Context API#

For apps using Surf Live, set up the provider context:

svelte
<!-- App.svelte -->
<script>
import { createSurfProvider, setSurfContext } from '@surfjs/svelte'
 
const provider = createSurfProvider({
url: 'wss://myapp.com/surf/ws',
endpoint: 'https://myapp.com',
})
 
setSurfContext(provider)
</script>
 
<slot />

Then access it in child components:

svelte
<script>
import { getSurfContext } from '@surfjs/svelte'
 
const { execute, connected } = getSurfContext()
</script>

| Option | Type | Description | |--------|------|-------------| | url | string | WebSocket URL for Surf Live | | endpoint | string? | Server URL for HTTP fallback | | auth | string? | Auth token | | channels | string[]? | Surf Live channels to subscribe to |