svelte-adapter-uws 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,1543 @@
1
+ # svelte-adapter-uws
2
+
3
+ A SvelteKit adapter powered by [uWebSockets.js](https://github.com/uNetworking/uWebSockets.js) - the fastest HTTP/WebSocket server available for Node.js, written in C++ and exposed through V8.
4
+
5
+ I've been loving Svelte and SvelteKit for a long time. I always wanted to expand on the standard adapters, sifting through the internet from time to time, never finding what I was searching for - a proper high-performance adapter with first-class WebSocket support, native TLS, pub/sub built in, and a client library that just works. So I'm doing it myself.
6
+
7
+ ## What you get
8
+
9
+ - **HTTP & HTTPS** - native TLS via uWebSockets.js `SSLApp`, no reverse proxy needed
10
+ - **WebSocket & WSS** - built-in pub/sub with a reactive Svelte client store
11
+ - **In-memory static file cache** - assets loaded once at startup, served from RAM with precompressed brotli/gzip variants
12
+ - **Backpressure handling** - streaming responses that won't blow up memory
13
+ - **Graceful shutdown** - waits for in-flight requests before exiting
14
+ - **Health check endpoint** - `/healthz` out of the box
15
+ - **Zero-config WebSocket** - just set `websocket: true` and go
16
+
17
+ ---
18
+
19
+ ## Table of contents
20
+
21
+ - [Installation](#installation)
22
+ - [Quick start: HTTP](#quick-start-http)
23
+ - [Quick start: HTTPS](#quick-start-https)
24
+ - [Quick start: WebSocket](#quick-start-websocket)
25
+ - [Quick start: WSS (secure WebSocket)](#quick-start-wss-secure-websocket)
26
+ - [Development, Preview & Production](#development-preview--production)
27
+ - [Adapter options](#adapter-options)
28
+ - [Environment variables](#environment-variables)
29
+ - [WebSocket handler (`hooks.ws`)](#websocket-handler-hooksws)
30
+ - [Authentication](#authentication)
31
+ - [Platform API (`event.platform`)](#platform-api-eventplatform)
32
+ - [Client store API](#client-store-api)
33
+ - [TypeScript setup](#typescript-setup)
34
+ - [Svelte 4 support](#svelte-4-support)
35
+ - [Deploying with Docker](#deploying-with-docker)
36
+ - [Clustering (Linux)](#clustering-linux)
37
+ - [Performance](#performance)
38
+ - [Troubleshooting](#troubleshooting)
39
+ - [License](#license)
40
+
41
+ ---
42
+
43
+ ## Installation
44
+
45
+ ### Starting from scratch
46
+
47
+ If you don't have a SvelteKit project yet:
48
+
49
+ ```bash
50
+ npx sv create my-app
51
+ cd my-app
52
+ npm install
53
+ ```
54
+
55
+ ### Adding the adapter
56
+
57
+ ```bash
58
+ npm install svelte-adapter-uws
59
+ npm install uNetworking/uWebSockets.js#v20.60.0
60
+ ```
61
+
62
+ > **Note:** uWebSockets.js is a native C++ addon installed directly from GitHub, not from npm. It may not compile on all platforms. Check the [uWebSockets.js README](https://github.com/uNetworking/uWebSockets.js) if you have issues.
63
+
64
+ If you plan to use WebSockets during development, also install `ws`:
65
+
66
+ ```bash
67
+ npm install -D ws
68
+ ```
69
+
70
+ ---
71
+
72
+ ## Quick start: HTTP
73
+
74
+ The simplest setup - just swap the adapter and you're done.
75
+
76
+ **svelte.config.js**
77
+ ```js
78
+ import adapter from 'svelte-adapter-uws';
79
+
80
+ export default {
81
+ kit: {
82
+ adapter: adapter()
83
+ }
84
+ };
85
+ ```
86
+
87
+ **Build and run:**
88
+ ```bash
89
+ npm run build
90
+ node build
91
+ ```
92
+
93
+ Your app is now running on `http://localhost:3000`.
94
+
95
+ To change the host or port:
96
+ ```bash
97
+ HOST=0.0.0.0 PORT=8080 node build
98
+ ```
99
+
100
+ ---
101
+
102
+ ## Quick start: HTTPS
103
+
104
+ No reverse proxy needed. uWebSockets.js handles TLS natively with its `SSLApp`.
105
+
106
+ **svelte.config.js** - same as HTTP, no changes needed:
107
+ ```js
108
+ import adapter from 'svelte-adapter-uws';
109
+
110
+ export default {
111
+ kit: {
112
+ adapter: adapter()
113
+ }
114
+ };
115
+ ```
116
+
117
+ **Build and run with TLS:**
118
+ ```bash
119
+ npm run build
120
+ SSL_CERT=/path/to/cert.pem SSL_KEY=/path/to/key.pem node build
121
+ ```
122
+
123
+ Your app is now running on `https://localhost:3000`.
124
+
125
+ > Both `SSL_CERT` and `SSL_KEY` must be set. Setting only one will throw an error.
126
+
127
+ ### Behind a reverse proxy (nginx, Caddy, etc.)
128
+
129
+ If your proxy terminates TLS and forwards to HTTP:
130
+
131
+ ```bash
132
+ ORIGIN=https://example.com node build
133
+ ```
134
+
135
+ Or if you want flexible header-based detection:
136
+ ```bash
137
+ PROTOCOL_HEADER=x-forwarded-proto HOST_HEADER=x-forwarded-host node build
138
+ ```
139
+
140
+ ---
141
+
142
+ ## Quick start: WebSocket
143
+
144
+ Three things to do:
145
+
146
+ 1. **Enable WebSocket in the adapter**
147
+ 2. **Add the Vite plugin** (for dev mode)
148
+ 3. **Use the client store** in your Svelte components
149
+
150
+ ### Step 1: Enable WebSocket
151
+
152
+ **svelte.config.js**
153
+ ```js
154
+ import adapter from 'svelte-adapter-uws';
155
+
156
+ export default {
157
+ kit: {
158
+ adapter: adapter({
159
+ websocket: true
160
+ })
161
+ }
162
+ };
163
+ ```
164
+
165
+ That's it. This gives you a pub/sub WebSocket server at `/ws` with no authentication. Any client can connect, subscribe to topics, and receive messages.
166
+
167
+ ### Step 2: Add the Vite plugin
168
+
169
+ This makes WebSockets work during `npm run dev`. Without this, `event.platform` won't have WebSocket methods in dev mode.
170
+
171
+ **vite.config.js**
172
+ ```js
173
+ import { sveltekit } from '@sveltejs/kit/vite';
174
+ import uwsDev from 'svelte-adapter-uws/vite';
175
+
176
+ export default {
177
+ plugins: [sveltekit(), uwsDev()]
178
+ };
179
+ ```
180
+
181
+ ### Step 3: Use the client store
182
+
183
+ **src/routes/+page.svelte**
184
+ ```svelte
185
+ <script>
186
+ import { on, status } from 'svelte-adapter-uws/client';
187
+
188
+ // Subscribe to the 'notifications' topic
189
+ // Auto-connects, auto-subscribes, auto-reconnects
190
+ const notifications = on('notifications');
191
+ </script>
192
+
193
+ {#if $status === 'open'}
194
+ <span>Connected</span>
195
+ {/if}
196
+
197
+ {#if $notifications}
198
+ <p>Event: {$notifications.event}</p>
199
+ <p>Data: {JSON.stringify($notifications.data)}</p>
200
+ {/if}
201
+ ```
202
+
203
+ ### Step 4: Publish from the server
204
+
205
+ **src/routes/api/notify/+server.js**
206
+ ```js
207
+ export async function POST({ request, platform }) {
208
+ const data = await request.json();
209
+
210
+ // This sends to ALL clients subscribed to 'notifications'
211
+ platform.publish('notifications', 'new-message', data);
212
+
213
+ return new Response('OK');
214
+ }
215
+ ```
216
+
217
+ **Build and run:**
218
+ ```bash
219
+ npm run build
220
+ node build
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Quick start: WSS (secure WebSocket)
226
+
227
+ WSS works automatically when you enable TLS. WebSocket connections upgrade over the same HTTPS port.
228
+
229
+ **svelte.config.js**
230
+ ```js
231
+ import adapter from 'svelte-adapter-uws';
232
+
233
+ export default {
234
+ kit: {
235
+ adapter: adapter({
236
+ websocket: true
237
+ })
238
+ }
239
+ };
240
+ ```
241
+
242
+ ```bash
243
+ npm run build
244
+ SSL_CERT=/path/to/cert.pem SSL_KEY=/path/to/key.pem node build
245
+ ```
246
+
247
+ The client store automatically uses `wss://` when the page is served over HTTPS - no configuration needed on the client side.
248
+
249
+ ---
250
+
251
+ ## Development, Preview & Production
252
+
253
+ ### `npm run dev` - works (with the Vite plugin)
254
+
255
+ Development works as expected. The Vite plugin (`svelte-adapter-uws/vite`) spins up a `ws` WebSocket server alongside Vite's dev server, so your client store and `event.platform` work identically to production.
256
+
257
+ **vite.config.js**
258
+ ```js
259
+ import { sveltekit } from '@sveltejs/kit/vite';
260
+ import uwsDev from 'svelte-adapter-uws/vite';
261
+
262
+ export default {
263
+ plugins: [sveltekit(), uwsDev()]
264
+ };
265
+ ```
266
+
267
+ Without the Vite plugin:
268
+ - HTTP routes work fine
269
+ - `event.platform` is `undefined` - any code calling `platform.publish()` will throw
270
+ - The client store will try to connect to `/ws` and fail silently (auto-reconnect will keep trying)
271
+
272
+ ### `npm run preview` - WebSockets don't work
273
+
274
+ SvelteKit's preview server is Vite's built-in HTTP server. It doesn't know about uWebSockets.js or WebSocket upgrades. Your HTTP routes and SSR will work, but **WebSocket connections will fail**.
275
+
276
+ Use `node build` instead of preview for testing WebSocket features.
277
+
278
+ ### `node build` - production, everything works
279
+
280
+ This is the real deal. uWebSockets.js handles everything:
281
+
282
+ ```bash
283
+ npm run build
284
+ node build
285
+ ```
286
+
287
+ Or with environment variables:
288
+ ```bash
289
+ PORT=8080 HOST=0.0.0.0 node build
290
+ ```
291
+
292
+ Or with TLS:
293
+ ```bash
294
+ SSL_CERT=./cert.pem SSL_KEY=./key.pem PORT=443 node build
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Adapter options
300
+
301
+ ```js
302
+ adapter({
303
+ // Output directory for the build
304
+ out: 'build', // default: 'build'
305
+
306
+ // Precompress static assets with brotli and gzip
307
+ precompress: true, // default: true
308
+
309
+ // Prefix for environment variables (e.g. 'MY_APP_' → MY_APP_PORT)
310
+ envPrefix: '', // default: ''
311
+
312
+ // Health check endpoint (set to false to disable)
313
+ healthCheckPath: '/healthz', // default: '/healthz'
314
+
315
+ // WebSocket configuration
316
+ websocket: true // or false, or an options object (see below)
317
+ })
318
+ ```
319
+
320
+ ### WebSocket options
321
+
322
+ ```js
323
+ adapter({
324
+ websocket: {
325
+ // Path for WebSocket connections
326
+ path: '/ws', // default: '/ws'
327
+
328
+ // Path to your custom handler module (auto-discovers src/hooks.ws.js if omitted)
329
+ handler: './src/lib/server/websocket.js', // default: auto-discover
330
+
331
+ // Max message size in bytes (connections sending larger messages are closed)
332
+ maxPayloadLength: 16 * 1024, // default: 16 KB
333
+
334
+ // Seconds of inactivity before the connection is closed
335
+ idleTimeout: 120, // default: 120
336
+
337
+ // Max bytes of backpressure before messages are dropped
338
+ maxBackpressure: 1024 * 1024, // default: 1 MB
339
+
340
+ // Enable per-message deflate compression
341
+ compression: false, // default: false
342
+
343
+ // Automatically send pings to keep the connection alive
344
+ sendPingsAutomatically: true, // default: true
345
+
346
+ // Allowed origins for WebSocket connections
347
+ // 'same-origin' - only accept where Origin matches Host (default)
348
+ // '*' - accept from any origin
349
+ // ['https://example.com'] - whitelist specific origins
350
+ allowedOrigins: 'same-origin' // default: 'same-origin'
351
+ }
352
+ })
353
+ ```
354
+
355
+ ---
356
+
357
+ ## Environment variables
358
+
359
+ All variables are set at **runtime** (when you run `node build`), not at build time.
360
+
361
+ If you set `envPrefix: 'MY_APP_'` in the adapter config, all variables are prefixed (e.g. `MY_APP_PORT` instead of `PORT`).
362
+
363
+ | Variable | Default | Description |
364
+ |---|---|---|
365
+ | `HOST` | `0.0.0.0` | Bind address |
366
+ | `PORT` | `3000` | Listen port |
367
+ | `ORIGIN` | *(derived)* | Fixed origin (e.g. `https://example.com`) |
368
+ | `SSL_CERT` | - | Path to TLS certificate file |
369
+ | `SSL_KEY` | - | Path to TLS private key file |
370
+ | `PROTOCOL_HEADER` | - | Header for protocol detection (e.g. `x-forwarded-proto`) |
371
+ | `HOST_HEADER` | - | Header for host detection (e.g. `x-forwarded-host`) |
372
+ | `PORT_HEADER` | - | Header for port override (e.g. `x-forwarded-port`) |
373
+ | `ADDRESS_HEADER` | - | Header for client IP (e.g. `x-forwarded-for`) |
374
+ | `XFF_DEPTH` | `1` | Position from right in `X-Forwarded-For` |
375
+ | `BODY_SIZE_LIMIT` | `512K` | Max request body size (supports `K`, `M`, `G` suffixes) |
376
+ | `SHUTDOWN_TIMEOUT` | `30` | Seconds to wait during graceful shutdown |
377
+ | `CLUSTER_WORKERS` | - | Number of worker processes (or `auto` for CPU count). Linux only, HTTP only |
378
+
379
+ ### Graceful shutdown
380
+
381
+ On `SIGTERM` or `SIGINT`, the server:
382
+ 1. Stops accepting new connections
383
+ 2. Emits a `sveltekit:shutdown` event on `process` (for cleanup hooks like closing database connections)
384
+ 3. Waits for in-flight SSR requests to complete (up to `SHUTDOWN_TIMEOUT` seconds)
385
+ 4. Exits
386
+
387
+ ```js
388
+ // Listen for shutdown in your server code (e.g. hooks.server.js)
389
+ process.on('sveltekit:shutdown', async (reason) => {
390
+ console.log(`Shutting down: ${reason}`);
391
+ await db.close();
392
+ });
393
+ ```
394
+
395
+ ### Examples
396
+
397
+ ```bash
398
+ # Simple HTTP
399
+ node build
400
+
401
+ # Custom port
402
+ PORT=8080 node build
403
+
404
+ # Behind nginx
405
+ ORIGIN=https://example.com node build
406
+
407
+ # Behind a proxy with forwarded headers
408
+ PROTOCOL_HEADER=x-forwarded-proto HOST_HEADER=x-forwarded-host ADDRESS_HEADER=x-forwarded-for node build
409
+
410
+ # Native TLS
411
+ SSL_CERT=./cert.pem SSL_KEY=./key.pem node build
412
+
413
+ # Everything at once
414
+ SSL_CERT=./cert.pem SSL_KEY=./key.pem PORT=443 HOST=0.0.0.0 BODY_SIZE_LIMIT=10M SHUTDOWN_TIMEOUT=60 node build
415
+ ```
416
+
417
+ ---
418
+
419
+ ## WebSocket handler (`hooks.ws`)
420
+
421
+ ### No handler needed (simplest)
422
+
423
+ With `websocket: true`, a built-in handler accepts all connections and handles subscribe/unsubscribe messages from the client store. No file needed.
424
+
425
+ > **Note:** `websocket: true` only sets up the server side. To actually receive messages in the browser, you need to import the client store (`on`, `crud`, etc.) in your Svelte components. Without the client store, the WebSocket endpoint exists but nothing connects to it.
426
+
427
+ ### Auto-discovered handler
428
+
429
+ Create `src/hooks.ws.js` (or `.ts`, `.mjs`) and it will be automatically discovered - no config needed:
430
+
431
+ **src/hooks.ws.js**
432
+ ```js
433
+ // Called during the HTTP → WebSocket upgrade handshake.
434
+ // Return an object to accept (becomes ws.getUserData()).
435
+ // Return false to reject with 401.
436
+ // Omit this export to accept all connections.
437
+ export async function upgrade({ headers, cookies, url, remoteAddress }) {
438
+ const sessionId = cookies.session_id;
439
+ if (!sessionId) return false;
440
+
441
+ const user = await validateSession(sessionId);
442
+ if (!user) return false;
443
+
444
+ // Whatever you return here is available as ws.getUserData()
445
+ return { userId: user.id, name: user.name };
446
+ }
447
+
448
+ // Called when a connection is established
449
+ export function open(ws) {
450
+ const { userId } = ws.getUserData();
451
+ console.log(`User ${userId} connected`);
452
+
453
+ // Subscribe this connection to a user-specific topic
454
+ ws.subscribe(`user:${userId}`);
455
+ }
456
+
457
+ // Called when a message is received
458
+ // Note: subscribe/unsubscribe messages from the client store are
459
+ // handled automatically BEFORE this function is called
460
+ export function message(ws, data, isBinary) {
461
+ const msg = JSON.parse(Buffer.from(data).toString());
462
+ console.log('Got message:', msg);
463
+ }
464
+
465
+ // Called when a client tries to subscribe to a topic (optional)
466
+ // Return false to deny the subscription
467
+ export function subscribe(ws, topic) {
468
+ const { role } = ws.getUserData();
469
+ // Only admins can subscribe to admin topics
470
+ if (topic.startsWith('admin') && role !== 'admin') return false;
471
+ }
472
+
473
+ // Called when the connection closes
474
+ export function close(ws, code, message) {
475
+ const { userId } = ws.getUserData();
476
+ console.log(`User ${userId} disconnected`);
477
+ }
478
+
479
+ // Called when backpressure has drained (optional, for flow control)
480
+ export function drain(ws) {
481
+ // You can resume sending large messages here
482
+ }
483
+ ```
484
+
485
+ ### Explicit handler path
486
+
487
+ If your handler is somewhere other than `src/hooks.ws.js`:
488
+
489
+ ```js
490
+ adapter({
491
+ websocket: {
492
+ handler: './src/lib/server/websocket.js'
493
+ }
494
+ })
495
+ ```
496
+
497
+ ### What the handler gets
498
+
499
+ The `upgrade` function receives an `UpgradeContext`:
500
+
501
+ ```js
502
+ {
503
+ headers: { 'cookie': '...', 'host': 'localhost:3000', ... }, // all lowercase
504
+ cookies: { session_id: 'abc123', theme: 'dark' }, // parsed from Cookie header
505
+ url: '/ws', // request path
506
+ remoteAddress: '127.0.0.1' // client IP
507
+ }
508
+ ```
509
+
510
+ The `subscribe` function receives `(ws, topic)` and can return `false` to deny a client's subscription request. Omit it to allow all subscriptions.
511
+
512
+ The `ws` object in `open`, `message`, `close`, and `drain` is a [uWebSockets.js WebSocket](https://github.com/uNetworking/uWebSockets.js). Key methods:
513
+
514
+ - `ws.getUserData()` - returns whatever `upgrade` returned
515
+ - `ws.subscribe(topic)` - subscribe to a topic for `app.publish()`
516
+ - `ws.unsubscribe(topic)` - unsubscribe from a topic
517
+ - `ws.send(data)` - send a message to this connection
518
+ - `ws.close()` - close the connection
519
+
520
+ ---
521
+
522
+ ## Authentication
523
+
524
+ WebSocket authentication uses the exact same cookies as your SvelteKit app. When the browser opens a WebSocket connection, it sends all cookies for the domain - including session cookies set by SvelteKit's `cookies.set()`. No tokens, no query parameters, no extra client-side code.
525
+
526
+ Here's the full flow from login to authenticated WebSocket:
527
+
528
+ ### Step 1: Login sets a cookie (standard SvelteKit)
529
+
530
+ **src/routes/login/+page.server.js**
531
+ ```js
532
+ import { authenticate, createSession } from '$lib/server/auth.js';
533
+
534
+ export const actions = {
535
+ default: async ({ request, cookies }) => {
536
+ const form = await request.formData();
537
+ const email = form.get('email');
538
+ const password = form.get('password');
539
+
540
+ const user = await authenticate(email, password);
541
+ if (!user) return { error: 'Invalid credentials' };
542
+
543
+ const sessionId = await createSession(user.id);
544
+
545
+ // This cookie is automatically sent on WebSocket upgrade requests
546
+ cookies.set('session', sessionId, {
547
+ path: '/',
548
+ httpOnly: true,
549
+ sameSite: 'strict',
550
+ secure: true,
551
+ maxAge: 60 * 60 * 24 * 7 // 1 week
552
+ });
553
+
554
+ return { success: true };
555
+ }
556
+ };
557
+ ```
558
+
559
+ ### Step 2: WebSocket handler reads the same cookie
560
+
561
+ **src/hooks.ws.js**
562
+ ```js
563
+ import { getSession } from '$lib/server/auth.js';
564
+
565
+ export async function upgrade({ cookies }) {
566
+ // Same cookie that SvelteKit set during login
567
+ const sessionId = cookies.session;
568
+ if (!sessionId) return false; // → 401, connection rejected
569
+
570
+ const user = await getSession(sessionId);
571
+ if (!user) return false; // → 401, expired or invalid session
572
+
573
+ // Attach user data to the socket - available via ws.getUserData()
574
+ return { userId: user.id, name: user.name, role: user.role };
575
+ }
576
+
577
+ export function open(ws) {
578
+ const { userId, role } = ws.getUserData();
579
+ console.log(`${userId} connected (${role})`);
580
+
581
+ // Subscribe to user-specific and role-based topics
582
+ ws.subscribe(`user:${userId}`);
583
+ if (role === 'admin') ws.subscribe('admin');
584
+ }
585
+
586
+ export function close(ws) {
587
+ const { userId } = ws.getUserData();
588
+ console.log(`${userId} disconnected`);
589
+ }
590
+ ```
591
+
592
+ ### Step 3: Client - nothing special needed
593
+
594
+ **src/routes/dashboard/+page.svelte**
595
+ ```svelte
596
+ <script>
597
+ import { on, status } from 'svelte-adapter-uws/client';
598
+
599
+ // The browser sends cookies automatically on the upgrade request.
600
+ // If the session is invalid, the connection is rejected and
601
+ // auto-reconnect will retry (useful if the user logs in later).
602
+ const notifications = on('notifications');
603
+ const userMessages = on('user-messages');
604
+ </script>
605
+
606
+ {#if $status === 'open'}
607
+ <span>Authenticated & connected</span>
608
+ {:else if $status === 'connecting'}
609
+ <span>Connecting...</span>
610
+ {:else}
611
+ <span>Disconnected (not logged in?)</span>
612
+ {/if}
613
+ ```
614
+
615
+ ### Step 4: Send messages to specific users from anywhere
616
+
617
+ **src/routes/api/notify/+server.js**
618
+ ```js
619
+ import { json } from '@sveltejs/kit';
620
+
621
+ export async function POST({ request, platform }) {
622
+ const { userId, message } = await request.json();
623
+
624
+ // Only that user receives this (they subscribed in open())
625
+ platform.publish(`user:${userId}`, 'notification', { message });
626
+
627
+ return json({ sent: true });
628
+ }
629
+ ```
630
+
631
+ ### Why this works
632
+
633
+ The WebSocket upgrade is an HTTP request. The browser treats it like any other request to your domain - it includes all cookies, follows the same-origin policy, and respects `httpOnly`/`secure`/`sameSite` flags. There's no difference between how cookies reach a `+page.server.js` load function and how they reach the `upgrade` handler.
634
+
635
+ | What | Where | Same cookies? |
636
+ |---|---|---|
637
+ | Page load | `+page.server.js` `load()` | Yes |
638
+ | Form action | `+page.server.js` `actions` | Yes |
639
+ | API route | `+server.js` | Yes |
640
+ | Server hook | `hooks.server.js` `handle()` | Yes |
641
+ | **WebSocket upgrade** | **`hooks.ws.js` `upgrade()`** | **Yes** |
642
+
643
+ ---
644
+
645
+ ## Platform API (`event.platform`)
646
+
647
+ Available in server hooks, load functions, form actions, and API routes.
648
+
649
+ ### `platform.publish(topic, event, data)`
650
+
651
+ Send a message to all WebSocket clients subscribed to a topic:
652
+
653
+ ```js
654
+ // src/routes/todos/+page.server.js
655
+ export const actions = {
656
+ create: async ({ request, platform }) => {
657
+ const formData = await request.formData();
658
+ const todo = await db.createTodo(formData.get('text'));
659
+
660
+ // Every client subscribed to 'todos' receives this
661
+ platform.publish('todos', 'created', todo);
662
+
663
+ return { success: true };
664
+ }
665
+ };
666
+ ```
667
+
668
+ ### `platform.send(ws, topic, event, data)`
669
+
670
+ Send a message to a single WebSocket connection. Wraps in the same `{ topic, event, data }` envelope as `publish()`.
671
+
672
+ This is useful when you store WebSocket references (e.g. in a `Map`) and need to message specific connections from SvelteKit handlers:
673
+
674
+ ```js
675
+ // src/hooks.ws.js - store connections by user ID
676
+ const userSockets = new Map();
677
+
678
+ export function open(ws) {
679
+ const { userId } = ws.getUserData();
680
+ userSockets.set(userId, ws);
681
+ }
682
+
683
+ export function close(ws) {
684
+ const { userId } = ws.getUserData();
685
+ userSockets.delete(userId);
686
+ }
687
+
688
+ // Export the map so SvelteKit handlers can access it
689
+ export { userSockets };
690
+ ```
691
+
692
+ ```js
693
+ // src/routes/api/dm/+server.js - send to a specific user
694
+ import { userSockets } from '../../hooks.ws.js';
695
+
696
+ export async function POST({ request, platform }) {
697
+ const { targetUserId, message } = await request.json();
698
+ const ws = userSockets.get(targetUserId);
699
+ if (ws) {
700
+ platform.send(ws, 'dm', 'new-message', { message });
701
+ }
702
+ return new Response('OK');
703
+ }
704
+ ```
705
+
706
+ To reply directly from inside `hooks.ws.js` (where `platform` isn't available), use `ws.send()` with the envelope format:
707
+
708
+ ```js
709
+ // src/hooks.ws.js
710
+ export function message(ws, rawData) {
711
+ const msg = JSON.parse(Buffer.from(rawData).toString());
712
+ // Reply to sender using the same envelope format the client store expects
713
+ ws.send(JSON.stringify({ topic: 'echo', event: 'reply', data: { got: msg } }));
714
+ }
715
+ ```
716
+
717
+ ### `platform.sendTo(filter, topic, event, data)`
718
+
719
+ Send a message to all connections whose `userData` matches a filter function. Returns the number of connections the message was sent to.
720
+
721
+ This is simpler than manually maintaining a `Map` of connections - no `hooks.ws.js` needed:
722
+
723
+ ```js
724
+ // src/routes/api/dm/+server.js - send to a specific user
725
+ export async function POST({ request, platform }) {
726
+ const { targetUserId, message } = await request.json();
727
+ const count = platform.sendTo(
728
+ (userData) => userData.userId === targetUserId,
729
+ 'dm', 'new-message', { message }
730
+ );
731
+ return new Response(count > 0 ? 'Sent' : 'User offline');
732
+ }
733
+ ```
734
+
735
+ ```js
736
+ // Send to all admins
737
+ platform.sendTo(
738
+ (userData) => userData.role === 'admin',
739
+ 'alerts', 'warning', { message: 'Server load high' }
740
+ );
741
+ ```
742
+
743
+ ### `platform.connections`
744
+
745
+ Number of active WebSocket connections:
746
+
747
+ ```js
748
+ // src/routes/api/stats/+server.js
749
+ import { json } from '@sveltejs/kit';
750
+
751
+ export async function GET({ platform }) {
752
+ return json({ online: platform.connections });
753
+ }
754
+ ```
755
+
756
+ ### `platform.subscribers(topic)`
757
+
758
+ Number of clients subscribed to a specific topic:
759
+
760
+ ```js
761
+ export async function GET({ platform, params }) {
762
+ return json({
763
+ viewers: platform.subscribers(`page:${params.id}`)
764
+ });
765
+ }
766
+ ```
767
+
768
+ ### `platform.topic(name)` - scoped helper
769
+
770
+ Reduces repetition when publishing multiple events to the same topic:
771
+
772
+ ```js
773
+ // src/routes/todos/+page.server.js
774
+ export const actions = {
775
+ create: async ({ request, platform }) => {
776
+ const todos = platform.topic('todos');
777
+ const todo = await db.create(await request.formData());
778
+ todos.created(todo); // shorthand for platform.publish('todos', 'created', todo)
779
+ },
780
+
781
+ update: async ({ request, platform }) => {
782
+ const todos = platform.topic('todos');
783
+ const todo = await db.update(await request.formData());
784
+ todos.updated(todo);
785
+ },
786
+
787
+ delete: async ({ request, platform }) => {
788
+ const todos = platform.topic('todos');
789
+ const id = (await request.formData()).get('id');
790
+ await db.delete(id);
791
+ todos.deleted({ id });
792
+ }
793
+ };
794
+ ```
795
+
796
+ The topic helper also has counter methods:
797
+
798
+ ```js
799
+ const online = platform.topic('online-users');
800
+ online.set(42); // → { event: 'set', data: 42 }
801
+ online.increment(); // → { event: 'increment', data: 1 }
802
+ online.increment(5); // → { event: 'increment', data: 5 }
803
+ online.decrement(); // → { event: 'decrement', data: 1 }
804
+ ```
805
+
806
+ ---
807
+
808
+ ## Client store API
809
+
810
+ Import from `svelte-adapter-uws/client`. Everything auto-connects - you don't need to call `connect()` first.
811
+
812
+ ### `on(topic)` - subscribe to a topic
813
+
814
+ The main function most users need. Returns a Svelte readable store that updates whenever a message is published to the topic.
815
+
816
+ > **Important:** The store starts as `null` (no message received yet). Always use `{#if $store}` before accessing properties, or you'll get "Cannot read properties of null".
817
+
818
+ ```svelte
819
+ <script>
820
+ import { on } from 'svelte-adapter-uws/client';
821
+
822
+ // Full event envelope: { topic, event, data }
823
+ const todos = on('todos');
824
+ </script>
825
+
826
+ <!-- ALWAYS guard with {#if} - $todos is null until the first message arrives -->
827
+ {#if $todos}
828
+ <p>{$todos.event}: {JSON.stringify($todos.data)}</p>
829
+ {/if}
830
+
831
+ <!-- WRONG - will crash with "Cannot read properties of null" -->
832
+ <!-- <p>{$todos.event}</p> -->
833
+ ```
834
+
835
+ ### `on(topic, event)` - subscribe to a specific event
836
+
837
+ Filters to a single event name and returns just the `data` payload (no envelope):
838
+
839
+ ```svelte
840
+ <script>
841
+ import { on } from 'svelte-adapter-uws/client';
842
+
843
+ // Only 'created' events, gives you just the data
844
+ const newTodo = on('todos', 'created');
845
+ </script>
846
+
847
+ {#if $newTodo}
848
+ <p>New todo: {$newTodo.text}</p>
849
+ {/if}
850
+ ```
851
+
852
+ ### `.scan(initial, reducer)` - accumulate state
853
+
854
+ Like `Array.reduce` but reactive. Each new event feeds through the reducer:
855
+
856
+ ```svelte
857
+ <script>
858
+ import { on } from 'svelte-adapter-uws/client';
859
+
860
+ const todos = on('todos').scan([], (list, { event, data }) => {
861
+ if (event === 'created') return [...list, data];
862
+ if (event === 'updated') return list.map(t => t.id === data.id ? data : t);
863
+ if (event === 'deleted') return list.filter(t => t.id !== data.id);
864
+ return list;
865
+ });
866
+ </script>
867
+
868
+ {#each $todos as todo (todo.id)}
869
+ <p>{todo.text}</p>
870
+ {/each}
871
+ ```
872
+
873
+ ### `crud(topic, initial?, options?)` - live CRUD list
874
+
875
+ One-liner for real-time collections. Handles `created`, `updated`, and `deleted` events automatically:
876
+
877
+ ```svelte
878
+ <script>
879
+ import { crud } from 'svelte-adapter-uws/client';
880
+
881
+ let { data } = $props(); // from +page.server.js load()
882
+
883
+ // $todos auto-updates when server publishes created/updated/deleted
884
+ const todos = crud('todos', data.todos);
885
+ </script>
886
+
887
+ {#each $todos as todo (todo.id)}
888
+ <p>{todo.text}</p>
889
+ {/each}
890
+ ```
891
+
892
+ Options:
893
+ - `key` - property to match items by (default: `'id'`)
894
+ - `prepend` - add new items to the beginning instead of end (default: `false`)
895
+
896
+ ```js
897
+ // Notifications, newest first
898
+ const notifications = crud('notifications', [], { prepend: true });
899
+
900
+ // Items keyed by 'slug' instead of 'id'
901
+ const posts = crud('posts', data.posts, { key: 'slug' });
902
+ ```
903
+
904
+ Pair with `platform.topic()` on the server:
905
+
906
+ ```js
907
+ // Server: +page.server.js
908
+ export const actions = {
909
+ create: async ({ request, platform }) => {
910
+ const todo = await db.create(await request.formData());
911
+ platform.topic('todos').created(todo); // client sees 'created'
912
+ },
913
+ update: async ({ request, platform }) => {
914
+ const todo = await db.update(await request.formData());
915
+ platform.topic('todos').updated(todo); // client sees 'updated'
916
+ },
917
+ delete: async ({ request, platform }) => {
918
+ await db.delete((await request.formData()).get('id'));
919
+ platform.topic('todos').deleted({ id }); // client sees 'deleted'
920
+ }
921
+ };
922
+ ```
923
+
924
+ ### `lookup(topic, initial?, options?)` - live keyed object
925
+
926
+ Like `crud()` but returns a `Record<string, T>` instead of an array. Better for dashboards and fast lookups:
927
+
928
+ ```svelte
929
+ <script>
930
+ import { lookup } from 'svelte-adapter-uws/client';
931
+
932
+ let { data } = $props();
933
+ const users = lookup('users', data.users);
934
+ </script>
935
+
936
+ {#if $users[selectedId]}
937
+ <UserCard user={$users[selectedId]} />
938
+ {/if}
939
+ ```
940
+
941
+ ### `latest(topic, max?, initial?)` - ring buffer
942
+
943
+ Keeps the last N events. Perfect for chat, activity feeds, notifications:
944
+
945
+ ```svelte
946
+ <script>
947
+ import { latest } from 'svelte-adapter-uws/client';
948
+
949
+ // Keep the last 100 chat messages
950
+ const messages = latest('chat', 100);
951
+ </script>
952
+
953
+ {#each $messages as msg}
954
+ <p><b>{msg.event}:</b> {msg.data.text}</p>
955
+ {/each}
956
+ ```
957
+
958
+ ### `count(topic, initial?)` - live counter
959
+
960
+ Handles `set`, `increment`, and `decrement` events:
961
+
962
+ ```svelte
963
+ <script>
964
+ import { count } from 'svelte-adapter-uws/client';
965
+
966
+ const online = count('online-users');
967
+ </script>
968
+
969
+ <p>{$online} users online</p>
970
+ ```
971
+
972
+ Server:
973
+ ```js
974
+ platform.topic('online-users').increment();
975
+ platform.topic('online-users').decrement();
976
+ platform.topic('online-users').set(42);
977
+ ```
978
+
979
+ ### `once(topic, event?, options?)` - wait for one event
980
+
981
+ Returns a promise that resolves with the first matching event and then unsubscribes:
982
+
983
+ ```js
984
+ import { once } from 'svelte-adapter-uws/client';
985
+
986
+ // Wait for any event on the 'jobs' topic
987
+ const event = await once('jobs');
988
+
989
+ // Wait for a specific event
990
+ const result = await once('jobs', 'completed');
991
+
992
+ // With a timeout (rejects if no event within 5 seconds)
993
+ const result = await once('jobs', 'completed', { timeout: 5000 });
994
+
995
+ // Timeout without event filter
996
+ const event = await once('jobs', { timeout: 5000 });
997
+ ```
998
+
999
+ ### `status` - connection status
1000
+
1001
+ Readable store with the current connection state:
1002
+
1003
+ ```svelte
1004
+ <script>
1005
+ import { status } from 'svelte-adapter-uws/client';
1006
+ </script>
1007
+
1008
+ {#if $status === 'open'}
1009
+ <span class="badge green">Live</span>
1010
+ {:else if $status === 'connecting'}
1011
+ <span class="badge yellow">Connecting...</span>
1012
+ {:else}
1013
+ <span class="badge red">Disconnected</span>
1014
+ {/if}
1015
+ ```
1016
+
1017
+ ### `ready()` - wait for connection
1018
+
1019
+ Returns a promise that resolves when the WebSocket connection is open:
1020
+
1021
+ ```js
1022
+ import { ready } from 'svelte-adapter-uws/client';
1023
+
1024
+ await ready();
1025
+ // connection is now open, safe to send messages
1026
+ ```
1027
+
1028
+ ### `connect(options?)` - power-user API
1029
+
1030
+ Most users don't need this - `on()` and `status` auto-connect. Use `connect()` when you need `close()`, `send()`, or custom options:
1031
+
1032
+ ```js
1033
+ import { connect } from 'svelte-adapter-uws/client';
1034
+
1035
+ const ws = connect({
1036
+ path: '/ws', // default: '/ws'
1037
+ reconnectInterval: 3000, // default: 3000 ms
1038
+ maxReconnectInterval: 30000, // default: 30000 ms
1039
+ maxReconnectAttempts: Infinity, // default: Infinity
1040
+ debug: true // default: false - turn this on to see everything!
1041
+ });
1042
+
1043
+ // With debug: true, you'll see every WebSocket event in the browser console:
1044
+ // [ws] connected
1045
+ // [ws] subscribe -> todos
1046
+ // [ws] <- todos created { id: 1, text: "Buy milk" }
1047
+ // [ws] send -> { type: "ping" }
1048
+ // [ws] disconnected
1049
+ // [ws] queued -> { type: "important" }
1050
+ // [ws] resubscribe -> todos
1051
+ // [ws] flush -> { type: "important" }
1052
+
1053
+ // Manual topic management
1054
+ ws.subscribe('chat');
1055
+ ws.unsubscribe('chat');
1056
+
1057
+ // Send custom messages to the server
1058
+ ws.send({ type: 'ping' });
1059
+
1060
+ // Send with queue (messages queue up while disconnected, flush on reconnect)
1061
+ ws.sendQueued({ type: 'important', data: '...' });
1062
+
1063
+ // Permanent disconnect (won't auto-reconnect)
1064
+ ws.close();
1065
+ ```
1066
+
1067
+ ---
1068
+
1069
+ ## TypeScript setup
1070
+
1071
+ Add the platform type to your `src/app.d.ts`:
1072
+
1073
+ ```ts
1074
+ import type { Platform as AdapterPlatform } from 'svelte-adapter-uws';
1075
+
1076
+ declare global {
1077
+ namespace App {
1078
+ interface Platform extends AdapterPlatform {}
1079
+ }
1080
+ }
1081
+
1082
+ export {};
1083
+ ```
1084
+
1085
+ Now `event.platform.publish()`, `event.platform.topic()`, etc. are fully typed.
1086
+
1087
+ ---
1088
+
1089
+ ## Svelte 4 support
1090
+
1091
+ This adapter supports both Svelte 4 and Svelte 5. All examples in this README use Svelte 5 syntax (`$props()`, runes). If you're on Svelte 4, here's how to translate:
1092
+
1093
+ **Svelte 5 (used in examples)**
1094
+ ```svelte
1095
+ <script>
1096
+ import { crud } from 'svelte-adapter-uws/client';
1097
+
1098
+ let { data } = $props();
1099
+ const todos = crud('todos', data.todos);
1100
+ </script>
1101
+ ```
1102
+
1103
+ **Svelte 4 equivalent**
1104
+ ```svelte
1105
+ <script>
1106
+ import { crud } from 'svelte-adapter-uws/client';
1107
+
1108
+ export let data;
1109
+ const todos = crud('todos', data.todos);
1110
+ </script>
1111
+ ```
1112
+
1113
+ The only difference is how you receive props. The client store API (`on`, `crud`, `lookup`, `latest`, `count`, `once`, `status`, `connect`) works identically in both versions - it uses `svelte/store` which hasn't changed.
1114
+
1115
+ ---
1116
+
1117
+ ## Deploying with Docker
1118
+
1119
+ uWebSockets.js is a native C++ addon, so your Docker image needs to match the platform it was compiled for. Build inside the container to be safe.
1120
+
1121
+ ```dockerfile
1122
+ FROM node:20-slim
1123
+
1124
+ WORKDIR /app
1125
+
1126
+ # Copy package files and install dependencies
1127
+ COPY package*.json ./
1128
+ RUN npm ci
1129
+
1130
+ # Copy source and build
1131
+ COPY . .
1132
+ RUN npm run build
1133
+
1134
+ # Only the build output is needed at runtime
1135
+ # (but node_modules must stay for uWebSockets.js native addon)
1136
+ EXPOSE 3000
1137
+ CMD ["node", "build"]
1138
+ ```
1139
+
1140
+ With TLS:
1141
+ ```dockerfile
1142
+ CMD ["sh", "-c", "SSL_CERT=/certs/cert.pem SSL_KEY=/certs/key.pem node build"]
1143
+ ```
1144
+
1145
+ With environment variables:
1146
+ ```bash
1147
+ docker run -p 3000:3000 \
1148
+ -e PORT=3000 \
1149
+ -e ORIGIN=https://example.com \
1150
+ my-app
1151
+ ```
1152
+
1153
+ > **Tip:** Don't use Alpine (`node:20-alpine`) - uWebSockets.js prebuilt binaries are compiled against glibc, not musl. If you must use Alpine, you'll need to compile from source.
1154
+
1155
+ ---
1156
+
1157
+ ## Clustering (Linux)
1158
+
1159
+ On Linux, multiple processes can share the same port via `SO_REUSEPORT` - the kernel load-balances incoming connections across workers. This gives you near-linear scaling for HTTP/SSR workloads with zero coordination overhead.
1160
+
1161
+ Set the `CLUSTER_WORKERS` environment variable to enable it:
1162
+
1163
+ ```bash
1164
+ # Use all available CPU cores
1165
+ CLUSTER_WORKERS=auto node build
1166
+
1167
+ # Fixed number of workers
1168
+ CLUSTER_WORKERS=4 node build
1169
+
1170
+ # Combined with other options
1171
+ CLUSTER_WORKERS=auto PORT=8080 ORIGIN=https://example.com node build
1172
+ ```
1173
+
1174
+ The primary process forks N workers, each running their own uWS server on the same port. If a worker crashes, it is automatically restarted. On `SIGTERM`/`SIGINT`, the primary forwards the signal to all workers for graceful shutdown.
1175
+
1176
+ ### Limitations
1177
+
1178
+ - **Linux only** - `SO_REUSEPORT` is a Linux kernel feature. On other platforms, the variable is ignored with a warning.
1179
+ - **HTTP/SSR only** - clustering is automatically disabled when WebSocket is enabled (`websocket: true` or `websocket: { ... }`). uWS pub/sub is per-process, so messages published in one worker would not reach clients connected to another worker. If you need clustered WebSocket, bring an external pub/sub backend (Redis, NATS, etc.) and manage multi-process coordination yourself.
1180
+
1181
+ ---
1182
+
1183
+ ## Performance
1184
+
1185
+ ### Why uWebSockets.js?
1186
+
1187
+ uWebSockets.js is a C++ HTTP and WebSocket server compiled to a native V8 addon. In benchmarks it consistently outperforms Node.js' built-in `http` module, Express, Fastify, and every other JavaScript HTTP server by a significant margin - often 5-10x more requests per second.
1188
+
1189
+ ### Our overhead vs barebones uWS
1190
+
1191
+ A barebones uWebSockets.js "hello world" can handle 500k+ requests per second on a single core. This adapter adds overhead that is unavoidable for what it does:
1192
+
1193
+ 1. **SvelteKit SSR** - every non-static request goes through SvelteKit's `server.respond()`, which runs your load functions, renders components, and produces HTML. This is the biggest cost and it's the whole point of using SvelteKit.
1194
+
1195
+ 2. **Static file cache** - on startup we walk the build output and load every static file into memory with its precompressed variants. This is a one-time cost. Serving static files is then a single `Map.get()` plus a `res.cork()` + `res.end()` - about as fast as it gets without sendfile.
1196
+
1197
+ 3. **Request construction** - we build a standard `Request` object from uWS' stack-allocated `HttpRequest`. This means reading all headers synchronously (uWS requirement) and constructing a URL string. We read headers lazily for static files (only `accept-encoding` and `if-none-match`), but SSR requires the full set.
1198
+
1199
+ 4. **Response streaming** - we read from the `Response.body` ReadableStream and write chunks through uWS with backpressure support (`onWritable`). Single-chunk responses (most SSR pages) are optimized into a single `res.cork()` + `res.end()` call.
1200
+
1201
+ 5. **WebSocket envelope** - every pub/sub message is wrapped in `JSON.stringify({ topic, event, data })`. This is a few microseconds per message. The tradeoff is a clean, standardized format that the client store understands without configuration.
1202
+
1203
+ **What we don't add:**
1204
+ - No middleware chain
1205
+ - No routing layer (uWS' native routing + SvelteKit's router)
1206
+ - No per-request allocations beyond what's needed
1207
+ - No Node.js `http.IncomingMessage` shim (we construct `Request` directly from uWS)
1208
+
1209
+ ### The bottom line
1210
+
1211
+ For static files, performance is very close to barebones uWS. For SSR, the bottleneck is your Svelte components and load functions, not the adapter. The adapter's job is to get out of the way as fast as possible - and it does.
1212
+
1213
+ ---
1214
+
1215
+ ## Full example: real-time todo list
1216
+
1217
+ Here's a complete example tying everything together.
1218
+
1219
+ **svelte.config.js**
1220
+ ```js
1221
+ import adapter from 'svelte-adapter-uws';
1222
+
1223
+ export default {
1224
+ kit: {
1225
+ adapter: adapter({
1226
+ websocket: true
1227
+ })
1228
+ }
1229
+ };
1230
+ ```
1231
+
1232
+ **vite.config.js**
1233
+ ```js
1234
+ import { sveltekit } from '@sveltejs/kit/vite';
1235
+ import uwsDev from 'svelte-adapter-uws/vite';
1236
+
1237
+ export default {
1238
+ plugins: [sveltekit(), uwsDev()]
1239
+ };
1240
+ ```
1241
+
1242
+ **src/routes/todos/+page.server.js**
1243
+ ```js
1244
+ import { db } from '$lib/server/db.js';
1245
+
1246
+ export async function load() {
1247
+ return { todos: await db.getTodos() };
1248
+ }
1249
+
1250
+ export const actions = {
1251
+ create: async ({ request, platform }) => {
1252
+ const text = (await request.formData()).get('text');
1253
+ const todo = await db.createTodo(text);
1254
+ platform.topic('todos').created(todo);
1255
+ },
1256
+
1257
+ toggle: async ({ request, platform }) => {
1258
+ const id = (await request.formData()).get('id');
1259
+ const todo = await db.toggleTodo(id);
1260
+ platform.topic('todos').updated(todo);
1261
+ },
1262
+
1263
+ delete: async ({ request, platform }) => {
1264
+ const id = (await request.formData()).get('id');
1265
+ await db.deleteTodo(id);
1266
+ platform.topic('todos').deleted({ id });
1267
+ }
1268
+ };
1269
+ ```
1270
+
1271
+ **src/routes/todos/+page.svelte**
1272
+ ```svelte
1273
+ <script>
1274
+ import { crud, status } from 'svelte-adapter-uws/client';
1275
+
1276
+ let { data } = $props();
1277
+ const todos = crud('todos', data.todos);
1278
+ </script>
1279
+
1280
+ {#if $status === 'open'}
1281
+ <span>Live</span>
1282
+ {/if}
1283
+
1284
+ <form method="POST" action="?/create">
1285
+ <input name="text" placeholder="New todo..." />
1286
+ <button>Add</button>
1287
+ </form>
1288
+
1289
+ <ul>
1290
+ {#each $todos as todo (todo.id)}
1291
+ <li>
1292
+ <form method="POST" action="?/toggle">
1293
+ <input type="hidden" name="id" value={todo.id} />
1294
+ <button>{todo.done ? 'Undo' : 'Done'}</button>
1295
+ </form>
1296
+ <span class:done={todo.done}>{todo.text}</span>
1297
+ <form method="POST" action="?/delete">
1298
+ <input type="hidden" name="id" value={todo.id} />
1299
+ <button>Delete</button>
1300
+ </form>
1301
+ </li>
1302
+ {/each}
1303
+ </ul>
1304
+ ```
1305
+
1306
+ Open the page in two browser tabs. Create, toggle, or delete a todo in one tab - it appears in the other tab instantly.
1307
+
1308
+ ---
1309
+
1310
+ ## Troubleshooting
1311
+
1312
+ ### "WebSocket works in production but not in dev"
1313
+
1314
+ You need the Vite plugin. Without it, there's no WebSocket server running during `npm run dev`.
1315
+
1316
+ **vite.config.js**
1317
+ ```js
1318
+ import { sveltekit } from '@sveltejs/kit/vite';
1319
+ import uwsDev from 'svelte-adapter-uws/vite';
1320
+
1321
+ export default {
1322
+ plugins: [sveltekit(), uwsDev()]
1323
+ };
1324
+ ```
1325
+
1326
+ Also make sure `ws` is installed:
1327
+ ```bash
1328
+ npm install -D ws
1329
+ ```
1330
+
1331
+ ### "Cannot read properties of undefined (reading 'publish')"
1332
+
1333
+ This means `event.platform` is `undefined`. Two possible causes:
1334
+
1335
+ **Cause 1: Missing Vite plugin in dev mode**
1336
+
1337
+ Same fix as above - add `uwsDev()` to your `vite.config.js`.
1338
+
1339
+ **Cause 2: Calling `platform` on the client side**
1340
+
1341
+ `event.platform` only exists on the server. If you're calling it in a `+page.svelte` or `+layout.svelte` file, move that code to `+page.server.js` or `+server.js`.
1342
+
1343
+ ```js
1344
+ // WRONG - +page.svelte (client-side)
1345
+ platform.publish('todos', 'created', todo);
1346
+
1347
+ // RIGHT - +page.server.js (server-side)
1348
+ export const actions = {
1349
+ create: async ({ platform }) => {
1350
+ platform.publish('todos', 'created', todo);
1351
+ }
1352
+ };
1353
+ ```
1354
+
1355
+ ### "WebSocket connects but immediately disconnects (and keeps reconnecting)"
1356
+
1357
+ Your `upgrade` handler is returning `false`, which rejects the connection with 401. The client store's auto-reconnect then tries again, gets rejected again, and so on.
1358
+
1359
+ **To debug**, enable debug mode on the client:
1360
+ ```js
1361
+ import { connect } from 'svelte-adapter-uws/client';
1362
+ connect({ debug: true });
1363
+ ```
1364
+
1365
+ Then check the browser's Network tab → WS tab. You'll see the upgrade request and its 401 response.
1366
+
1367
+ **Common causes:**
1368
+ - The session cookie isn't being set (check your login action)
1369
+ - The cookie name doesn't match (`cookies.session` vs `cookies.session_id`)
1370
+ - The session expired or is invalid
1371
+ - `sameSite: 'strict'` can block cookies on cross-origin navigations - try `'lax'` if you're redirecting from an external site
1372
+
1373
+ ### "WebSocket doesn't work with `npm run preview`"
1374
+
1375
+ This is expected. SvelteKit's preview server is Vite's built-in HTTP server - it doesn't know about WebSocket upgrades. Use `node build` instead:
1376
+
1377
+ ```bash
1378
+ npm run build
1379
+ node build
1380
+ ```
1381
+
1382
+ ### "Could not load uWebSockets.js"
1383
+
1384
+ uWebSockets.js is a native C++ addon. It's installed from GitHub, not npm, and needs to compile for your platform.
1385
+
1386
+ ```bash
1387
+ # Make sure you're using the right install command (no uWebSockets.js@ prefix)
1388
+ npm install uNetworking/uWebSockets.js#v20.60.0
1389
+ ```
1390
+
1391
+ **On Windows:** Make sure you have the Visual C++ Build Tools installed. You can get them from the [Visual Studio Installer](https://visualstudio.microsoft.com/downloads/) (select "Desktop development with C++").
1392
+
1393
+ **On Linux:** Make sure `build-essential` is installed:
1394
+ ```bash
1395
+ sudo apt install build-essential
1396
+ ```
1397
+
1398
+ **On Docker:** Use a Node.js image that includes build tools:
1399
+ ```dockerfile
1400
+ FROM node:20
1401
+ ```
1402
+
1403
+ ### "I can't see what's happening with WebSocket messages"
1404
+
1405
+ Turn on debug mode. It logs every WebSocket event to the browser console:
1406
+
1407
+ ```svelte
1408
+ <script>
1409
+ import { connect } from 'svelte-adapter-uws/client';
1410
+
1411
+ // Call this once, anywhere - it's a singleton
1412
+ connect({ debug: true });
1413
+ </script>
1414
+ ```
1415
+
1416
+ You'll see output like:
1417
+ ```
1418
+ [ws] connected
1419
+ [ws] subscribe -> todos
1420
+ [ws] <- todos created {"id":1,"text":"Buy milk"}
1421
+ [ws] disconnected
1422
+ [ws] resubscribe -> todos
1423
+ ```
1424
+
1425
+ ### "Messages are arriving but my store isn't updating"
1426
+
1427
+ Make sure the topic names match exactly between server and client:
1428
+
1429
+ ```js
1430
+ // Server
1431
+ platform.publish('todos', 'created', todo); // topic: 'todos'
1432
+
1433
+ // Client - must match exactly
1434
+ const todos = on('todos'); // 'todos' - correct
1435
+ const todos = on('Todos'); // 'Todos' - WRONG, case sensitive
1436
+ const todos = on('todo'); // 'todo' - WRONG, singular vs plural
1437
+ ```
1438
+
1439
+ ### "How do I see what the message envelope looks like?"
1440
+
1441
+ Every message sent through `platform.publish()` or `platform.topic().created()` arrives as JSON with this shape:
1442
+
1443
+ ```json
1444
+ {
1445
+ "topic": "todos",
1446
+ "event": "created",
1447
+ "data": { "id": 1, "text": "Buy milk", "done": false }
1448
+ }
1449
+ ```
1450
+
1451
+ The client store parses this automatically. When you use `on('todos')`, the store value is:
1452
+ ```js
1453
+ { topic: 'todos', event: 'created', data: { id: 1, text: 'Buy milk', done: false } }
1454
+ ```
1455
+
1456
+ When you use `on('todos', 'created')`, you get just the `data`:
1457
+ ```js
1458
+ { id: 1, text: 'Buy milk', done: false }
1459
+ ```
1460
+
1461
+ ### "WebSocket works locally but not behind nginx/Caddy"
1462
+
1463
+ Your reverse proxy needs to forward WebSocket upgrade requests. Here's a complete nginx config that handles both your app and WebSocket:
1464
+
1465
+ ```nginx
1466
+ server {
1467
+ listen 443 ssl;
1468
+ server_name example.com;
1469
+
1470
+ ssl_certificate /path/to/cert.pem;
1471
+ ssl_certificate_key /path/to/key.pem;
1472
+
1473
+ # WebSocket - must be listed before the catch-all
1474
+ location /ws {
1475
+ proxy_pass http://localhost:3000;
1476
+ proxy_http_version 1.1;
1477
+ proxy_set_header Upgrade $http_upgrade;
1478
+ proxy_set_header Connection "upgrade";
1479
+ proxy_set_header Host $host;
1480
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1481
+ proxy_set_header X-Forwarded-Proto $scheme;
1482
+ }
1483
+
1484
+ # Everything else - your SvelteKit app
1485
+ location / {
1486
+ proxy_pass http://localhost:3000;
1487
+ proxy_set_header Host $host;
1488
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
1489
+ proxy_set_header X-Forwarded-Proto $scheme;
1490
+ }
1491
+ }
1492
+ ```
1493
+
1494
+ Then run your app with:
1495
+ ```bash
1496
+ PROTOCOL_HEADER=x-forwarded-proto HOST_HEADER=host ADDRESS_HEADER=x-forwarded-for node build
1497
+ ```
1498
+
1499
+ For Caddy, it just works - Caddy proxies WebSocket upgrades automatically, no special config needed:
1500
+
1501
+ ```
1502
+ example.com {
1503
+ reverse_proxy localhost:3000
1504
+ }
1505
+ ```
1506
+
1507
+ ### "I want to use a different WebSocket path"
1508
+
1509
+ Set it in both the adapter config and the client:
1510
+
1511
+ **svelte.config.js**
1512
+ ```js
1513
+ adapter({
1514
+ websocket: {
1515
+ path: '/my-ws'
1516
+ }
1517
+ })
1518
+ ```
1519
+
1520
+ **Client**
1521
+ ```js
1522
+ import { connect } from 'svelte-adapter-uws/client';
1523
+ connect({ path: '/my-ws' });
1524
+ ```
1525
+
1526
+ Or if you're using `on()` directly (which auto-connects), call `connect()` first:
1527
+
1528
+ ```svelte
1529
+ <script>
1530
+ import { connect, on } from 'svelte-adapter-uws/client';
1531
+
1532
+ // Set the path before any on() calls
1533
+ connect({ path: '/my-ws' });
1534
+
1535
+ const todos = on('todos');
1536
+ </script>
1537
+ ```
1538
+
1539
+ ---
1540
+
1541
+ ## License
1542
+
1543
+ [MIT](LICENSE)