A comprehensive API monitoring and analytics backend built for the Treblle Hackathon. This backend provides real-time API monitoring, security analysis, analytics aggregation, and user management capabilities.
- API Proxy & Monitoring - Real-time request/response logging and analysis
- Security Analysis - Automatic security issue detection and scoring
- Analytics Aggregation - Pre-computed metrics for performance optimization
- User Management - OAuth and traditional authentication support
- Project Management - Multi-project support with endpoint discovery
- Request Logging - Comprehensive request/response data storage
- Geographic Data - IP-based location tracking
- Real-time Processing - Background request processing
- Filtering & Sorting - Advanced query capabilities for endpoints and requests
- Pagination - Efficient data retrieval with pagination support
- Data Export - Complete user data export functionality
- Runtime: Node.js with TypeScript
- Framework: Express.js
- Database: SQLite with Prisma ORM
- Authentication: JWT tokens with bcrypt password hashing
- Security: Automatic security analysis and scoring
- Geolocation: IP-based location services
-
Clone the repository
git clone <repository-url> cd treblle-hackathon-backend
-
Install dependencies
npm install
-
Environment Setup Create a
.envfile in the root directory:JWT_SECRET=your-jwt-secret-key INTERNAL_API_KEY=your-internal-api-key DATABASE_URL="file:./prisma/dev.db" PROXY_BASE_URL="http://localhost:8080"
-
Database Setup
# Generate Prisma client npx prisma generate # Run database migrations npx prisma migrate dev # (Optional) Open Prisma Studio npx prisma studio
-
Start Development Server
npm run dev
The server will start on http://localhost:8080
POST /api/auth/register
Content-Type: application/json
{
"email": "[email protected]",
"password": "password123",
"name": "John Doe"
}POST /api/auth/login
Content-Type: application/json
{
"email": "[email protected]",
"password": "password123"
}POST /api/auth/oauth-user
X-Internal-API-Key: your-internal-api-key
Content-Type: application/json
{
"email": "[email protected]",
"name": "John Doe",
"provider": "google",
"providerId": "google-user-id"
}POST /api/projects
Authorization: Bearer <jwt-token>
Content-Type: application/json
{
"name": "My API Project",
"originalBaseUrl": "https://api.example.com"
}GET /api/projects
Authorization: Bearer <jwt-token>GET /api/projects/{projectId}/endpoints?method=GET&status=healthy&timeRange=24h&sortBy=path&order=asc
Authorization: Bearer <jwt-token>Query Parameters:
method- Filter by HTTP method (GET, POST, PUT, DELETE, etc.)status- Filter by endpoint status (healthy, error, all)timeRange- Filter by time range (1h, 24h, 7d, 30d)sortBy- Sort by field (path, method, requestCount, errorRate, avgResponseTime, lastRequest)order- Sort order (asc, desc)
GET /api/projects/{projectId}/requests?method=POST&statusCode=4xx&timeRange=7d&sortBy=createdAt&order=desc&page=1&limit=20
Authorization: Bearer <jwt-token>Query Parameters:
method- Filter by HTTP methodstatusCode- Filter by status code ranges (2xx, 4xx, 5xx, all)timeRange- Filter by time range (1h, 24h, 7d, 30d)sortBy- Sort by field (createdAt, method, path, responseCode, durationMs)order- Sort order (asc, desc)page- Pagination page numberlimit- Items per page
PUT /api/user/profile
Authorization: Bearer <jwt-token>
Content-Type: application/json
{
"name": "New User Name"
}PUT /api/user/password
Authorization: Bearer <jwt-token>
Content-Type: application/json
{
"currentPassword": "current_password",
"newPassword": "new_password"
}GET /api/user/export
Authorization: Bearer <jwt-token>DELETE /api/user/account
Authorization: Bearer <jwt-token>GET /api/analytics/{projectId}
Authorization: Bearer <jwt-token>POST /api/proxy/{projectId}/*
Authorization: Bearer <jwt-token>The proxy automatically:
- Logs all request/response data
- Performs security analysis
- Updates analytics aggregations
- Tracks geographic data
id- Unique identifieremail- User email (unique)password- Hashed password (for credentials auth)name- User display nameprovider- Auth provider (credentials, google, etc.)providerId- Provider-specific user IDcreatedAt- Account creation timestampupdatedAt- Last update timestamp
id- Unique identifiername- Project nameoriginalBaseUrl- Original API base URLproxyUrl- Generated proxy URLuserId- Owner user IDcreatedAt- Project creation timestamp
id- Unique identifierprojectId- Associated project IDmethod- HTTP methodpath- Request pathrequestHeaders- Request headers (JSON)requestBody- Request body (JSON)queryParams- Query parameters (JSON)responseHeaders- Response headers (JSON)responseBody- Response body (JSON)responseCode- HTTP status codedurationMs- Request duration in millisecondsipAddress- Client IP addressuserAgent- Client user agentcity- Client citycountry- Client countrysecurityScore- Security score (0-100)securityIssues- Security issues array (JSON)requestSize- Request size in bytesresponseSize- Response size in bytescreatedAt- Request timestamp
id- Unique identifierprojectId- Associated project IDdate- Aggregation datehour- Hour of day (null for daily aggregations)requestCount- Total requestsavgResponseTime- Average response timeerrorRate- Error rate percentagetotalRequests- Total request counttotalErrors- Total error count
src/
βββ api/ # API routes
β βββ routes/ # Route definitions
β βββ index.ts # Main API router
βββ config/ # Configuration files
βββ controllers/ # Request handlers
βββ middleware/ # Express middleware
βββ services/ # Business logic services
βββ types/ # TypeScript type definitions
- Handles request proxying
- Performs security analysis
- Updates analytics aggregations
- Background processing for performance
- Pre-computes metrics for performance
- Handles hourly and daily aggregations
- Optimizes query performance
- Analyzes requests for security issues
- Generates security scores
- Detects potential vulnerabilities
# Generate Prisma client
npx prisma generate
# Create migration
npx prisma migrate dev --name migration-name
# Reset database
npx prisma migrate reset
# Open Prisma Studio
npx prisma studio- JWT Authentication - Secure token-based authentication
- Password Hashing - bcrypt with salt rounds
- Input Validation - Comprehensive request validation
- SQL Injection Protection - Prisma ORM protection
- CORS Configuration - Cross-origin request handling
- Security Analysis - Automatic security issue detection
- Analytics Aggregation - Pre-computed metrics reduce query time
- Background Processing - Non-blocking request processing
- Database Indexing - Optimized queries with proper indexing
- Pagination - Efficient data retrieval
- Connection Pooling - Database connection optimization
JWT_SECRET=your-jwt-secret-key
INTERNAL_API_KEY=your-internal-api-key
DATABASE_URL="file:./prisma/dev.db"
NODE_ENV=production
PORT=8080- Use PostgreSQL or MySQL for production database
- Implement proper logging and monitoring
- Set up reverse proxy (nginx)
- Configure SSL/TLS certificates
- Implement rate limiting
- Set up backup strategies
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the ISC License.
This backend was built for the Treblle Hackathon, focusing on:
- Real-time API monitoring
- Security analysis and scoring
- Comprehensive analytics and reporting
- User-friendly project management
- Scalable architecture for future growth
Built with β€οΈ for the Treblle Hackathon