Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Real-Time Applications Guide

Real-Time Applications Guide

Build real-time features with WebSockets and Server-Sent Events

websocketreal-timessesocket
by antigravity-team
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This websocket prompt is ideal for developers working on:

  • websocket applications requiring modern best practices and optimal performance
  • Projects that need production-ready websocket code with proper error handling
  • Teams looking to standardize their websocket development workflow
  • Developers wanting to learn industry-standard websocket patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the websocket code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this websocket prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...