|
| 1 | +--- |
| 2 | +title: WebSocket Endpoint |
| 3 | +--- |
| 4 | + |
| 5 | +WebSocket endpoint may be included by passing the ws handler file you specify in your start config. |
| 6 | +Note that this feature is [experimental on the Nitro server](https://nitro.unjs.io/guide/websocket#opt-in-to-the-experimental-feature) and its config may change in future releases of SolidStart. Use it with caution. |
| 7 | + |
| 8 | +```ts title="./app.config.ts" |
| 9 | +import { defineConfig } from "@solidjs/start/config"; |
| 10 | + |
| 11 | +export default defineConfig({ |
| 12 | + server: { |
| 13 | + experimental: { |
| 14 | + websocket: true, |
| 15 | + }, |
| 16 | + }, |
| 17 | +}).addRouter({ |
| 18 | + name: "ws", |
| 19 | + type: "http", |
| 20 | + handler: "./src/ws.ts", |
| 21 | + target: "server", |
| 22 | + base: "/ws", |
| 23 | +}); |
| 24 | +``` |
| 25 | + |
| 26 | +Inside the ws file, you can export an eventHandler function to manage WebSocket connections and events: |
| 27 | + |
| 28 | +```tsx title="./src/ws.ts" |
| 29 | +import { eventHandler } from "vinxi/http"; |
| 30 | + |
| 31 | +export default eventHandler({ |
| 32 | + handler() {}, |
| 33 | + websocket: { |
| 34 | + async open(peer) { |
| 35 | + console.log("open", peer.id, peer.url); |
| 36 | + }, |
| 37 | + async message(peer, msg) { |
| 38 | + const message = msg.text(); |
| 39 | + console.log("msg", peer.id, peer.url, message); |
| 40 | + }, |
| 41 | + async close(peer, details) { |
| 42 | + console.log("close", peer.id, peer.url); |
| 43 | + }, |
| 44 | + async error(peer, error) { |
| 45 | + console.log("error", peer.id, peer.url, error); |
| 46 | + }, |
| 47 | + }, |
| 48 | +}); |
| 49 | +``` |
0 commit comments