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
WebSocket Real-Time Communication

WebSocket Real-Time Communication

Real-time communication patterns with WebSockets including rooms, broadcasting, and reconnection

WebSocketReal-timeSocket.ioNode.js
by Antigravity Team
⭐0Stars
.antigravity
# WebSocket Real-Time Communication for Google Antigravity

Build real-time applications with WebSockets using Google Antigravity's Gemini 3 engine. This guide covers connection management, rooms, broadcasting, and reconnection strategies.

## WebSocket Server with Socket.io

```typescript
// src/socket/server.ts
import { Server as HttpServer } from 'http';
import { Server, Socket } from 'socket.io';
import { verifyToken } from '../auth';
import { redis } from '../redis';

interface ServerToClientEvents {
  message: (data: Message) => void;
  userJoined: (user: UserInfo) => void;
  userLeft: (userId: string) => void;
  typing: (data: { userId: string; isTyping: boolean }) => void;
  error: (error: { code: string; message: string }) => void;
}

interface ClientToServerEvents {
  joinRoom: (roomId: string) => void;
  leaveRoom: (roomId: string) => void;
  sendMessage: (data: { roomId: string; content: string }) => void;
  typing: (data: { roomId: string; isTyping: boolean }) => void;
}

interface InterServerEvents {
  ping: () => void;
}

interface SocketData {
  userId: string;
  email: string;
  name: string;
}

export function createSocketServer(httpServer: HttpServer) {
  const io = new Server<
    ClientToServerEvents,
    ServerToClientEvents,
    InterServerEvents,
    SocketData
  >(httpServer, {
    cors: {
      origin: process.env.ALLOWED_ORIGINS?.split(',') || '*',
      credentials: true,
    },
    pingTimeout: 60000,
    pingInterval: 25000,
  });

  // Authentication middleware
  io.use(async (socket, next) => {
    const token = socket.handshake.auth.token;

    if (!token) {
      return next(new Error('Authentication required'));
    }

    try {
      const user = verifyToken(token);
      socket.data.userId = user.id;
      socket.data.email = user.email;
      socket.data.name = user.name;
      next();
    } catch (error) {
      next(new Error('Invalid token'));
    }
  });

  io.on('connection', (socket) => {
    console.log(`User connected: ${socket.data.userId}`);

    // Track online users in Redis
    redis.sadd('online_users', socket.data.userId);

    // Join user's personal room for direct messages
    socket.join(`user:${socket.data.userId}`);

    // Handle room joining
    socket.on('joinRoom', async (roomId) => {
      // Verify user has access to room
      const hasAccess = await checkRoomAccess(socket.data.userId, roomId);

      if (!hasAccess) {
        socket.emit('error', { code: 'FORBIDDEN', message: 'No access to room' });
        return;
      }

      socket.join(`room:${roomId}`);

      // Notify room members
      socket.to(`room:${roomId}`).emit('userJoined', {
        userId: socket.data.userId,
        name: socket.data.name,
      });

      // Track room presence
      await redis.sadd(`room:${roomId}:members`, socket.data.userId);
    });

    // Handle room leaving
    socket.on('leaveRoom', async (roomId) => {
      socket.leave(`room:${roomId}`);

      socket.to(`room:${roomId}`).emit('userLeft', socket.data.userId);

      await redis.srem(`room:${roomId}:members`, socket.data.userId);
    });

    // Handle messages
    socket.on('sendMessage', async (data) => {
      const { roomId, content } = data;

      // Save message to database
      const message = await saveMessage({
        roomId,
        userId: socket.data.userId,
        content,
      });

      // Broadcast to room
      io.to(`room:${roomId}`).emit('message', {
        id: message.id,
        content: message.content,
        userId: socket.data.userId,
        userName: socket.data.name,
        roomId,
        createdAt: message.createdAt.toISOString(),
      });
    });

    // Handle typing indicators
    socket.on('typing', ({ roomId, isTyping }) => {
      socket.to(`room:${roomId}`).emit('typing', {
        userId: socket.data.userId,
        isTyping,
      });
    });

    // Handle disconnection
    socket.on('disconnect', async () => {
      console.log(`User disconnected: ${socket.data.userId}`);

      await redis.srem('online_users', socket.data.userId);

      // Notify all rooms user was in
      const rooms = Array.from(socket.rooms);
      for (const room of rooms) {
        if (room.startsWith('room:')) {
          const roomId = room.replace('room:', '');
          await redis.srem(`room:${roomId}:members`, socket.data.userId);
          socket.to(room).emit('userLeft', socket.data.userId);
        }
      }
    });
  });

  return io;
}
```

## Client-Side WebSocket Hook

```typescript
// hooks/useSocket.ts
import { useEffect, useRef, useCallback, useState } from 'react';
import { io, Socket } from 'socket.io-client';

interface UseSocketOptions {
  url: string;
  token: string;
  onConnect?: () => void;
  onDisconnect?: () => void;
  onError?: (error: Error) => void;
}

export function useSocket({ url, token, onConnect, onDisconnect, onError }: UseSocketOptions) {
  const socketRef = useRef<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [reconnectAttempts, setReconnectAttempts] = useState(0);

  useEffect(() => {
    const socket = io(url, {
      auth: { token },
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
      reconnectionDelayMax: 5000,
    });

    socket.on('connect', () => {
      setIsConnected(true);
      setReconnectAttempts(0);
      onConnect?.();
    });

    socket.on('disconnect', () => {
      setIsConnected(false);
      onDisconnect?.();
    });

    socket.on('connect_error', (error) => {
      setReconnectAttempts((prev) => prev + 1);
      onError?.(error);
    });

    socketRef.current = socket;

    return () => {
      socket.disconnect();
    };
  }, [url, token, onConnect, onDisconnect, onError]);

  const emit = useCallback(<T>(event: string, data: T) => {
    socketRef.current?.emit(event, data);
  }, []);

  const on = useCallback(<T>(event: string, callback: (data: T) => void) => {
    socketRef.current?.on(event, callback);
    return () => {
      socketRef.current?.off(event, callback);
    };
  }, []);

  const joinRoom = useCallback((roomId: string) => {
    socketRef.current?.emit('joinRoom', roomId);
  }, []);

  const leaveRoom = useCallback((roomId: string) => {
    socketRef.current?.emit('leaveRoom', roomId);
  }, []);

  return {
    socket: socketRef.current,
    isConnected,
    reconnectAttempts,
    emit,
    on,
    joinRoom,
    leaveRoom,
  };
}
```

## Chat Room Component

```typescript
// components/ChatRoom.tsx
'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { useSocket } from '@/hooks/useSocket';
import { useAuth } from '@/hooks/useAuth';

interface Message {
  id: string;
  content: string;
  userId: string;
  userName: string;
  createdAt: string;
}

interface ChatRoomProps {
  roomId: string;
}

export function ChatRoom({ roomId }: ChatRoomProps) {
  const { user, token } = useAuth();
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [typingUsers, setTypingUsers] = useState<Map<string, string>>(new Map());
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const typingTimeoutRef = useRef<NodeJS.Timeout>();

  const { socket, isConnected, joinRoom, leaveRoom, emit, on } = useSocket({
    url: process.env.NEXT_PUBLIC_WS_URL!,
    token,
    onConnect: () => console.log('Connected to chat'),
    onDisconnect: () => console.log('Disconnected from chat'),
  });

  // Join room on mount
  useEffect(() => {
    if (isConnected) {
      joinRoom(roomId);
    }

    return () => {
      if (isConnected) {
        leaveRoom(roomId);
      }
    };
  }, [isConnected, roomId, joinRoom, leaveRoom]);

  // Listen for messages
  useEffect(() => {
    const unsubscribe = on<Message>('message', (message) => {
      setMessages((prev) => [...prev, message]);
    });

    return unsubscribe;
  }, [on]);

  // Listen for typing indicators
  useEffect(() => {
    const unsubscribe = on<{ userId: string; isTyping: boolean }>('typing', (data) => {
      setTypingUsers((prev) => {
        const next = new Map(prev);
        if (data.isTyping) {
          next.set(data.userId, data.userId);
        } else {
          next.delete(data.userId);
        }
        return next;
      });
    });

    return unsubscribe;
  }, [on]);

  // Auto-scroll to bottom
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const sendMessage = useCallback(() => {
    if (!input.trim()) return;

    emit('sendMessage', { roomId, content: input });
    setInput('');

    // Stop typing indicator
    emit('typing', { roomId, isTyping: false });
  }, [input, roomId, emit]);

  const handleInputChange = useCallback((value: string) => {
    setInput(value);

    // Send typing indicator
    emit('typing', { roomId, isTyping: true });

    // Clear previous timeout
    if (typingTimeoutRef.current) {
      clearTimeout(typingTimeoutRef.current);
    }

    // Stop typing after 2 seconds of inactivity
    typingTimeoutRef.current = setTimeout(() => {
      emit('typing', { roomId, isTyping: false });
    }, 2000);
  }, [roomId, emit]);

  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.map((message) => (
          <div
            key={message.id}
            className={`flex ${message.userId === user?.id ? 'justify-end' : 'justify-start'}`}
          >
            <div
              className={`max-w-xs px-4 py-2 rounded-lg ${
                message.userId === user?.id
                  ? 'bg-blue-500 text-white'
                  : 'bg-gray-200 text-gray-900'
              }`}
            >
              <p className="text-xs font-semibold">{message.userName}</p>
              <p>{message.content}</p>
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>

      {typingUsers.size > 0 && (
        <div className="px-4 py-2 text-sm text-gray-500">
          {Array.from(typingUsers.values()).join(', ')} typing...
        </div>
      )}

      <div className="p-4 border-t">
        <div className="flex gap-2">
          <input
            type="text"
            value={input}
            onChange={(e) => handleInputChange(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
            placeholder="Type a message..."
            className="flex-1 px-4 py-2 border rounded-lg"
          />
          <button
            onClick={sendMessage}
            disabled={!isConnected}
            className="px-6 py-2 bg-blue-500 text-white rounded-lg disabled:opacity-50"
          >
            Send
          </button>
        </div>
      </div>
    </div>
  );
}
```

## Best Practices

Google Antigravity's Gemini 3 engine recommends these WebSocket patterns: Implement authentication in middleware. Use rooms for efficient broadcasting. Handle reconnection gracefully. Add typing indicators for UX. Use Redis for scaling across servers.

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...