Fallback Connection
This guide demonstrates a Teleportal server that supports both WebSocket and HTTP transports, with the client automatically falling back to HTTP if WebSocket connection fails.
This is the recommended way to set up a Teleportal server, as it provides the best compatibility with different client environments.
What it demonstrates
Section titled “What it demonstrates”- Setting up a Teleportal server that supports both WebSocket and HTTP transports
- Client-side automatic fallback from WebSocket to HTTP transport
- Using the
connectionTypeproperty to determine which transport is active
Server Setup
Section titled “Server Setup”The server supports both WebSocket and HTTP:
import { serve } from "crossws/server";import { Server } from "teleportal/server";import { getWebsocketHandlers } from "teleportal/websocket-server";import { getHttpHandlers } from "teleportal/http";
const server = new Server({ getStorage: async (ctx) => { // Your storage implementation return documentStorage; },});
// WebSocket handlersconst wsHandlers = getWebsocketHandlers({ server, onUpgrade: async () => { return { context: { userId: "user-123" }, }; },});
// HTTP handlersconst httpHandlers = getHttpHandlers({ server, onConnect: async (request) => { return { context: { userId: "user-123" }, }; },});
serve({ websocket: wsHandlers, fetch: httpHandlers,});Client Setup
Section titled “Client Setup”The Provider automatically uses fallback connection:
import { Provider } from "teleportal/providers";
// Provider automatically tries WebSocket first, falls back to HTTPconst provider = await Provider.create({ url: "wss://example.com", // Tries WebSocket first document: "my-document",});
// Check which connection type is activeconsole.log(provider.connectionType); // "websocket" | "http" | null
await provider.synced;How It Works
Section titled “How It Works”- Initial Attempt: Provider tries to connect via WebSocket
- Fallback: If WebSocket fails, automatically falls back to HTTP/SSE
- Reconnection: Provider continues to attempt WebSocket in the background
- Upgrade: If WebSocket becomes available, connection is upgraded
Next Steps
Section titled “Next Steps”- WebSocket Only - WebSocket-only setup
- HTTP Transport - HTTP-only setup