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 FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 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 Applications Complete Guide

WebSocket Real-Time Applications Complete Guide

Build real-time applications with WebSocket and Socket.io. Learn connection management, rooms, authentication, scaling with Redis, and Next.js integration for live features.

websocketsocket-iorealtimechatnextjsredistypescript
by AntigravityAI
⭐0Stars
👁️2Views
.antigravity
# WebSocket Real-Time Applications Guide

Build real-time features with WebSocket and Socket.io for Next.js applications including live notifications, chat, and collaborative editing.

## Socket.io Server Setup

### Custom Server with Next.js

```typescript
// server.ts
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { Server } from "socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.PORT || 3000;

app.prepare().then(async () => {
  const server = createServer((req, res) => {
    const parsedUrl = parse(req.url!, true);
    handle(req, res, parsedUrl);
  });

  const io = new Server(server, {
    cors: {
      origin: process.env.NEXT_PUBLIC_APP_URL,
      methods: ["GET", "POST"],
      credentials: true,
    },
    transports: ["websocket", "polling"],
  });

  // Redis adapter for horizontal scaling
  if (process.env.REDIS_URL) {
    const pubClient = createClient({ url: process.env.REDIS_URL });
    const subClient = pubClient.duplicate();
    await Promise.all([pubClient.connect(), subClient.connect()]);
    io.adapter(createAdapter(pubClient, subClient));
  }

  // Middleware for authentication
  io.use(async (socket, next) => {
    const token = socket.handshake.auth.token;
    if (!token) {
      return next(new Error("Authentication required"));
    }

    try {
      const user = await verifyToken(token);
      socket.data.user = user;
      next();
    } catch (error) {
      next(new Error("Invalid token"));
    }
  });

  // Connection handler
  io.on("connection", (socket) => {
    console.log(`User connected: ${socket.data.user.id}`);

    // Join user-specific room
    socket.join(`user:${socket.data.user.id}`);

    // Handle joining rooms
    socket.on("join:room", async (roomId: string) => {
      const canJoin = await checkRoomAccess(socket.data.user.id, roomId);
      if (canJoin) {
        socket.join(`room:${roomId}`);
        socket.to(`room:${roomId}`).emit("user:joined", {
          userId: socket.data.user.id,
          username: socket.data.user.name,
        });
      }
    });

    // Handle messages
    socket.on("message:send", async (data: { roomId: string; content: string }) => {
      const message = await saveMessage({
        roomId: data.roomId,
        userId: socket.data.user.id,
        content: data.content,
      });

      io.to(`room:${data.roomId}`).emit("message:new", message);
    });

    // Handle typing indicators
    socket.on("typing:start", (roomId: string) => {
      socket.to(`room:${roomId}`).emit("typing:update", {
        userId: socket.data.user.id,
        username: socket.data.user.name,
        isTyping: true,
      });
    });

    socket.on("typing:stop", (roomId: string) => {
      socket.to(`room:${roomId}`).emit("typing:update", {
        userId: socket.data.user.id,
        isTyping: false,
      });
    });

    // Handle disconnection
    socket.on("disconnect", () => {
      console.log(`User disconnected: ${socket.data.user.id}`);
    });
  });

  // Make io accessible for API routes
  (global as any).io = io;

  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});
```

## Client-Side Hook

### useSocket Hook

```typescript
// hooks/useSocket.ts
"use client";

import { useEffect, useRef, useCallback, useState } from "react";
import { io, Socket } from "socket.io-client";
import { useSession } from "next-auth/react";

interface UseSocketOptions {
  autoConnect?: boolean;
  reconnection?: boolean;
}

export function useSocket(options: UseSocketOptions = {}) {
  const { autoConnect = true, reconnection = true } = options;
  const { data: session } = useSession();
  const socketRef = useRef<Socket | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    if (!session?.user || !autoConnect) return;

    const socket = io(process.env.NEXT_PUBLIC_SOCKET_URL || "", {
      auth: { token: session.accessToken },
      reconnection,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
      transports: ["websocket", "polling"],
    });

    socket.on("connect", () => {
      setIsConnected(true);
      setError(null);
    });

    socket.on("disconnect", () => {
      setIsConnected(false);
    });

    socket.on("connect_error", (err) => {
      setError(err);
      setIsConnected(false);
    });

    socketRef.current = socket;

    return () => {
      socket.disconnect();
    };
  }, [session, autoConnect, reconnection]);

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

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

  const joinRoom = useCallback((roomId: string) => {
    emit("join:room", roomId);
  }, [emit]);

  const leaveRoom = useCallback((roomId: string) => {
    emit("leave:room", roomId);
  }, [emit]);

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

## Real-Time Chat Component

```typescript
// components/Chat.tsx
"use client";

import { useState, useEffect, useRef } from "react";
import { useSocket } from "@/hooks/useSocket";

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

export function Chat({ roomId }: { roomId: string }) {
  const { isConnected, emit, on, joinRoom } = useSocket();
  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>();

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

  useEffect(() => {
    const unsubMessage = on("message:new", (message: Message) => {
      setMessages((prev) => [...prev, message]);
    });

    const unsubTyping = on("typing:update", (data: {
      userId: string;
      username: string;
      isTyping: boolean;
    }) => {
      setTypingUsers((prev) => {
        const next = new Map(prev);
        if (data.isTyping) {
          next.set(data.userId, data.username);
        } else {
          next.delete(data.userId);
        }
        return next;
      });
    });

    return () => {
      unsubMessage();
      unsubTyping();
    };
  }, [on]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleTyping = () => {
    emit("typing:start", roomId);
    
    if (typingTimeoutRef.current) {
      clearTimeout(typingTimeoutRef.current);
    }
    
    typingTimeoutRef.current = setTimeout(() => {
      emit("typing:stop", roomId);
    }, 2000);
  };

  const sendMessage = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim()) return;

    emit("message:send", { roomId, content: input });
    setInput("");
    emit("typing:stop", roomId);
  };

  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 gap-2">
            <span className="font-bold">{message.username}:</span>
            <span>{message.content}</span>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>

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

      <form onSubmit={sendMessage} className="p-4 border-t">
        <input
          value={input}
          onChange={(e) => {
            setInput(e.target.value);
            handleTyping();
          }}
          placeholder="Type a message..."
          className="w-full px-4 py-2 border rounded-lg"
        />
      </form>
    </div>
  );
}
```

## Server-Side Emit from API Routes

```typescript
// app/api/notify/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const { userId, event, data } = await req.json();
  
  const io = (global as any).io;
  if (io) {
    io.to(`user:${userId}`).emit(event, data);
  }

  return NextResponse.json({ success: true });
}
```

This WebSocket guide covers real-time features with Socket.io, authentication, Redis scaling, and React hooks.

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