A Twitter-like microblogging API built with TypeScript, Express.js, and PostgreSQL. This project demonstrates clean architecture principles, proper layer separation, and production-ready patterns for building scalable REST APIs.
This project follows Clean Architecture principles with clear separation of concerns:
src/
βββ domain/ # Business entities & interfaces
β βββ entities/ # Core domain models (User, Chirp)
βββ services/ # Business logic layer
β βββ chirp.service.ts # Chirp use cases
β βββ user.service.ts # User & auth use cases
β βββ content-filter.service.ts
βββ infrastructure/ # External concerns
β βββ auth/ # Authentication (JWT, Password hashing)
β βββ database/ # Database (Drizzle ORM, Repositories)
βββ presentation/ # HTTP layer
β βββ controllers/ # Request handlers
β βββ middleware/ # Express middleware
β βββ routes/ # Route definitions
βββ shared/ # Cross-cutting concerns
βββ constants.ts # Application constants
βββ errors/ # Custom error classes
| Layer | Responsibility |
|---|---|
| Domain | Pure business entities, no dependencies on frameworks |
| Application | Business logic, orchestrates domain entities |
| Infrastructure | Database access, external services, authentication |
| Presentation | HTTP concerns, request/response handling |
| Shared | Utilities used across all layers |
- User Management: Registration, authentication, profile updates
- Chirps (Tweets): Create, read, delete with 140-character limit
- Authentication: JWT access tokens + refresh token rotation
- Content Moderation: Automatic profanity filtering
- Premium Features: Chirpy Red subscription via webhook
- Database Migrations: Automated with Drizzle Kit
| Technology | Purpose |
|---|---|
| TypeScript | Type-safe JavaScript |
| Express.js 5 | Web framework |
| PostgreSQL | Primary database |
| Drizzle ORM | Type-safe database queries |
| Argon2 | Password hashing (winner of PHC) |
| JWT | Stateless authentication |
| Vitest | Unit testing |
- Node.js 20+ (see
.nvmrc) - PostgreSQL 14+
# Clone the repository
git clone https://github.com/yourusername/chirpy-server-ts.git
cd chirpy-server-ts
# Install dependencies
npm install
# Configure environment
cp .env.example .env
# Edit .env with your database credentials
# Run migrations
npm run migrate
# Start development server
npm run dev| Variable | Description | Example |
|---|---|---|
DB_URL |
PostgreSQL connection string | postgresql://user:pass@localhost:5432/chirpy |
SECRET |
JWT signing secret | your-256-bit-secret |
POLKA_KEY |
Webhook API key | polka-api-key |
PLATFORM |
Environment (dev/prod) |
dev |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/users |
Register new user | - |
POST |
/api/login |
Login, get tokens | - |
POST |
/api/refresh |
Refresh access token | Bearer (refresh) |
POST |
/api/revoke |
Revoke refresh token | Bearer (refresh) |
PUT |
/api/users |
Update user profile | Bearer |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/chirps |
Create a chirp | Bearer |
GET |
/api/chirps |
List all chirps | - |
GET |
/api/chirps?author_id=<uuid> |
Filter by author | - |
GET |
/api/chirps?sort=desc |
Sort by date | - |
GET |
/api/chirps/:id |
Get single chirp | - |
DELETE |
/api/chirps/:id |
Delete own chirp | Bearer |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
GET |
/api/healthz |
Health check | - |
POST |
/admin/reset |
Reset database (dev only) | - |
| Method | Endpoint | Description | Auth |
|---|---|---|---|
POST |
/api/polka/webhooks |
Polka payment webhook | ApiKey |
# Run all tests
npm test
# Run tests in watch mode
npm test -- --watchContains pure TypeScript interfaces representing business entities:
// User entity
interface User {
id: string;
email: string;
isChirpyRed: boolean;
createdAt: Date;
updatedAt: Date;
}
// Chirp entity
interface Chirp {
id: string;
body: string;
userId: string;
createdAt: Date;
updatedAt: Date;
}Business logic encapsulated in services:
- ChirpService: Create, read, delete chirps with validation
- UserService: Registration, authentication, profile management
- ContentFilterService: Profanity detection and filtering
External concerns isolated from business logic:
- Repositories: Database access patterns (CRUD operations)
- Auth: JWT creation/validation, password hashing
HTTP-specific code:
- Controllers: Handle requests, delegate to services
- Middleware: Auth guards, error handling, logging
- Routes: Express router definitions
- Password Hashing: Argon2id (memory-hard, resistant to GPU attacks)
- JWT Tokens: Short-lived access tokens (1 hour)
- Refresh Tokens: Long-lived (60 days), stored in database, revocable
- API Key Auth: Webhook endpoints protected with API keys
- Input Validation: Request body validation in controllers
- Error Handling: Centralized error middleware, no stack traces in production
-
Input Validation with Zod
- Add schema validation for all request bodies
- Generate OpenAPI documentation from schemas
- Improve error messages for invalid inputs
-
Dependency Injection Container
- Implement IoC container (e.g., tsyringe, inversify)
- Enable easier testing with mock dependencies
- Improve modularity and testability
-
API Versioning
- Add
/api/v1/prefix to all routes - Enable backward-compatible API evolution
- Add
-
Rate Limiting
- Implement per-user and per-IP rate limits
- Protect against brute force attacks
-
Request ID Tracing
- Add unique request IDs to all requests
- Include in logs for debugging
- Return in response headers
-
Structured Logging
- Replace console.log with structured logger (pino/winston)
- Add log levels, timestamps, context
- Enable log aggregation
-
Database Connection Pooling
- Configure proper connection pool settings
- Add health checks for database connectivity
-
Integration Tests
- Add supertest-based API tests
- Test full request/response cycles
- Add database fixtures
-
Caching Layer
- Add Redis for session/token caching
- Cache frequently accessed chirps
- Implement cache invalidation
-
Pagination
- Add cursor-based pagination for chirps
- Include pagination metadata in responses
-
Search Functionality
- Full-text search for chirps
- Search by hashtags, mentions
-
Real-time Features
- WebSocket support for live updates
- Server-Sent Events for notifications
-
Metrics & Monitoring
- Prometheus metrics endpoint
- Request duration histograms
- Error rate tracking
-
Docker Support
- Add Dockerfile and docker-compose.yml
- Multi-stage builds for production
- Health check endpoints
-
CI/CD Pipeline
- GitHub Actions for testing
- Automated deployments
- Code coverage reporting
ISC
Built as a portfolio project demonstrating clean architecture and TypeScript best practices.