Secure, scalable healthcare management system bridging traditional Indian medicine with modern standards
A robust Node.js backend API for the MediBridge platform that provides comprehensive health record management, ICD-11 integration, and hospital authentication systems.
MediBridge Backend is a RESTful API server built with Express.js that powers the MediBridge healthcare platform. It integrates traditional Indian medicine (Ayush) with modern medical standards, providing secure patient record management with hospital-verified authentication.
- 🔐 Multi-tier Authentication - Google OAuth, JWT tokens, and hospital verification
- 🏥 Comprehensive Health Records - Complete CRUD operations with ICD-11 integration
- 🌐 Bilingual Support - English and Namaste (traditional Indian) medical terminology
- 📊 Advanced Analytics - Health trends, statistics, and dashboard data
- 🛡️ Enterprise Security - Role-based access, rate limiting, and audit logging
- ⚡ High Performance - Optimized database queries and caching strategies
- Google OAuth 2.0 - Secure social authentication
- JWT Tokens - Stateless authentication with configurable expiration
- Hospital Authentication - Special verification for healthcare providers
- Role-Based Access Control (RBAC) - Granular permissions system
- Rate Limiting - Protection against API abuse and DDoS
- Security Headers - Comprehensive security with Helmet.js
- Session Management - Secure session handling with cookies
- Audit Logging - Complete trail of all sensitive operations
- Complete CRUD Operations - Create, read, update, delete health records
- Multi-type Records - Support for consultations, lab results, prescriptions, imaging
- ICD-11 Integration - World Health Organization standard medical codes
- Namaste Names - Traditional Indian medicine terminology support
- Patient-Centric Design - Records organized by patient with privacy controls
- Document Verification - Hospital-verified authentic medical documents
- Search & Filtering - Advanced search capabilities with multiple criteria
- Batch Operations - Efficient handling of multiple records
- Real-time Metrics - Live health statistics and KPIs
- Trend Analysis - Historical health data visualization
- Export Capabilities - Data export in JSON and CSV formats
- Custom Reports - Flexible reporting system for healthcare insights
- Reminder System - Medication and appointment reminders
- Population Health - Anonymized aggregate health data
- Document Verification - Integrated verification workflows
- Confidence Scoring - AI-powered verification confidence levels
- Batch Verification - Process multiple documents simultaneously
- Verification History - Complete audit trail of verification activities
- Hospital Integration - Direct integration with hospital systems
🟢 Node.js 18+ - JavaScript runtime environment
🚀 Express.js 4.18.2 - Web application framework
🐘 PostgreSQL 12+ - Primary database system
🔐 JWT 9.0.2 - JSON Web Token authentication
🛡️ Helmet.js 7.1.0 - Security headers
⏱️ Rate Limiting 7.1.5 - API abuse protection
🍪 Cookie Parser 1.4.7 - Cookie handling
🔒 bcryptjs 2.4.3 - Password hashing
🌐 CORS 2.8.5 - Cross-origin resource sharing
🔍 Google Auth 9.2.0 - OAuth 2.0 integration
🏥 Hospital Auth - Custom healthcare provider auth
📊 Analytics Engine - Custom health analytics
🔄 Database Pool - Connection pooling for performance
backend/
├── src/
│ ├── auth/ # Authentication logic
│ │ ├── auth.js # Auth utilities and middleware
│ │ └── routes.js # Auth endpoints
│ ├── config/ # Configuration files
│ │ └── database.js # Database connection setup
│ ├── middleware/ # Custom middleware
│ │ ├── hospitalAuth.js # Hospital authentication
│ │ └── rbac.js # Role-based access control
│ ├── routes/ # API route handlers
│ │ ├── dashboard.js # Dashboard endpoints
│ │ ├── healthRecords.js # Health records CRUD
│ │ ├── hospital.js # Hospital management
│ │ └── verification.js # Document verification
│ └── index.js # Main application entry point
├── database-*.sql # Database schema and setup
├── test-*.js # Testing utilities
├── package.json # Dependencies and scripts
└── README.md # This documentation
- Node.js 18+ - Latest LTS version recommended
- PostgreSQL 12+ - Database server
- npm/yarn - Package manager
- Google Cloud Account - For OAuth configuration
# Clone the repository
git clone <repository-url>
cd medibridge/backend
# Install dependencies
npm install
# Verify installation
npm ls --depth=0# Create PostgreSQL database
createdb medibridge
# Run database schema
psql -d medibridge -f database-hospital-setup.sql
# Test database connection
node test-database.jsCreate a .env file in the backend root directory:
# ===========================================
# DATABASE CONFIGURATION
# ===========================================
DATABASE_URL=postgresql://username:password@localhost:5432/medibridge
DB_HOST=localhost
DB_PORT=5432
DB_NAME=medibridge
DB_USER=your_username
DB_PASSWORD=your_password
# ===========================================
# AUTHENTICATION SECRETS
# ===========================================
JWT_SECRET=your-super-secure-jwt-secret-key-min-32-chars
JWT_EXPIRES_IN=7d
SESSION_SECRET=your-session-secret-key
# ===========================================
# GOOGLE OAUTH CONFIGURATION
# ===========================================
GOOGLE_CLIENT_ID=your-google-oauth-client-id
GOOGLE_CLIENT_SECRET=your-google-oauth-client-secret
# ===========================================
# SERVER CONFIGURATION
# ===========================================
PORT=3000
NODE_ENV=development
FRONTEND_URL=http://localhost:5173
API_VERSION=v1
# ===========================================
# SECURITY SETTINGS
# ===========================================
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
BCRYPT_SALT_ROUNDS=12
# ===========================================
# CORS SETTINGS
# ===========================================
CORS_ORIGIN=http://localhost:5173
CORS_CREDENTIALS=true# Development mode (with auto-restart)
npm run dev
# Production mode
npm start
# Test the server
curl http://localhost:3000/api/health# Test database connection
node test-database.js
# Test environment variables
node test-env.js
# Check API endpoints
curl http://localhost:3000/api/dashboard/overviewDevelopment: http://localhost:3000/api
Production: https://api.medibridge.com/api
Authenticate user with Google OAuth token
Request:
{
"token": "google-oauth-id-token",
"userType": "patient" // or "hospital"
}Response:
{
"success": true,
"data": {
"user": {
"id": 123,
"email": "user@example.com",
"name": "John Doe",
"role": "patient"
},
"token": "jwt-token-here",
"expiresIn": "7d"
}
}Get current authenticated user profile
Headers: Authorization: Bearer <jwt-token>
Response:
{
"success": true,
"data": {
"id": 123,
"email": "user@example.com",
"name": "John Doe",
"role": "patient",
"verified": true,
"createdAt": "2024-01-15T10:30:00Z"
}
}Logout user and invalidate session
Response:
{
"success": true,
"message": "Logged out successfully"
}Retrieve user's health records with pagination and filtering
Query Parameters:
page(number): Page number (default: 1)limit(number): Records per page (default: 10, max: 100)type(string): Record type filterstatus(string): Verification status filtersearch(string): Search term for title/descriptionstartDate(date): Filter records from dateendDate(date): Filter records to date
Response:
{
"success": true,
"data": [
{
"id": 1,
"title": "John Doe",
"recordType": "consultation",
"description": "Annual health checkup",
"icd11Code": "QA02",
"icd11Title": "General medical examination",
"diagnosis": "Healthy individual",
"symptoms": ["routine checkup"],
"namasteName": "वार्षिक स्वास्थ्य जांच",
"doctorName": "Dr. Smith",
"hospitalName": "City Hospital",
"visitDate": "2024-01-15",
"severity": "mild",
"verificationStatus": "verified",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-15T10:30:00Z"
}
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"totalRecords": 47,
"hasNextPage": true,
"hasPreviousPage": false
}
}Create a new health record
Request:
{
"recordType": "consultation",
"title": "John Doe",
"description": "Annual physical examination",
"icd11Code": "QA02",
"icd11Title": "General medical examination",
"diagnosis": "Patient is in good health",
"symptoms": ["routine checkup", "no complaints"],
"namasteName": "वार्षिक स्वास्थ्य जांच",
"doctorName": "Dr. Sarah Johnson",
"hospitalName": "MediBridge General Hospital",
"visitDate": "2024-01-15",
"severity": "mild"
}Response:
{
"success": true,
"data": {
"id": 1,
"title": "John Doe",
"recordType": "consultation",
// ... full record data
"verificationStatus": "pending",
"createdAt": "2024-01-15T10:30:00Z"
},
"message": "Health record created successfully"
}Get specific health record by ID
Update existing health record
Delete health record (soft delete with audit trail)
Get health records statistics and overview
Response:
{
"success": true,
"data": {
"totalRecords": 47,
"recordsByType": {
"consultation": 15,
"labResult": 12,
"prescription": 10,
"imaging": 8,
"vaccination": 2
},
"verificationStatus": {
"verified": 35,
"pending": 10,
"rejected": 2
},
"recentRecords": 5,
"healthScore": 85.5
}
}Comprehensive dashboard data for authenticated user
Response:
{
"success": true,
"data": {
"statistics": {
"totalRecords": 47,
"verifiedRecords": 35,
"pendingVerification": 10,
"healthScore": 85.5
},
"recentRecords": [...],
"medicalHistory": [...],
"upcomingReminders": [...],
"chartData": {
"healthTrends": [...],
"recordsOverTime": [...]
}
}
}Advanced analytics with time-series data
Query Parameters:
period(string): 7d, 30d, 90d, 1ymetric(string): health_score, record_count, verification_rate
Export user's health data
Query Parameters:
format(string): json, csvincludeAttachments(boolean): Include file attachments
Verify a specific health record
Request:
{
"verificationType": "full",
"verifierNotes": "Document verified against hospital records"
}Batch verify multiple health records
Request:
{
"recordIds": [1, 2, 3, 4, 5],
"verificationType": "full"
}Get verification history for a specific record
Get verification system statistics
Hospital-specific dashboard (requires hospital role)
Hospital verification of patient records
{
"sub": "user-id",
"email": "user@example.com",
"role": "patient",
"hospitalId": null,
"iat": 1640995200,
"exp": 1641600000
}| Role | Permissions |
|---|---|
| Patient | Read/write own records, view own dashboard |
| Doctor | Read/write all records, access analytics |
| Hospital | Verify records, manage hospital patients |
| Admin | Full system access, user management |
- Helmet.js - Security headers
- CORS - Cross-origin request validation
- Rate Limiting - Request throttling
- JWT Validation - Token verification
- Role Authorization - Permission checking
- Input Validation - Request sanitization
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
google_id VARCHAR(255) UNIQUE,
role VARCHAR(50) DEFAULT 'patient',
hospital_id INTEGER REFERENCES hospitals(id),
verified BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);CREATE TABLE health_records (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
title VARCHAR(255) NOT NULL,
record_type VARCHAR(100) NOT NULL,
description TEXT,
icd11_code VARCHAR(20),
icd11_title VARCHAR(255),
diagnosis TEXT,
symptoms JSONB,
namaste_name VARCHAR(255),
doctor_name VARCHAR(255),
hospital_name VARCHAR(255),
visit_date DATE,
severity VARCHAR(50),
verification_status VARCHAR(50) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);CREATE TABLE hospitals (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
license_number VARCHAR(100) UNIQUE,
address TEXT,
phone VARCHAR(20),
email VARCHAR(255),
verified BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);-- Performance indexes
CREATE INDEX idx_health_records_user_id ON health_records(user_id);
CREATE INDEX idx_health_records_type ON health_records(record_type);
CREATE INDEX idx_health_records_date ON health_records(visit_date);
CREATE INDEX idx_health_records_verification ON health_records(verification_status);
-- Search indexes
CREATE INDEX idx_health_records_search ON health_records USING gin(to_tsvector('english', title || ' ' || description));// Example validation middleware
const validateHealthRecord = [
body("title").trim().isLength({ min: 1, max: 255 }),
body("recordType").isIn([
"consultation",
"lab_result",
"prescription",
"imaging",
]),
body("icd11Code")
.optional()
.matches(/^[A-Z0-9.]+$/),
body("severity").isIn(["mild", "moderate", "severe"]),
// ... additional validations
];const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: "Too many requests from this IP",
standardHeaders: true,
legacyHeaders: false,
});app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
})
);import pg from "pg";
const { Pool } = pg;
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 20, // maximum number of clients
idleTimeoutMillis: 30000, // close idle clients after 30 seconds
connectionTimeoutMillis: 2000, // return an error after 2 seconds
});- In-Memory Caching for frequently accessed data
- Redis Integration ready for session storage
- Database Query Caching for static reference data
- API Response Caching for dashboard analytics
// Efficient pagination with limit/offset
const getHealthRecords = async (userId, page = 1, limit = 10, filters = {}) => {
const offset = (page - 1) * limit;
const query = `
SELECT * FROM health_records
WHERE user_id = $1
${filters.type ? "AND record_type = $2" : ""}
ORDER BY created_at DESC
LIMIT $${filters.type ? 3 : 2} OFFSET $${filters.type ? 4 : 3}
`;
// ... query execution
};# Create test database
createdb medibridge_test
# Set test environment
export NODE_ENV=test
export DATABASE_URL=postgresql://user:pass@localhost:5432/medibridge_test
# Run tests (when implemented)
npm testtest-database.js- Database connection testingtest-env.js- Environment variables validationtest-neon.js- Cloud database testing
- Unit Tests - Individual function testing
- Integration Tests - API endpoint testing
- Security Tests - Authentication and authorization
- Performance Tests - Load testing for scalability
NODE_ENV=production
DATABASE_URL=postgresql://user:pass@prod-host:5432/medibridge
JWT_SECRET=production-super-secure-secret
FRONTEND_URL=https://medibridge.com
CORS_ORIGIN=https://medibridge.comFROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY src/ ./src/
EXPOSE 3000
CMD ["npm", "start"]- Set
NODE_ENV=production - Configure secure database connection with SSL
- Set up SSL/TLS certificates
- Configure rate limiting for production load
- Set up monitoring and logging (Winston, Morgan)
- Configure backup strategies
- Set up health check endpoints
- Configure proper CORS origins
- Set secure JWT secrets (min 32 characters)
- Enable database connection pooling
- Set up error tracking (Sentry)
app.get("/api/health", (req, res) => {
res.json({
status: "OK",
timestamp: new Date().toISOString(),
uptime: process.uptime(),
environment: process.env.NODE_ENV,
version: process.env.npm_package_version,
});
});import morgan from "morgan";
// Custom logging format
morgan.token("user", (req) => req.user?.id || "anonymous");
app.use(
morgan(":method :url :status :res[content-length] - :response-time ms :user")
);// Global error handler
app.use((err, req, res, next) => {
console.error("Error:", err);
if (process.env.NODE_ENV === "production") {
res.status(500).json({
success: false,
message: "Internal server error",
});
} else {
res.status(500).json({
success: false,
message: err.message,
stack: err.stack,
});
}
});const logAuditEvent = async (
userId,
action,
resourceType,
resourceId,
details
) => {
await pool.query(
`
INSERT INTO audit_logs (user_id, action, resource_type, resource_id, details, created_at)
VALUES ($1, $2, $3, $4, $5, NOW())
`,
[userId, action, resourceType, resourceId, JSON.stringify(details)]
);
};- Fork the repository
- Clone your fork:
git clone <your-fork-url> - Install dependencies:
npm install - Create feature branch:
git checkout -b feature/amazing-feature - Set up development database and environment variables
- Make your changes and test thoroughly
- Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
- ES6+ JavaScript with ES modules
- Express.js best practices
- Async/await for asynchronous operations
- Error handling with try-catch blocks
- Input validation for all endpoints
- Security first approach
- Performance optimization considerations
type(scope): description
Types: feat, fix, docs, style, refactor, test, chore
Scope: auth, records, dashboard, db, security
Examples:
feat(auth): add hospital authentication system
fix(records): resolve pagination issue in health records
docs(api): update authentication endpoint documentation
{
"success": true,
"data": {
// Response data here
},
"message": "Operation completed successfully",
"timestamp": "2024-01-15T10:30:00Z"
}{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": {
"field": "email",
"issue": "Invalid email format"
}
},
"timestamp": "2024-01-15T10:30:00Z"
}{
"success": true,
"data": [...],
"pagination": {
"currentPage": 1,
"totalPages": 10,
"totalRecords": 95,
"recordsPerPage": 10,
"hasNextPage": true,
"hasPreviousPage": false
}
}- API Postman Collection - [Import Link]
- Database Schema - [ERD Diagram]
- Security Guidelines - [Security Doc]
- Deployment Guide - [Deploy Doc]
This project is licensed under the ISC License - see the LICENSE file for details.
- 📧 Email Support - backend-support@medibridge.com
- 💬 GitHub Issues - For bugs and feature requests
- 📖 Documentation - Check this README and inline code comments
- 🎥 Video Tutorials - [YouTube Channel]
When reporting issues, please include:
- Node.js version
- Operating system
- Steps to reproduce
- Expected vs actual behavior
- Error logs and stack traces
- Environment details (development/production)
- Clone and install dependencies:
cd backend
npm install- Environment Configuration:
Create a
.envfile with:
# Database
DATABASE_URL=postgresql://username:password@host:port/database
# Authentication
JWT_SECRET=your-super-secret-jwt-key
JWT_EXPIRES_IN=7d
SESSION_SECRET=your-session-secret
# Google OAuth
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
# Server
PORT=3000
NODE_ENV=development
FRONTEND_URL=http://localhost:3000- Start the server:
# Development
npm run dev
# Production
npm startGoogle OAuth authentication
{
"token": "google-id-token"
}Get current user profile (requires authentication)
Verify JWT token validity
Logout and clear session
Get user's health records with pagination and filtering
- Query params:
page,limit,type,status
Create new health record
{
"recordType": "consultation",
"title": "Annual Checkup",
"description": "Routine annual physical examination",
"icd11Code": "QA02",
"diagnosis": "Normal examination findings",
"doctorName": "Dr. Smith",
"hospitalName": "City Hospital",
"visitDate": "2024-01-15",
"severity": "mild"
}Get specific health record
Update health record
Delete health record
Get health records statistics
Comprehensive dashboard data including:
- Statistics overview
- Recent records
- Medical history summary
- Verification status
- Charts data
Advanced analytics with time-series data
- Query params:
period(7d, 30d, 90d, 1y),metric
Health trends and scoring
Upcoming medication and follow-up reminders
Export health data
- Query params:
format(json, csv),includeAttachments(true, false)
Search ICD-11 codes
- Query params:
query,limit
Get specific ICD-11 code details
Verify single health record with Namaste TM2
{
"verificationType": "full"
}Batch verify multiple records
{
"recordIds": [1, 2, 3],
"verificationType": "full"
}Get verification history for a record
Get verification statistics
- Patient: Can manage own records
- Doctor: Can view/edit all records
- Verifier: Can verify records and view analytics
- Admin: Full system access
read_own_records: Read user's own recordswrite_own_records: Create/edit user's own recordsread_all_records: Read all records in systemwrite_all_records: Create/edit any recordsverify_records: Perform record verificationmanage_users: User management operationsview_analytics: Access analytics dashboardsexport_data: Export user data
- users: User profiles and authentication
- health_records: Main health record storage
- medical_history: Chronic conditions and history
- medications: Current and past medications
- verification_logs: Verification audit trail
- analytics: Metrics and dashboard data
- audit_logs: System audit trail
- Automated indexing for performance
- JSON fields for flexible data storage
- Audit trails for compliance
- Referential integrity with foreign keys
- JWT tokens with configurable expiration
- HTTP-only cookies option
- Session management with secure settings
- CORS protection with whitelist
- Rate limiting (100 requests/15min, 5 auth/15min)
- Helmet.js security headers
- Input validation and sanitization
- Role-based authorization on all endpoints
- Encrypted sensitive fields
- Audit logging for all operations
- Data anonymization options
- GDPR compliance ready
- Connection pooling with configurable limits
- Query optimization with indexes
- Pagination for large datasets
- Caching strategies ready
- Request logging with timing
- Error tracking and reporting
- Health check endpoints
- Audit trail for compliance
npm run dev # Start development server
npm run start # Start production server
npm run test # Run test suite (to be implemented)- Hot reload with nodemon
- Environment-based configuration
- Detailed error messages in development
- SQL query logging for debugging
- Set
NODE_ENV=production - Configure secure database connection
- Set up SSL/TLS certificates
- Configure rate limiting
- Set up monitoring and logging
- Configure backup strategies
Ensure all required environment variables are set:
- Database connection string
- JWT secrets
- Google OAuth credentials
- CORS origins
- Rate limiting settings
The system is designed to integrate with the official ICD-11 API:
- Search functionality for medical codes
- Code validation and details
- Hierarchical navigation
- Multi-language support ready
Verification system integration points:
- Document verification API
- Confidence scoring
- Batch processing
- Result tracking
All API responses follow a consistent format:
Success Response:
{
"success": true,
"data": {
/* response data */
},
"message": "Operation completed successfully"
}Error Response:
{
"success": false,
"message": "Error description",
"error": "Detailed error (development only)"
}Paginated Response:
{
"success": true,
"data": [
/* array of items */
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"totalRecords": 100,
"hasNextPage": true,
"hasPreviousPage": false
}
}- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
This project is licensed under the ISC License.
For support, email support@medibridge.com or create an issue in the repository.
MediBridge Backend - Revolutionizing health record management with cutting-edge technology and security. 🏥✨