Build real-time features with WebSockets and Server-Sent Events
# Real-Time Applications Guide for Google Antigravity
Implement real-time features in your applications using WebSockets and SSE with Google Antigravity IDE.
## WebSocket Server Setup
```typescript
// server/websocket.ts
import { WebSocketServer, WebSocket } from "ws";
import { createServer } from "http";
import { parse } from "url";
import { verifyToken } from "./auth";
interface Client {
ws: WebSocket;
userId: string;
rooms: Set<string>;
}
const clients = new Map<string, Client>();
const rooms = new Map<string, Set<string>>();
const server = createServer();
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", async (request, socket, head) => {
try {
const { query } = parse(request.url || "", true);
const token = query.token as string;
const user = await verifyToken(token);
if (!user) {
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request, user);
});
} catch (error) {
socket.destroy();
}
});
wss.on("connection", (ws: WebSocket, request, user) => {
const clientId = crypto.randomUUID();
const client: Client = { ws, userId: user.id, rooms: new Set() };
clients.set(clientId, client);
// Send connection confirmation
send(ws, { type: "connected", clientId });
ws.on("message", (data) => {
try {
const message = JSON.parse(data.toString());
handleMessage(clientId, message);
} catch (error) {
send(ws, { type: "error", message: "Invalid message format" });
}
});
ws.on("close", () => {
// Leave all rooms
client.rooms.forEach((room) => leaveRoom(clientId, room));
clients.delete(clientId);
});
// Heartbeat
ws.on("pong", () => { client.lastPong = Date.now(); });
});
// Heartbeat interval
setInterval(() => {
clients.forEach((client, id) => {
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.ping();
}
});
}, 30000);
function handleMessage(clientId: string, message: any) {
const client = clients.get(clientId);
if (!client) return;
switch (message.type) {
case "join":
joinRoom(clientId, message.room);
break;
case "leave":
leaveRoom(clientId, message.room);
break;
case "broadcast":
broadcastToRoom(message.room, {
type: "message",
from: client.userId,
content: message.content
}, clientId);
break;
case "direct":
sendToUser(message.targetUserId, {
type: "direct",
from: client.userId,
content: message.content
});
break;
}
}
function joinRoom(clientId: string, roomName: string) {
const client = clients.get(clientId);
if (!client) return;
client.rooms.add(roomName);
if (!rooms.has(roomName)) {
rooms.set(roomName, new Set());
}
rooms.get(roomName)!.add(clientId);
broadcastToRoom(roomName, {
type: "user_joined",
userId: client.userId,
room: roomName
});
}
function leaveRoom(clientId: string, roomName: string) {
const client = clients.get(clientId);
if (!client) return;
client.rooms.delete(roomName);
rooms.get(roomName)?.delete(clientId);
if (rooms.get(roomName)?.size === 0) {
rooms.delete(roomName);
}
}
function broadcastToRoom(room: string, message: any, excludeClient?: string) {
const roomClients = rooms.get(room);
if (!roomClients) return;
roomClients.forEach((clientId) => {
if (clientId !== excludeClient) {
const client = clients.get(clientId);
if (client) send(client.ws, message);
}
});
}
function sendToUser(userId: string, message: any) {
clients.forEach((client) => {
if (client.userId === userId) {
send(client.ws, message);
}
});
}
function send(ws: WebSocket, data: any) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
server.listen(3001);
```
## React WebSocket Hook
```typescript
// hooks/useWebSocket.ts
import { useEffect, useRef, useState, useCallback } from "react";
interface UseWebSocketOptions {
url: string;
token: string;
onMessage?: (data: any) => void;
onConnect?: () => void;
onDisconnect?: () => void;
reconnect?: boolean;
reconnectInterval?: number;
}
export function useWebSocket({
url,
token,
onMessage,
onConnect,
onDisconnect,
reconnect = true,
reconnectInterval = 3000
}: UseWebSocketOptions) {
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<Error | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const reconnectTimeoutRef = useRef<NodeJS.Timeout>();
const connect = useCallback(() => {
try {
const ws = new WebSocket(`${url}?token=${token}`);
wsRef.current = ws;
ws.onopen = () => {
setIsConnected(true);
setError(null);
onConnect?.();
};
ws.onclose = () => {
setIsConnected(false);
onDisconnect?.();
if (reconnect) {
reconnectTimeoutRef.current = setTimeout(connect, reconnectInterval);
}
};
ws.onerror = (event) => {
setError(new Error("WebSocket error"));
};
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
onMessage?.(data);
} catch (e) {
console.error("Failed to parse message:", e);
}
};
} catch (e) {
setError(e as Error);
}
}, [url, token, onMessage, onConnect, onDisconnect, reconnect, reconnectInterval]);
useEffect(() => {
connect();
return () => {
clearTimeout(reconnectTimeoutRef.current);
wsRef.current?.close();
};
}, [connect]);
const send = useCallback((data: any) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(data));
}
}, []);
const joinRoom = useCallback((room: string) => {
send({ type: "join", room });
}, [send]);
const leaveRoom = useCallback((room: string) => {
send({ type: "leave", room });
}, [send]);
const broadcast = useCallback((room: string, content: any) => {
send({ type: "broadcast", room, content });
}, [send]);
return {
isConnected,
error,
send,
joinRoom,
leaveRoom,
broadcast
};
}
```
## Server-Sent Events
```typescript
// app/api/events/route.ts
import { NextRequest } from "next/server";
export async function GET(request: NextRequest) {
const encoder = new TextEncoder();
const stream = new ReadableStream({
async start(controller) {
const sendEvent = (event: string, data: any) => {
controller.enqueue(encoder.encode(`event: ${event}\n`));
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
};
// Send initial data
sendEvent("connected", { timestamp: Date.now() });
// Subscribe to updates
const unsubscribe = eventEmitter.subscribe((event) => {
sendEvent(event.type, event.data);
});
// Keep connection alive
const heartbeat = setInterval(() => {
controller.enqueue(encoder.encode(": heartbeat\n\n"));
}, 30000);
// Cleanup on close
request.signal.addEventListener("abort", () => {
clearInterval(heartbeat);
unsubscribe();
controller.close();
});
}
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
});
}
```
## Best Practices
1. **Implement reconnection logic** with exponential backoff
2. **Use heartbeats** to detect stale connections
3. **Handle authentication** before upgrading to WebSocket
4. **Implement room-based messaging** for scalability
5. **Use SSE for server-to-client** only scenarios
6. **Add message queuing** for offline support
7. **Monitor connection health** in production
Google Antigravity helps build robust real-time features with proper error handling and reconnection strategies.This websocket prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their websocket implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For websocket projects, consider mentioning your framework version, coding style, and any specific libraries you're using.