Build real-time applications with WebSocket and Socket.io. Learn connection management, rooms, authentication, scaling with Redis, and Next.js integration for live features.
# 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.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.