Skip to content
This repository was archived by the owner on Oct 22, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions examples/raw-websocket-handler/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Raw WebSocket Handler Proxy for RivetKit

Example project demonstrating raw WebSocket handling with [RivetKit](https://rivetkit.org).

[Learn More →](https://github.com/rivet-dev/rivetkit)

[Discord](https://rivet.dev/discord) — [Documentation](https://rivetkit.org) — [Issues](https://github.com/rivet-dev/rivetkit/issues)

## Getting Started

### Prerequisites

- Node.js 18 or later
- pnpm (for monorepo management)

### Installation

```sh
git clone https://github.com/rivet-dev/rivetkit
cd rivetkit/examples/raw-websocket-handler-proxy
npm install
```

### Development

```sh
npm run dev
```

This starts both the backend server (on port 9000) and the frontend development server (on port 5173).

Open http://localhost:5173 in your browser to see the chat application demo.

### Testing

```sh
npm test
```

## Features

This example demonstrates:

- Creating actors with raw WebSocket handlers using `onWebsocket`
- Managing WebSocket connections and broadcasting messages
- Maintaining actor state across connections
- Supporting multiple connection methods (direct actor connection vs proxy endpoint)
- Real-time chat functionality with user presence
- Message persistence and history limits
- User name changes
- Comprehensive test coverage

## License

Apache 2.0
39 changes: 39 additions & 0 deletions examples/raw-websocket-handler/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "example-raw-websocket-handler",
"version": "2.0.13",
"private": true,
"type": "module",
"description": "RivetKit example demonstrating raw WebSocket handler",
"keywords": [
"rivetkit",
"websocket",
"actor",
"chat",
"realtime"
],
"scripts": {
"dev": "concurrently \"npm:dev:*\"",
"dev:backend": "tsx watch src/backend/server.ts",
"dev:frontend": "vite",
"check-types": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"rivetkit": "workspace:*",
"@rivetkit/react": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"hono": "^4.7.0"
},
"devDependencies": {
"@types/node": "^22.10.2",
"@types/react": "^18.3.16",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"concurrently": "^9.1.0",
"tsx": "^4.19.2",
"typescript": "^5.7.2",
"vite": "^6.0.5",
"vitest": "^3.1.1"
}
}
77 changes: 77 additions & 0 deletions examples/raw-websocket-handler/src/backend/registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { actor, setup } from "rivetkit";

export const chatRoom = actor({
state: {
messages: [] as Array<{
id: string;
text: string;
timestamp: number;
}>,
},
createVars: () => {
return {
sockets: new Set<any>(),
};
},
onWebSocket(ctx, socket) {
// Add socket to the set
ctx.vars.sockets.add(socket);

// Send recent messages to new connection
socket.send(
JSON.stringify({
type: "init",
messages: ctx.state.messages,
}),
);

// Handle incoming messages
socket.addEventListener("message", (event: any) => {
try {
const data = JSON.parse(event.data);

if (data.type === "message" && data.text) {
const message = {
id: crypto.randomUUID(),
text: data.text,
timestamp: Date.now(),
};

// Add to state
ctx.state.messages.push(message);
ctx.saveState({});

// Keep only last 50 messages
if (ctx.state.messages.length > 50) {
ctx.state.messages.shift();
}

// Broadcast to all connected clients
const broadcast = JSON.stringify({
type: "message",
...message,
});

for (const ws of ctx.vars.sockets) {
if (ws.readyState === 1) {
// OPEN
ws.send(broadcast);
}
}
}
} catch (e) {
console.error("Failed to process message:", e);
}
});

// Remove socket on close
socket.addEventListener("close", () => {
ctx.vars.sockets.delete(socket);
});
},
actions: {},
});

export const registry = setup({
use: { chatRoom },
});
8 changes: 8 additions & 0 deletions examples/raw-websocket-handler/src/backend/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { registry } from "./registry.js";

registry.start({
cors: {
origin: "http://localhost:5173",
credentials: true,
},
});
119 changes: 119 additions & 0 deletions examples/raw-websocket-handler/src/frontend/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import React, { useState, useEffect, useRef } from "react";
import { createClient, createRivetKit } from "@rivetkit/react";
import type { registry } from "../backend/registry";

const client = createClient<typeof registry>();
const { useActor } = createRivetKit(client);

export default function App() {
const [messages, setMessages] = useState<Array<{ id: string; text: string; timestamp: number }>>([]);
const [inputText, setInputText] = useState("");
const [isConnected, setIsConnected] = useState(false);

// Connect to the WebSocket actor
const chatRoom = useActor({
name: "chatRoom",
key: ["random"],
});

// Raw WS we created to connect to the actors
const wsRef = useRef<WebSocket | null>(null);

useEffect(() => {
(async () => {
const ws = await chatRoom.handle?.websocket();

if (!ws) return;

ws.onopen = () => {
setIsConnected(true);
console.log("Connected via direct access!");
};

ws.onmessage = (event) => {
const data = JSON.parse(event.data);

if (data.type === "init") {
setMessages(data.messages);
} else if (data.type === "message") {
setMessages(prev => [...prev, {
id: data.id,
text: data.text,
timestamp: data.timestamp
}]);
}
};

ws.onclose = (event) => {
setIsConnected(false);
console.log("WebSocket closed:", event.code, event.reason);
};

ws.onerror = (event) => {
console.error("WebSocket error:", event);
};

wsRef.current = ws;
})();

return () => {
if (wsRef.current) {
wsRef.current.close();
}
};
}, [chatRoom.handle]);

const sendMessage = (e: React.FormEvent) => {
e.preventDefault();
if (!inputText.trim() || !wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return;

wsRef.current.send(JSON.stringify({
type: "message",
text: inputText.trim()
}));
setInputText("");
};

return (
<div style={{ maxWidth: "800px", margin: "0 auto", padding: "20px" }}>
<h1>Raw WebSocket Chat</h1>

<div style={{
padding: "10px",
background: isConnected ? "#4caf50" : "#f44336",
color: "white",
borderRadius: "4px",
marginBottom: "20px"
}}>
{isConnected ? "Connected" : "Disconnected"}
</div>

<div style={{
background: "white",
border: "1px solid #ddd",
borderRadius: "8px",
padding: "10px",
height: "400px",
overflowY: "auto",
marginBottom: "10px"
}}>
{messages.map((msg) => (
<div key={msg.id} style={{ marginBottom: "10px" }}>
<strong>{new Date(msg.timestamp).toLocaleTimeString()}:</strong> {msg.text}
</div>
))}
</div>

<form onSubmit={sendMessage} style={{ display: "flex", gap: "10px" }}>
<input
type="text"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Type a message..."
style={{ flex: 1, padding: "8px", borderRadius: "4px", border: "1px solid #ddd" }}
/>
<button type="submit">Send</button>
</form>
</div>
);
}
21 changes: 21 additions & 0 deletions examples/raw-websocket-handler/src/frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>RivetKit Raw WebSocket Handler</title>
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
background: #f5f5f5;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/main.tsx"></script>
</body>
</html>
9 changes: 9 additions & 0 deletions examples/raw-websocket-handler/src/frontend/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
20 changes: 20 additions & 0 deletions examples/raw-websocket-handler/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"types": ["node", "vitest/globals"]
},
"include": ["src/**/*", "tests/**/*"],
"exclude": ["node_modules", "dist"]
}
4 changes: 4 additions & 0 deletions examples/raw-websocket-handler/turbo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"]
}
13 changes: 13 additions & 0 deletions examples/raw-websocket-handler/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";

export default defineConfig({
plugins: [react()],
root: "src/frontend",
build: {
outDir: "../../dist",
},
server: {
host: "0.0.0.0",
},
});
7 changes: 7 additions & 0 deletions examples/raw-websocket-handler/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
test: {
include: ["tests/**/*.test.ts"],
},
});
Loading
Loading