WebSocket Only
This guide demonstrates a minimal Teleportal server setup using only WebSocket connections. The server uses in-memory storage and accepts all WebSocket upgrade requests.
What it demonstrates
Section titled “What it demonstrates”- Setting up a basic Teleportal server with WebSocket transport only
- Using in-memory
YDocStoragefor document storage - Handling WebSocket upgrades with context extraction
- Client connection using the
ProviderAPI with WebSocket transport
Server Setup
Section titled “Server Setup”import { serve } from "crossws/server";import { Server } from "teleportal/server";import { YDocStorage } from "teleportal/storage";import { getWebsocketHandlers } from "teleportal/websocket-server";
// Create a Teleportal server with in-memory storageconst server = new Server({ storage: new YDocStorage(),});
// Set up WebSocket handlersserve({ websocket: getWebsocketHandlers({ server, onUpgrade: async () => { // Extract user context from the request // In production, you'd verify authentication here return { context: { userId: "nick", room: "test" }, }; }, }), fetch: () => new Response("Not found", { status: 404 }),});Client Setup
Section titled “Client Setup”import { Provider } from "teleportal/providers";
const provider = await Provider.create({ url: `ws://localhost:3000`, document: "test",});
await provider.synced;
provider.doc.getText("test").insert(0, "Hello, world!");
console.log(provider.doc.getText("test").toString());
provider.doc.on("update", () => { console.log(provider.doc.getText("test").toString());});How It Works
Section titled “How It Works”- Server: Creates a
Serverinstance with in-memoryYDocStorage - WebSocket Handlers: Uses
getWebsocketHandlersto handle WebSocket connections - Context Extraction:
onUpgradecallback extracts user context from the request - Client:
Provider.create()automatically connects via WebSocket - Synchronization:
provider.syncedwaits for the document to be fully synchronized
Next Steps
Section titled “Next Steps”- HTTP Transport - Learn about HTTP/SSE transport
- Authentication - Add authentication to your server
- Persistent Storage - Use persistent storage instead of in-memory