A comprehensive Node.js/TypeScript backend for real-time crowd management and safety monitoring during large-scale events.
- Real-time Communication: Socket.IO for live updates and bidirectional communication
- MongoDB Integration: Geospatial data storage with TTL indexes for location pings
- AI/ML Integration: REST API integration with Python ML microservice
- Authentication: JWT-based authentication with role-based access control
- Alert System: Real-time alert generation and management
- Action Coordination: Emergency response action logging and notification
- Report Management: Incident reporting with auto-triage capabilities
- SMS/WhatsApp: Twilio integration for emergency notifications
- Comprehensive API: RESTful API with OpenAPI documentation
- Express.js Server: RESTful API with middleware for security, validation, and error handling
- Socket.IO: Real-time WebSocket communication for live updates
- MongoDB: Primary database with geospatial indexing and TTL collections
- Mongoose ODM: Schema-based modeling with validation and middleware
- JWT Authentication: Secure token-based authentication with refresh tokens
- Twilio Integration: SMS and WhatsApp emergency notifications
- Users: Admin and staff accounts with role-based permissions
- Events: Event definitions with geospatial boundaries
- Zones: Sub-areas within events with polygon definitions
- LocationPings: Real-time location data with TTL expiration (15 minutes)
- Alerts: System-generated and manual alerts with severity levels
- Actions: Emergency response actions with multi-channel delivery
- Reports: Incident reports with auto-triage and attachment support
- AI Insights/Predictions: Cached ML service results
-
Clone and navigate to backend directory:
cd backend -
Install dependencies:
npm install
-
Set up environment variables:
cp .env.example .env # Edit .env with your configuration -
Start MongoDB (if running locally):
mongod
-
Seed the database:
npm run seed
-
Start the development server:
npm run dev
The server will start on http://localhost:8080
MONGO_URI: MongoDB connection stringJWT_SECRET: Secret key for JWT tokens (minimum 32 characters)FRONTEND_ORIGIN: Frontend URL for CORS
PORT: Server port (default: 8080)ML_BASE: ML service base URL (default: http://localhost:5001)TWILIO_ACCOUNT_SID: Twilio account SID for SMS/WhatsAppTWILIO_AUTH_TOKEN: Twilio auth tokenTWILIO_FROM: Twilio phone numberREDIS_URL: Redis connection for caching (optional)
POST /api/auth/login- User loginPOST /api/auth/refresh- Refresh access tokenGET /api/auth/me- Get current user profilePATCH /api/auth/me- Update user profilePOST /api/auth/change-password- Change password
GET /api/map-data- Get live map data with densityPOST /api/map-data/ping- Add location pingGET /api/map-data/history/:eventId- Get location historyGET /api/map-data/density/:eventId/:zoneId- Get zone density
GET /api/alerts- Get alerts with filteringPOST /api/alerts- Create new alertPATCH /api/alerts/:id/resolve- Resolve alertGET /api/alerts/stats/:eventId- Get alert statistics
GET /api/ai-insights- Get latest AI insightsGET /api/ai-predictions- Get AI predictionsPOST /api/ai-insights/refresh- Refresh insights from ML servicePOST /api/ai-predictions/refresh- Refresh predictions
GET /api/actions- Get emergency actionsPOST /api/actions- Create new actionGET /api/actions/templates- Get emergency action templatesGET /api/actions/stats/:eventId- Get action statistics
GET /api/reports- Get incident reportsPOST /api/reports- Submit new report (supports anonymous)PATCH /api/reports/:id/status- Update report statusGET /api/reports/priority/:eventId- Get priority reports
GET /api/system-health- Get system health status
map:update- Live map data updatesalert:new- New alert notificationsalert:updated- Alert status changesaction:created- New emergency actionsreport:new- New incident reportsinsight:update- AI insight updatesprediction:update- AI prediction updates
subscribe:zones- Subscribe to specific zonesunsubscribe:zones- Unsubscribe from zones
location_pings.loc- 2dsphere index for location querieszones.polygon- 2dsphere index for zone queriesevents.bounds- 2dsphere index for event boundaries
location_pings.createdAt- Expires after 900 seconds (15 minutes)
alerts.eventId + status- Alert filteringreports.eventId + status- Report filteringactions.eventId + createdAt- Action historyusers.email- Unique constraint and login
- Access Token: 24-hour expiration, contains user ID, email, role
- Refresh Token: 7-day expiration, stored as httpOnly cookie
- Role-Based Access: admin, staff roles with hierarchical permissions
- Most endpoints require valid JWT token in Authorization header
- Admin-only endpoints restricted to admin role
- Some report endpoints allow anonymous access
- Authentication: JWT token validation on connection
- Room Management: Automatic event and zone room joining
- Broadcasting: Targeted updates to specific events/zones
- Error Handling: Connection retry and error recovery
- Location Updates: Real-time crowd density visualization
- Alert Notifications: Instant emergency alert broadcasting
- Action Coordination: Live emergency response updates
- Report Notifications: Real-time incident report alerts
- Insights Endpoint: POST to
/insightswith crowd data - Predictions Endpoint: POST to
/predictionswith features - Health Checks: Automatic ML service health monitoring
- Fallback Handling: Cached results when ML service unavailable
- Backend aggregates location and zone data
- Calls ML service with processed features
- Caches ML results in MongoDB
- Broadcasts updates via WebSocket
- Serves cached data for subsequent requests
- SMS Notifications: Emergency action and alert notifications
- WhatsApp Support: Rich media emergency notifications
- Bulk Messaging: Mass notification capabilities
- Delivery Tracking: Message status and error handling
- Critical Alerts: Automatic SMS/WhatsApp for critical severity
- Emergency Actions: Multi-channel delivery for emergency responses
- System Failures: Admin notifications for service degradation
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm run start- Start production servernpm run test- Run test suitenpm run lint- Run ESLintnpm run seed- Seed database with test data
- Unit Tests: Service layer testing with Jest
- Integration Tests: API endpoint testing with Supertest
- Socket Tests: WebSocket connection and event testing
- E2E Tests: Full workflow testing
src/
├── app.ts # Express app configuration
├── server.ts # Server startup and Socket.IO
├── config/ # Database, logging, environment
├── middleware/ # Authentication, error handling
├── models/ # Mongoose schemas and models
├── services/ # Business logic layer
├── controllers/ # Request/response handling
├── routes/ # API route definitions
└── utils/ # Helper functions and utilities
# Build image
npm run docker:build
# Run container
npm run docker:run- Environment Variables: Secure JWT secrets and API keys
- Database: MongoDB Atlas or dedicated MongoDB instance
- SSL/TLS: HTTPS termination with reverse proxy
- Rate Limiting: API rate limiting and abuse prevention
- Monitoring: Health checks, logging, and alerting
- Scaling: Horizontal scaling with load balancer
- JWT Tokens: Secure token-based authentication
- Role-Based Access: Hierarchical permission system
- Password Hashing: bcrypt with salt rounds
- Session Management: Secure cookie handling
- Helmet: Security headers and protection
- CORS: Cross-origin request configuration
- Rate Limiting: Request rate limiting per IP
- Input Validation: Zod schema validation
- SQL Injection: MongoDB query sanitization
- PII Protection: Minimal personal data storage
- Audit Logging: Admin action logging
- Data Retention: TTL for ephemeral location data
- GDPR Compliance: Data deletion capabilities
-
MongoDB Connection:
- Verify MONGO_URI is correct
- Check MongoDB service is running
- Ensure network connectivity
-
JWT Errors:
- Verify JWT_SECRET is set and secure
- Check token expiration
- Validate token format
-
Socket.IO Issues:
- Check CORS configuration
- Verify frontend connection URL
- Monitor connection logs
-
ML Service Integration:
- Verify ML_BASE URL is accessible
- Check ML service health endpoint
- Monitor timeout configurations
- Application Logs:
logs/combined.log - Error Logs:
logs/error.log - Console Output: Real-time development logs
- Health Endpoint:
/api/system-health - Service Status: Database, ML service, Socket.IO
- Performance Metrics: Response times, error rates
MIT License - see LICENSE file for details.
For technical support or questions about the CrowdShield AI backend:
- Create an issue in the project repository
- Contact the development team
- Review the API documentation and logs