Complete backend server for the Safe Ride Accident Detection System with real-time emergency alerts.
- β Express.js REST API
- β MongoDB for data storage
- β Socket.IO for real-time bidirectional communication
- β Firebase Cloud Messaging (FCM) for push notifications
- β Twilio SMS fallback
- β Redis support (optional)
- β Rate limiting
- β Authentication middleware
- β Error handling
- Node.js >= 18.0.0
- MongoDB (local or Atlas)
- Firebase project (for FCM)
- Twilio account (for SMS fallback)
- Redis (optional, for session management)
cd backend
npm installOption A: Local MongoDB
# Install MongoDB on your system
# Windows: https://www.mongodb.com/try/download/community
# Mac: brew install mongodb-community
# Linux: sudo apt-get install mongodb
# Start MongoDB
mongodOption B: MongoDB Atlas (Cloud)
- Go to https://www.mongodb.com/cloud/atlas
- Create a free cluster
- Get your connection string
- Update
.envfile
- Go to Firebase Console: https://console.firebase.google.com
- Select your project:
alpha-flutter-health - Go to Project Settings > Service Accounts
- Click "Generate new private key"
- Save the JSON file as
firebase-service-account.jsonin thebackend/folder
cp .env.example .envEdit .env and update:
NODE_ENV=development
PORT=5000
# MongoDB - Update this
MONGODB_URI=mongodb://localhost:27017/safe_ride
# JWT Secret - Change this!
JWT_SECRET=your_very_secret_key_change_this
# Firebase
FIREBASE_PROJECT_ID=alpha-flutter-health
FIREBASE_PRIVATE_KEY_PATH=./firebase-service-account.json
## π Running the Server
### Development Mode
```bash
npm run devnpm startServer will start on: http://localhost:5000
Register/Login
POST /api/users/register
Content-Type: application/json
{
"phoneNumber": "+916261795658",
"name": "John Doe",
"fcmToken": "firebase_token_here"
}Get Profile
GET /api/users/profile
x-user-id: user_id_hereAdd Emergency Contact
POST /api/users/emergency-contacts
x-user-id: user_id_here
Content-Type: application/json
{
"phoneNumber": "+919876543210",
"name": "Jane Doe",
"relationship": "Wife",
"isPrimary": true
}Update Settings
PUT /api/users/settings
x-user-id: user_id_here
Content-Type: application/json
{
"autoSendAlert": true,
"alertCountdown": 15,
"shareLocation": true,
"sendSMSFallback": true
}Create Alert
POST /api/alerts
x-user-id: user_id_here
Content-Type: application/json
{
"magnitude": 75,
"latitude": 23.2599,
"longitude": 77.4126,
"address": "Bhopal, MP",
"deviceInfo": "Samsung M556B",
"bluetoothDevice": "HC-05"
}Cancel Alert
POST /api/alerts/:alertId/cancel
x-user-id: user_id_hereGet Alert History
GET /api/alerts?page=1&limit=20
x-user-id: user_id_hereAuthenticate
socket.emit('authenticate', {
userId: 'user_id_here',
phoneNumber: '+916261795658'
});Create Emergency
socket.emit('emergency:create', {
magnitude: 80,
latitude: 23.2599,
longitude: 77.4126
});Update Location
socket.emit('location:update', {
latitude: 23.2599,
longitude: 77.4126,
alertId: 'alert_id_if_active'
});Cancel Emergency
socket.emit('emergency:cancel', {
alertId: 'alert_id_here'
});Authentication Success
socket.on('authenticated', (data) => {
console.log('Authenticated:', data);
});Emergency Alert Received
socket.on('emergency:alert', (data) => {
console.log('Emergency Alert:', data);
// data contains: alertId, severity, latitude, longitude, userPhoneNumber, userName
});Alert Countdown Started
socket.on('alert:countdown_started', (data) => {
console.log('Countdown started:', data.countdown);
});Alert Sent
socket.on('alert:sent', (data) => {
console.log('Alert sent to emergency contacts');
});Alert Cancelled
socket.on('emergency:cancelled', (data) => {
console.log('Alert was cancelled');
});Location Update
socket.on('emergency:location_update', (data) => {
console.log('Location updated:', data.latitude, data.longitude);
});phoneNumber: String (unique)name: StringfcmToken: StringemergencyContacts: Arraysettings: ObjectisOnline: BooleansocketId: String
userId: ObjectIdseverity: String (minor, moderate, severe, critical)magnitude: Numberlocation: Object {latitude, longitude, address}status: String (pending, cancelled, sent, acknowledged, resolved)notificationsSent: Arraymetadata: Object
- Import the API endpoints into Postman
- Register a user:
POST /api/users/register - Copy the returned
userId - Add emergency contacts
- Create an alert
- Check MongoDB to see the data
Use https://www.websocket.org/echo.html or Socket.IO client:
const socket = io('http://localhost:5000');
socket.on('connect', () => {
console.log('Connected');
socket.emit('authenticate', {
phoneNumber: '+916261795658'
});
});
socket.on('authenticated', (data) => {
console.log('Authenticated:', data);
});backend/
βββ src/
β βββ config/ # Configuration files
β βββ controllers/ # Route controllers
β βββ models/ # MongoDB models
β βββ routes/ # API routes
β βββ services/ # Business logic
β βββ middleware/ # Custom middleware
β βββ socket/ # Socket.IO handlers
β βββ server.js # Main server file
βββ package.json
βββ .env
βββ README.md
MongoDB Connection Error
- Make sure MongoDB is running:
mongod - Check connection string in
.env
Firebase Error
- Ensure
firebase-service-account.jsonis in the backend folder - Check file path in
.env
Socket.IO Not Connecting
- Check CORS settings
- Verify port is not in use
- Check firewall settings
MIT
Safe Ride Team