Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

34 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Realtime Private Chat

A private, real-time, self-destructing messaging platform built with Next.js, Elysia, and Upstash.

Features

Core Functionality

  • Private Room Creation: Generate unique, secure chat rooms with a single click
  • Real-time Messaging: Instant message delivery using Upstash Realtime channels
  • Self-Destructing Rooms: Rooms automatically expire after 12 minutes (configurable)
  • Manual Destruction: Users can manually destroy rooms at any time, permanently deleting all messages
  • User Limit: Maximum 2 users per room for private, one-on-one conversations
  • Anonymous Identity: Auto-generated anonymous usernames (e.g., anon-lion-abc12) stored in localStorage
  • Room Link Sharing: Easy room URL copying for quick sharing with another user

Security & Privacy

  • Token-Based Authentication: HTTP-only cookies with secure tokens for room access
  • Room Capacity Enforcement: Middleware prevents more than 2 users from joining a room
  • Message Privacy: Messages are only visible to authenticated room participants
  • Auto-Expiration: All data (messages, room metadata) automatically deleted after TTL expires
  • Secure Cookies: HttpOnly, Secure (in production), and SameSite=strict cookie policies

User Experience

  • Live Countdown Timer: Real-time display of remaining room lifetime
  • Visual Alerts: Color-coded timer (amber β†’ red) when time is running low
  • Error Handling: Clear error messages for room not found, room full, and room destroyed scenarios
  • Responsive Design: Clean, modern UI with dark theme optimized for all screen sizes
  • Message Timestamps: Messages display time sent (HH:mm format)
  • Sender Identification: Distinguishes between "YOU" and other participants with color coding
  • Auto-Scroll: Messages automatically scroll to show new content

Tech Stack

Frontend

  • Next.js - React framework with App Router
  • React - UI library
  • TailwindCSS - Utility-first CSS framework
  • @tanstack/react-query - Data fetching and state management

Backend

  • Elysia - Fast, type-safe web framework
  • @elysiajs/eden - Type-safe API client for frontend-backend communication

Infrastructure

  • Upstash Redis - Cloud-native Redis for data storage
  • @upstash/realtime - Real-time pub/sub messaging
  • Zod - Schema validation (used via Elysia)

Architecture

Data Storage (Upstash Redis)

  • meta_room:{roomId} - Room metadata hash
    • connected: Array of authenticated user tokens
    • createdAt: Room creation timestamp
    • TTL: 12 minutes (720 seconds)
  • messages:{roomId} - List of messages in the room
    • Each message contains: id, sender, text, timestamp, roomId, token
    • TTL: Synced with room TTL
  • {roomId} - Additional room data storage
    • TTL: Synced with room TTL

Real-time Events

  • chat.message - Broadcasted when a new message is sent
  • chat.destroy - Broadcasted when a room is manually destroyed

API Endpoints

Room Management

  • POST /api/room/create - Create a new chat room
    • Returns: { roomId: string }
  • GET /api/room/ttl?roomId={roomId} - Get remaining room lifetime
    • Returns: { ttl: number } (seconds)
  • DELETE /api/room?roomId={roomId} - Destroy room immediately
    • Emits: chat.destroy event
    • Deletes: All room data and messages

Messages

  • POST /api/messages?roomId={roomId} - Send a message
    • Body: { sender: string, text: string }
    • Validation: sender max 100 chars, text max 1000 chars
    • Emits: chat.message event
  • GET /api/messages?roomId={roomId} - Get all messages in room
    • Returns: { messages: Message[] }
    • Note: Token only included for sender's own messages

Real-time

  • GET /api/realtime - WebSocket endpoint for real-time updates
    • Handled by Upstash Realtime

Middleware

  • Room Proxy (src/proxy.ts)
    • Validates room existence before access
    • Enforces 2-user limit per room
    • Generates and sets authentication tokens
    • Redirects on errors (room not found, room full)

Client-Side Hooks

  • useUsername - Generates and persists anonymous usernames
  • useRealtime - Subscribes to real-time events (chat.message, chat.destroy)

Installation

Prerequisites

  • Node.js 20+ installed
  • Upstash account with Redis and Realtime enabled

Setup

  1. Clone the repository

    git clone https://github.com/03aey/realtime-chat
    cd realtime-chat
  2. Install dependencies

    bun install
  3. Configure environment variables Create a .env file in the root directory:

    UPSTASH_REDIS_REST_URL=<your-upstash-redis-url>
    UPSTASH_REDIS_REST_TOKEN=<your-upstash-redis-token>

    Get these credentials from your Upstash Dashboard.

  4. Run development server

    bun dev
  5. Open in browser Navigate to localhost:3000

Usage Guide

Creating a Room

  1. Visit the homepage
  2. Your anonymous identifier is auto-generated and displayed
  3. Click "Create secure room"
  4. You'll be redirected to your new room

Sharing a Room

  1. In the room, click the "Copy" button next to the Room ID
  2. Share the URL with the person you want to chat with
  3. Only 2 users can join a room

Sending Messages

  1. Type your message in the input field
  2. Press Enter or click "SEND"
  3. Messages appear instantly for both participants
  4. Your messages are labeled "YOU" in green
  5. Other participant's messages are labeled with their identifier in blue

Destroying a Room

  1. Click the "Destroy now" button (πŸ’£ icon) in the header
  2. All messages are permanently deleted
  3. Both users are redirected to the homepage with a "ROOM DESTROYED" notice

Room Expiration

  • Rooms automatically expire after 12 minutes
  • A countdown timer shows remaining time
  • When time reaches 0, the room is destroyed
  • Users are redirected to homepage with "ROOM DESTROYED" notice

Configuration

Adjusting Room TTL

Edit ROOM_TTL_SECONDS in src/app/api/[[...slugs]]/route.ts:

const ROOM_TTL_SECONDS = 12 * 60; // Change this value (in seconds)

Customizing Usernames

Edit the ANIMALS array in src/hooks/use-username.ts:

const ANIMALS = [
	"Lion",
	"Tiger",
	"Elephant",
	// Add more animals here
];

Changing User Limit

Modify the capacity check in src/proxy.ts:

if (meta.connected.length >= 2) {
	// Change 2 to desired limit
	return NextResponse.redirect(new URL("/?error=room-full", req.url));
}

Project Structure

realtime-chat/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”‚   β”œβ”€β”€ [[...slugs]]/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ route.ts          # Main API routes (Elysia)
β”‚   β”‚   β”‚   β”‚   └── auth.ts           # Authentication middleware
β”‚   β”‚   β”‚   └── realtime/
β”‚   β”‚   β”‚       └── route.ts          # Upstash Realtime handler
β”‚   β”‚   β”œβ”€β”€ room/
β”‚   β”‚   β”‚   └── [roomId]/
β”‚   β”‚   β”‚       └── page.tsx          # Chat room UI
β”‚   β”‚   β”œβ”€β”€ layout.tsx                # Root layout
β”‚   β”‚   β”œβ”€β”€ page.tsx                  # Homepage
β”‚   β”‚   └── globals.css               # Global styles
β”‚   β”œβ”€β”€ components/
β”‚   β”‚   └── providers.tsx             # React Query provider
β”‚   β”œβ”€β”€ hooks/
β”‚   β”‚   └── use-username.ts           # Username generation hook
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ eden.ts                   # API client (Elysia Eden)
β”‚   β”‚   β”œβ”€β”€ realtime-client.ts        # Realtime client hook
β”‚   β”‚   β”œβ”€β”€ realtime.ts               # Realtime schema & config
β”‚   β”‚   └── redis.ts                  # Redis client
β”‚   └── proxy.ts                      # Room access middleware
β”œβ”€β”€ public/                           # Static assets
β”œβ”€β”€ .env                              # Environment variables
β”œβ”€β”€ package.json                      # Dependencies
β”œβ”€β”€ tsconfig.json                     # TypeScript config
β”œβ”€β”€ next.config.ts                    # Next.js config
└── tailwind.config.ts                # TailwindCSS config

Security Considerations

  • No Server-Side Logging: Messages are not logged or stored beyond Redis
  • Ephemeral Storage: All data is deleted when room expires or is destroyed
  • Token Validation: Each request validates room membership via tokens
  • Input Validation: All inputs are validated using Zod schemas
  • CORS: Configure CORS for production if needed
  • Rate Limiting: Consider adding rate limiting for production use

Troubleshooting

Room not found error

  • Room may have expired (12-minute TTL)
  • Room may have been manually destroyed
  • Invalid room ID in URL

Room full error

  • Maximum 2 users allowed per room
  • Wait for a user to leave or create a new room

Real-time updates not working

  • Check Upstash Realtime credentials
  • Verify WebSocket connection in browser dev tools
  • Ensure /api/realtime endpoint is accessible

Environment variables not loading

  • Verify .env file exists in root directory
  • Restart development server after adding variables
  • Check variable names match exactly

GitHub LinkedIn Portfolio Linktree

About

A secure, real-time private chat application with self-destructing rooms, anonymous users, and instant messaging powered by Next.js, Elysia, and Upstash.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages