WebSocket Real-Time Chat

fullstack
TypeScript
scaffolding
playful
Remix

Build a real-time chat application using WebSocket with rooms and presence.

12/8/2025

Prompt

Generate a production-ready real-time chat application using WebSocket with rooms, presence, typing indicators, and message persistence for the following requirements:

Application Overview

Platform Details

  • Backend Framework: [Node.js + ws / Socket.io / Bun / Deno / Go]
  • Frontend Framework: [React / Next.js / Vue / Svelte / React Native]
  • Database: [PostgreSQL / MongoDB / Redis / Supabase / None]
  • Authentication: [JWT / Session / OAuth / Custom / None]
  • Deployment: [Vercel / Railway / AWS / Heroku / Custom]

Chat Features

  • Chat Type: [One-on-one / Group chat / Both]
  • Rooms: [Multiple rooms / Single room / Dynamic rooms]
  • Message Persistence: [Save to database / In-memory only]
  • File Sharing: [Yes / No]
  • Typing Indicators: [Yes / No]
  • Read Receipts: [Yes / No]
  • User Presence: [Online/offline status / Last seen / None]

Chat Functionality

Rooms/Channels

Room Types

  • Public Rooms: [Anyone can join]
  • Private Rooms: [Invite-only]
  • Direct Messages: [One-on-one chats]
  • Group Chats: [Multiple users]

Room Features

  • Room Creation: [Users can create rooms / Admin only]
  • Room Discovery: [List all public rooms / Search]
  • Room Capacity: [Unlimited / Max X users]
  • Room Persistence: [Rooms persist / Temporary]

Message Features

Message Types

  • Text Messages: [Plain text]
  • Rich Text: [Markdown / HTML / Formatting]
  • Emojis/Reactions: [Emoji picker / Reactions to messages]
  • File Attachments: [Images / Documents / Videos]
  • Links: [URL previews / Embeds]
  • Code Blocks: [Syntax highlighting]

Message Actions

  • Edit Messages: [Yes / No]
  • Delete Messages: [Yes / No]
  • Reply/Thread: [Reply to specific messages]
  • Pin Messages: [Pin important messages]
  • Search Messages: [Search chat history]

User Features

Presence

  • Online Status: [Online / Away / Offline]
  • Last Seen: [Show last active time]
  • Typing Indicator: [Show when user is typing]
  • User List: [Show online users in room]

User Profile

  • Username: [Display name]
  • Avatar: [Profile picture]
  • Status Message: [Custom status]
  • User Roles: [Admin / Moderator / User]

Notifications

  • New Message: [Desktop notification / Sound / Badge]
  • Mentions: [Notify when @mentioned]
  • Unread Count: [Show unread message count]
  • Push Notifications: [Mobile push notifications]

WebSocket Events

Client → Server Events

Connection Events

  • connect: [Initial connection]
  • authenticate: [Send auth token]
  • disconnect: [Clean disconnect]

Room Events

  • join-room: [Join a chat room]
    • Payload: [roomId, userId, username]
  • leave-room: [Leave a room]
    • Payload: [roomId, userId]
  • create-room: [Create new room]
    • Payload: [roomName, isPrivate, members]

Message Events

  • send-message: [Send chat message]
    • Payload: [roomId, userId, text, attachments]
  • edit-message: [Edit existing message]
    • Payload: [messageId, newText]
  • delete-message: [Delete message]
    • Payload: [messageId]
  • typing-start: [User started typing]
    • Payload: [roomId, userId, username]
  • typing-stop: [User stopped typing]
    • Payload: [roomId, userId]

Presence Events

  • status-change: [Update online status]
    • Payload: [userId, status]

Server → Client Events

Connection Events

  • connected: [Connection successful]
  • authenticated: [Authentication successful]
  • error: [Connection or auth error]

Room Events

  • room-joined: [Successfully joined room]
    • Payload: [roomId, users, messageHistory]
  • user-joined: [Another user joined]
    • Payload: [roomId, userId, username]
  • user-left: [User left room]
    • Payload: [roomId, userId, username]
  • room-created: [New room created]
    • Payload: [room]

Message Events

  • new-message: [New message received]
    • Payload: [messageId, roomId, userId, username, text, timestamp, attachments]
  • message-edited: [Message was edited]
    • Payload: [messageId, newText, editedAt]
  • message-deleted: [Message was deleted]
    • Payload: [messageId]
  • typing-indicator: [User is typing]
    • Payload: [roomId, userId, username, isTyping]

Presence Events

  • user-status: [User status changed]
    • Payload: [userId, status, lastSeen]
  • online-users: [List of online users]
    • Payload: [users]

Server Implementation

WebSocket Server Setup

  • Port: [8080 / 3001 / Custom]
  • Path: [/ws / /socket / Custom]
  • CORS: [Allowed origins]
  • Max Connections: [Per user / Total]

Connection Management

  • Authentication: [Verify JWT on connect / Session-based]
  • Connection Tracking: [Map userId to WebSocket connection]
  • Reconnection: [Handle reconnection with same session]
  • Heartbeat/Ping: [Ping every X seconds to keep alive]

Room Management

  • Room Storage: [In-memory Map / Redis / Database]
  • Room Data Structure:
    • roomId
    • roomName
    • members (Set of userIds)
    • connections (Set of WebSocket connections)
    • createdAt
    • isPrivate

Message Handling

  • Message Validation: [Validate message content, length]
  • Rate Limiting: [Max X messages per minute]
  • Spam Prevention: [Duplicate message detection]
  • Broadcasting: [Send to all room members except sender]

Persistence (if enabled)

Database Schema

Messages Table
  • id: [Primary key]
  • room_id: [Foreign key to rooms]
  • user_id: [Foreign key to users]
  • username: [Denormalized username]
  • text: [Message content]
  • attachments: [JSON array of file URLs]
  • edited: [Boolean]
  • deleted: [Boolean]
  • created_at: [Timestamp]
  • updated_at: [Timestamp]
Rooms Table
  • id: [Primary key]
  • name: [Room name]
  • is_private: [Boolean]
  • created_by: [User ID]
  • created_at: [Timestamp]
Room Members Table
  • room_id: [Foreign key]
  • user_id: [Foreign key]
  • joined_at: [Timestamp]
  • role: [admin, moderator, member]

Client Implementation

WebSocket Client Setup

  • Connection URL: [ws://localhost:8080 / wss://domain.com]
  • Auto-Reconnect: [Retry with exponential backoff]
  • Connection State: [connecting, connected, disconnected, error]

React Hooks

useWebSocket Hook

  • Purpose: [Manage WebSocket connection]
  • Returns: [ws, connectionState, send, disconnect]
  • Features: [Auto-reconnect, event listeners, cleanup]

useChat Hook

  • Purpose: [Manage chat state and messages]
  • State: [messages, users, typingUsers, unreadCount]
  • Actions: [sendMessage, editMessage, deleteMessage, joinRoom, leaveRoom]

usePresence Hook

  • Purpose: [Track user presence]
  • State: [onlineUsers, userStatuses]
  • Actions: [updateStatus, trackTyping]

UI Components

ChatRoom Component

  • Features:
    • Message list with auto-scroll
    • Message input with send button
    • User list sidebar
    • Typing indicators
    • Unread message indicator

Message Component

  • Features:
    • User avatar and username
    • Message text with formatting
    • Timestamp
    • Edit/delete buttons (own messages)
    • Reactions (if enabled)

MessageInput Component

  • Features:
    • Text input with auto-resize
    • Send button
    • File upload button
    • Emoji picker
    • Typing indicator trigger

UserList Component

  • Features:
    • List of online users
    • User avatars and names
    • Online/offline status
    • User count

RoomList Component

  • Features:
    • List of available rooms
    • Unread message badges
    • Create room button
    • Search/filter rooms

Advanced Features

Typing Indicators

  • Trigger: [On input change]
  • Debounce: [Stop typing after X seconds of inactivity]
  • Display: [Show "User is typing..." in chat]

Read Receipts

  • Track: [Last read message per user]
  • Display: [Checkmarks or "Read by X users"]
  • Storage: [In-memory / Database]

Message Reactions

  • Reactions: [👍 ❤️ 😂 😮 😢 🎉]
  • Display: [Show reaction count below message]
  • Toggle: [Add/remove reaction]

File Uploads

  • Upload Method: [Direct to server / Cloud storage (S3, Cloudinary)]
  • File Types: [Images, documents, videos]
  • Max Size: [5MB / 10MB / Custom]
  • Preview: [Image thumbnails, file icons]

Search

  • Search Scope: [Current room / All rooms]
  • Search By: [Message text / Username / Date]
  • Results: [Highlight matches, jump to message]

Moderation

  • Mute Users: [Prevent user from sending messages]
  • Ban Users: [Remove and prevent from rejoining]
  • Delete Messages: [Moderators can delete any message]
  • Slow Mode: [Limit message frequency]

Security

Authentication

  • Method: [JWT token in connection / Session cookie]
  • Token Validation: [Verify on connect and periodically]
  • Token Refresh: [Handle token expiration]

Authorization

  • Room Access: [Check if user can join room]
  • Message Permissions: [Check if user can edit/delete]
  • Admin Actions: [Verify admin/moderator role]

Input Validation

  • Message Length: [Max X characters]
  • XSS Prevention: [Sanitize HTML, escape special characters]
  • Rate Limiting: [Max messages per minute]
  • Spam Detection: [Block duplicate messages]

Connection Security

  • WSS (TLS): [Use secure WebSocket in production]
  • Origin Validation: [Check request origin]
  • CSRF Protection: [Token-based protection]

Performance Optimization

Message Pagination

  • Load Strategy: [Load last 50 messages / Infinite scroll]
  • Lazy Loading: [Load older messages on scroll]
  • Virtual Scrolling: [For large message lists]

Connection Pooling

  • Max Connections: [Limit per user / per server]
  • Load Balancing: [Distribute across multiple servers]
  • Sticky Sessions: [Route user to same server]

Caching

  • Message Cache: [Cache recent messages in Redis]
  • User Cache: [Cache user data]
  • Room Cache: [Cache room metadata]

Code Generation Requirements

Generate a complete real-time chat application including:

  1. WebSocket Server:

    • Server setup with ws or Socket.io
    • Connection handling with authentication
    • Room management (join, leave, create)
    • Message broadcasting
    • Typing indicator handling
    • Presence tracking
    • Heartbeat/ping for connection health
  2. Event Handlers:

    • Handler for each client event
    • Message validation and sanitization
    • Rate limiting logic
    • Error handling
  3. Database Layer (if persistence enabled):

    • Database schema (messages, rooms, room_members)
    • Migrations
    • Message CRUD operations
    • Room CRUD operations
    • Message history retrieval
  4. Client WebSocket Integration:

    • WebSocket connection setup
    • Auto-reconnect logic
    • Event listeners for all server events
    • Send functions for all client events
  5. React Hooks:

    • useWebSocket hook
    • useChat hook
    • usePresence hook
    • useTypingIndicator hook
  6. UI Components:

    • ChatRoom component
    • Message component
    • MessageInput component
    • UserList component
    • RoomList component
    • TypingIndicator component
  7. Authentication:

    • JWT token generation and validation
    • WebSocket authentication middleware
    • Token refresh logic
  8. File Upload (if enabled):

    • File upload endpoint
    • Cloud storage integration (S3, Cloudinary)
    • File URL generation
    • File preview components
  9. Notifications:

    • Desktop notification API integration
    • Unread message counter
    • Sound notifications
    • Push notification setup (optional)
  10. Testing:

    • WebSocket connection tests
    • Message sending/receiving tests
    • Room join/leave tests
    • Reconnection tests
  11. Documentation:

    • WebSocket event documentation
    • API documentation
    • Setup guide
    • Deployment guide

Output production-ready real-time chat application following best practices with:

  • Reliable WebSocket connection with auto-reconnect
  • Room-based chat with join/leave functionality
  • Real-time message broadcasting
  • Typing indicators and presence tracking
  • Message persistence (if enabled)
  • Authentication and authorization
  • Input validation and XSS prevention
  • Rate limiting and spam prevention
  • File upload support (if enabled)
  • Read receipts and reactions (if enabled)
  • Responsive UI with auto-scroll
  • Unread message tracking
  • Desktop notifications
  • Proper error handling
  • Connection health monitoring (heartbeat/ping)
  • Scalable architecture
  • Clean code with TypeScript types
  • Comprehensive documentation

Tags

websocket
realtime
chat
nodejs

Tested Models

gpt-4
claude-3-5-sonnet

Comments (0)

Sign in to leave a comment

Sign In
WebSocket Real-Time Chat | vibeprompt.directory