Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions CHAT_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Real-Time Chat Room with Cloudflare Durable Objects

A modern, mobile-friendly chat room application built with Cloudflare Workers, Durable Objects, React Router, and Tailwind CSS.

## Features

- 🚀 **Real-time messaging** - Instant message delivery using WebSockets
- 📱 **Mobile-friendly** - Responsive design that works on all devices
- ⚡ **Serverless** - Powered by Cloudflare Workers for global performance
- 🔄 **Persistent storage** - Messages stored in Durable Objects
- 🏠 **Multiple rooms** - Support for different chat rooms (currently using "general")
- 🎨 **Modern UI** - Clean, intuitive interface with Tailwind CSS

## Architecture

### Backend (Cloudflare Workers + Durable Objects)

- **`workers/app.ts`** - Main worker with ChatRoom Durable Object class and routing logic
- **`wrangler.jsonc`** - Configuration for Cloudflare Workers and Durable Objects

### Frontend (React Router + Tailwind CSS)

- **`app/routes/home.tsx`** - Welcome page with link to chat room
- **`app/routes/chat.tsx`** - Main chat interface with real-time messaging
- **`app/routes.ts`** - Route configuration

## How It Works

1. **User Joins**: Users enter a username and connect to the chat room
2. **WebSocket Connection**: Browser establishes WebSocket connection to `/chat` endpoint
3. **Durable Object**: Request is routed to ChatRoom Durable Object instance
4. **Message History**: New users receive the last 50 messages
5. **Real-time Updates**: All connected users receive new messages instantly
6. **Persistent Storage**: Messages are stored in Durable Object storage

## Usage

### Development

```bash
# Install dependencies
npm install

# Start development server
npm run dev
```

### Deployment

```bash
# Build and deploy to Cloudflare
npm run deploy
```

### Accessing the Chat

1. Open the application in your browser
2. Click "Join Chat Room" on the home page
3. Enter your username
4. Start chatting!

## Technical Details

### WebSocket Communication

The chat uses WebSockets for real-time communication with the following message types:

- `history` - Sent to new users with recent messages
- `new_message` - Broadcast when a user sends a message
- `user_joined` - Notification when a user joins (future enhancement)

### Message Format

```typescript
interface ChatMessage {
id: string; // Unique message ID
username: string; // Sender's username
message: string; // Message content
timestamp: number; // Unix timestamp
}
```

### Room Support

The application supports multiple chat rooms via URL parameters:
- Default room: `general`
- Custom room: Add `?room=roomname` to WebSocket URL

### Storage

- Messages are stored in Durable Object storage
- Last 1000 messages are kept per room
- New users see the last 50 messages

## Mobile Optimization

- Responsive design works on all screen sizes
- Touch-friendly interface
- Optimized message input for mobile keyboards
- Smooth scrolling to new messages
- Compact UI elements for small screens

## Security Considerations

- Input validation on message content (max 1000 characters)
- Username validation (max 50 characters)
- WebSocket connection limits handled by Cloudflare
- No authentication implemented (add as needed)

## Future Enhancements

- User authentication
- Message reactions/emojis
- File sharing
- Private messaging
- User presence indicators
- Message search
- Chat room creation/management
- Message encryption
136 changes: 136 additions & 0 deletions DEPLOYMENT_GUIDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Deployment Guide for Chat Room with Durable Objects

## The Issue

The deployment is failing because **Durable Objects with migrations require `wrangler deploy`** for the initial deployment, but the platform is using `wrangler versions upload`.

Error: `"migrations must be fully applied by running 'wrangler deploy'"`

## Solutions

### Option 1: Manual Deployment (Recommended)

Deploy manually using the correct command:

```bash
# 1. Clone the repository locally
git clone <your-repo-url>
cd <your-repo-name>

# 2. Install dependencies
npm install

# 3. Build the application
npm run build

# 4. Deploy with migrations
npx wrangler deploy --compatibility-date=2025-04-04

# 5. (Optional) Set up subsequent deployments
npx wrangler versions upload
```

### Option 2: Configure Platform Deployment

If using Cloudflare Pages or similar platform:

1. **Change the deployment command** in your platform settings from:
```
npx wrangler versions upload
```
To:
```
npm run deploy
```

2. **Or use the custom deployment script**:
```bash
chmod +x deploy.sh
./deploy.sh
```

### Option 3: Two-Phase Deployment

If the platform doesn't support `wrangler deploy`:

1. **First, deploy without migrations** (temporarily comment out the migrations section in `wrangler.jsonc`)
2. **Then run migrations separately**:
```bash
npx wrangler deploy --compatibility-date=2025-04-04
```

## After Initial Deployment

Once the migration is applied successfully, subsequent deployments can use:
- `wrangler versions upload` (for gradual deployments)
- `wrangler deploy` (for immediate deployments)

## Verifying Deployment

After successful deployment, test:

1. **Visit your worker URL**
2. **Click "Join Chat Room"**
3. **Enter a username and start chatting**
4. **Test on mobile devices**

## Troubleshooting

### Migration Already Applied Error
If you get "migration already applied", you can safely use:
```bash
npx wrangler versions upload
```

### WebSocket Connection Issues
- Ensure your domain supports WebSocket upgrades
- Check browser console for connection errors
- Verify the Durable Object binding is working

### Storage Issues
- Durable Objects automatically handle storage
- Messages persist across deployments
- Check Cloudflare dashboard for Durable Object logs

## Platform-Specific Instructions

### Cloudflare Pages
1. Go to your Pages project settings
2. Change "Build command" to: `npm run build`
3. Change "Deploy command" to: `npm run deploy`

### GitHub Actions
Add to your workflow:
```yaml
- name: Deploy to Cloudflare Workers
run: npm run deploy
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
```

### Other CI/CD Platforms
Ensure the deployment step runs:
```bash
npm run deploy
```
Instead of calling wrangler directly.

## Success Indicators

✅ **Build completes** without TypeScript errors
✅ **Migration applies** without conflicts
✅ **Durable Object binding** is created
✅ **WebSocket connections** work
✅ **Messages persist** between sessions
✅ **Mobile interface** is responsive

## Need Help?

If you continue to have deployment issues:

1. **Check Cloudflare Workers dashboard** for error logs
2. **Verify your wrangler authentication**: `npx wrangler whoami`
3. **Try local development**: `npm run dev`
4. **Check the browser console** for WebSocket errors

The chat room should work perfectly once the initial migration is applied!
7 changes: 5 additions & 2 deletions app/routes.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { type RouteConfig, index } from "@react-router/dev/routes";
import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [index("routes/home.tsx")] satisfies RouteConfig;
export default [
index("routes/home.tsx"),
route("chat", "routes/chat.tsx")
] satisfies RouteConfig;
Loading