Skip to content
Architecture

Built on proven technology

React, Node.js, PostgreSQL, Redis, AWS — the same stack trusted by Slack, Netflix, and Uber. Any JavaScript developer can be productive on day one.

The Stack

Six layers of production-grade infrastructure, each chosen for reliability, performance, and developer familiarity.

Frontend
Next.js 16 + React 19
TypeScript, App Router, Framer Motion animations, Socket.IO client, IndexedDB offline cache.
Backend
Node.js + Express
TypeScript, 88 REST endpoints, 85+ Socket.IO event types, file uploads, email & SMS services.
Database
PostgreSQL 16
Prisma ORM with 9 models, type-safe queries, automatic migrations, indexed for fast lookups.
Caching
Redis 7
Presence tracking, rate limiting, pub/sub across instances, token blacklisting, session management.
AI
OpenAI GPT-4o-mini
Luna chatbot assistant, automatic conversation summaries, streaming token-by-token responses.
Cloud
AWS Infrastructure
EC2 (PM2 cluster), RDS (managed Postgres), ElastiCache (Redis), S3 (media), Nginx reverse proxy.

Message Delivery Pipeline

From keypress to read receipt in under 100ms. Six stages, fully observable, horizontally scalable.

1
Emit
Client sends "message:send" via Socket.IO with content, type, and recipient.
2
Validate
Server validates auth, permissions, rate limits, and message payload.
3
Persist
Message written to PostgreSQL with sender, recipient, timestamp, and status.
4
Deliver
Server emits "message:new" to recipient's Socket room in real time.
5
Acknowledge
"message:delivered" fires back to sender. UI updates from clock to tick.
6
Read Receipt
When message scrolls into view, "message:read" completes the cycle.

End-to-end delivery completes in under 100ms. Offline messages are persisted in PostgreSQL and delivered automatically on reconnection. The Socket.IO Redis adapter enables horizontal scaling across multiple backend instances.

Database Schema

9 Prisma models with type-safe queries, automatic migrations, and indexed fields for fast lookups.

User
Credentials, profile fields, settings, presence state, guest sessions, avatar and cover URLs.
Conversation
DM thread between two users. Tracks last message timestamp for sort order.
Message
Content, type (text/voice/image/video/file), sender, recipient or group, status, reply ref.
Group
Name, description, avatar, cover image, creation date, and metadata.
GroupMember
Join table: user ↔ group with role (Owner, Admin, Member) and invite status.
Friendship
Bidirectional friend connection with status: pending, accepted, or blocked.
Reaction
Emoji reaction on a message by a user. Unique constraint prevents duplicates.
MessageEditHistory
Full edit audit trail — original content, new content, and timestamp per revision.
Session
Active auth sessions for token management, refresh rotation, and multi-device support.

Built for developers, by a developer

Every tooling decision was made to maximise developer productivity. One command to start, strict types everywhere, and tests that run in seconds.

One Command Setup
Run bash dev.sh — Docker spins up PostgreSQL and Redis, migrations run, all five servers start with hot reload. Ready in under 60 seconds.
TypeScript Strict Mode
Every file — frontend, backend, and widget — is strict TypeScript. No implicit any, full type inference, and Prisma-generated types for the database.
Three-Tier Testing
3,000+ tests across Jest (unit/integration) and Playwright (E2E). 99% frontend coverage. Tests run in parallel and complete in under 30 seconds.
Hot Reload Everything
Frontend (Next.js Fast Refresh), backend (nodemon), and widget (esbuild watcher) — all live-reload on save. No manual restarts.
Git Hooks & CI
Husky pre-commit runs all tests. Post-commit auto-increments version and updates the changelog. Every commit is validated before it lands.
Storybook
69 component stories with dark and light theme variants. Visual documentation for every UI component, tested in isolation.
Terminal
git clone https://github.com/neofuture/chatr.git
cd chatr
cp .env.example .env
bash dev.sh

# ✅ PostgreSQL + Redis running (Docker)
# ✅ Migrations applied
# ✅ Frontend on localhost:3000
# ✅ Backend on localhost:3001
# ✅ Widget dev server on localhost:3003
# ✅ All watchers active

88 Endpoints, Fully Documented

Every endpoint is documented in Swagger UI. Authentication, messaging, groups, files, AI — all accessible via standard REST with JWT auth.

Send a Message
POST /api/messages
Authorization: Bearer <token>
Content-Type: application/json

{
  "conversationId": "abc-123",
  "content": "Hello from the API!",
  "type": "text"
}

// → 201 Created
// Real-time delivery via WebSocket
WebSocket Events
import { io } from "socket.io-client";

const socket = io("https://your-server.com", {
  auth: { token: "Bearer <jwt>" }
});

socket.on("message:new", (msg) => {
  console.log("New message:", msg);
});

socket.on("user:typing", ({ userId }) => {
  showTypingIndicator(userId);
});

Interactive API docs: Full Swagger UI is available at /api-docs on any running instance. Explore, test, and integrate directly from your browser.

Scales without rewriting

Designed for production from day one. Horizontal scaling, managed databases, and battle-tested infrastructure patterns used by teams at every scale.

PM2 Cluster Mode
Backend runs in cluster mode across all CPU cores. Add instances behind a load balancer for horizontal scaling — no code changes.
Managed PostgreSQL (RDS)
Automated backups, point-in-time recovery, read replicas for scaling reads. Prisma handles connection pooling.
Redis Adapter (ElastiCache)
Socket.IO Redis adapter enables WebSocket events across multiple backend instances. Managed Redis with failover.
S3 Media Storage
All uploaded files stored in S3 with server-side processing (Sharp for images). CDN-ready URLs, unlimited storage.
Nginx Reverse Proxy
SSL termination, WebSocket proxying, gzip compression, and static asset caching. Let's Encrypt auto-renewal.
Zero-Downtime Deploy
PM2 handles rolling restarts. Deploy new code while existing connections stay active. No maintenance windows.

Enterprise-grade security at every layer

Not bolted on as an afterthought. Authentication, authorisation, and data protection are built into the architecture from the ground up.

JWT + Refresh Tokens
Short-lived access tokens with secure HTTP-only refresh tokens. Automatic rotation, server-side blacklisting on logout.
Multi-Factor Auth
Email verification, SMS codes (The SMS Works), and TOTP authenticator apps. Users choose their security level.
Redis Rate Limiting
Per-endpoint, per-user rate limits enforced via Redis. Prevents brute-force, spam, and API abuse.
Server-Side Enforcement
Every permission check happens server-side. The frontend is a UI layer — all business logic is authoritative on the backend.
Input Validation & Sanitisation
All user input validated and sanitised server-side. SQL injection, XSS, and CSRF protections throughout.
Granular Privacy Controls
Users control visibility of online status, last seen, profile info, and read receipts on a per-field basis.

Quality Assurance

Over 3,000 automated tests across three tiers — every component, endpoint, and user flow is covered.

3,000+
Total Tests
1,475
Frontend
1,133
Backend
168
End-to-End

Frontend tests cover every React component, hook, context, and page at 99% coverage. Backend tests validate every API endpoint, auth flow, Socket handler, and service integration. End-to-end tests use Playwright driving Desktop Chrome and iPhone 14 with two simultaneous users verifying real-time delivery, typing indicators, and presence.

Developer Dashboard

Custom-built project intelligence with live metrics, code health gauges, commit intelligence, security auditing, and an embedded test runner — all auto-refreshing in real time.

Dashboard — metric cards, code health gauges, commit intelligence
Dashboard — metric cards, code health gauges, commit intelligence
Full analytics dashboard
Full analytics dashboard — test runner, security audit, build health

Storybook — 69 component stories

Every UI component is documented in Storybook with interactive stories, dark and light theme variants, and accessibility checks. Browse, test, and inspect components in complete isolation.

69 Stories
Every major component — messaging, profiles, settings, navigation, image croppers, panels — has dedicated Storybook stories.
Dark & Light Variants
Each story renders in both dark and light themes. Visual consistency verified across every component.
Accessibility Checks
The a11y addon audits every story for WCAG violations — ARIA roles, contrast ratios, keyboard navigation.
Open Storybook

Deploy anywhere

Run locally with Docker, deploy to AWS with one command, or host on any cloud provider. The stack is standard — no proprietary lock-in.

Local (Docker)
bash dev.sh — Docker Compose spins up PostgreSQL and Redis. All servers start with hot reload. Development ready in under 60 seconds.
AWS (Production)
bash aws.sh — Deploys to EC2 with RDS, ElastiCache, S3, Nginx, SSL, and PM2 cluster mode.
Any Cloud
Standard Node.js + PostgreSQL + Redis. Works on DigitalOcean, Hetzner, Railway, Render, Azure, GCP — anywhere that runs Docker or Node.js.

Clean, modular project structure

Three workspaces, strict TypeScript, and clear separation of concerns. Any developer can navigate the codebase in minutes.

Frontend
frontend/
├── src/app/          # Next.js pages
├── src/components/   # 186 React components
├── src/contexts/     # 9 React contexts
├── src/hooks/        # 15+ custom hooks
├── src/lib/          # Utilities & helpers
├── src/services/     # API & socket clients
└── 134 test files    # 99% coverage
Backend
backend/
├── src/routes/       # 88 REST endpoints
├── src/socket/       # 85+ event handlers
├── src/services/     # Business logic
├── src/middleware/    # Auth, rate limiting
├── src/utils/        # Helpers & validators
├── prisma/           # 9 models, migrations
└── 27 test files     # 73% coverage
Widget & Tooling
widget/
├── src/chatr.ts      # Standalone JS widget
├── src/styles/       # Scoped CSS
└── tests/            # 54 tests

e2e/
├── 14 spec files     # Playwright E2E
├── Desktop Chrome    # + iPhone 14
Documentation/        # Markdown guides
scripts/              # Dev & deploy tools

Explore the full platform

Read the documentation, explore the dashboard, or see the complete product overview.