A robust Node.js + Express.js REST API for healthcare clinic management system with MongoDB database, JWT authentication, appointment scheduling, prescription management, and AI-powered assistant.
Live API: https://hackathon-server-4c7a.onrender.com
Backend server for AI Clinic Pro that handles all business logic, database operations, user authentication, appointment management, prescription generation, and AI interactions. Designed to work with React frontend (separate repository).
Backend Features:
- Multi-role user authentication (Admin, Doctor, Patient, Receptionist)
- JWT-based secure authentication
- OTP-based password reset (with demo & production modes)
- Appointment scheduling and management
- Digital prescription creation and PDF generation
- Patient records management
- AI-powered medical assistant responses
- Analytics data aggregation
- Role-based access control
- MongoDB database integration
- Email notifications (Nodemailer)
- Automatic OTP expiration
- User blocking/management
Express.js Server (Port: 5000)
β
Middleware (Auth, CORS, Error Handling)
β
Routes (7 modules)
β
Controllers (Business Logic)
β
Models (MongoDB Schemas)
β
Utilities (Email, PDF, AI)
β
Database (MongoDB)
backend/
βββ src/
β βββ config/
β β βββ db.js # MongoDB connection
β β
β βββ models/
β β βββ User.js # User schema (all roles)
β β βββ Patient.js # Patient records
β β βββ Appointment.js # Appointment scheduling
β β βββ Prescription.js # Prescription data
β β βββ DiagnosisLog.js # AI diagnosis history
β β
β βββ controllers/
β β βββ authController.js # Authentication logic
β β βββ patientController.js # Patient management
β β βββ appointmentController.js # Appointment operations
β β βββ prescriptionController.js# Prescription handling
β β βββ adminController.js # Admin operations
β β βββ aiController.js # AI assistant logic
β β βββ analyticsController.js # Analytics data
β β
β βββ routes/
β β βββ authRoutes.js # /api/auth/*
β β βββ patientRoutes.js # /api/patients/*
β β βββ appointmentRoutes.js # /api/appointments/*
β β βββ prescriptionRoutes.js # /api/prescriptions/*
β β βββ adminRoutes.js # /api/admin/*
β β βββ aiRoutes.js # /api/ai/*
β β βββ analyticsRoutes.js # /api/analytics/*
β β
β βββ middlewares/
β β βββ authMiddleware.js # JWT verification & role checking
β β
β βββ utils/
β β βββ emailHelper.js # OTP email sending (Demo & Production)
β β βββ aiHelper.js # AI response generation
β β βββ generatePDF.js # PDF prescription generation
β β
β βββ server.js # Express app setup
β
βββ uploads/
β βββ prescriptions/ # Generated PDF storage
β
βββ .env # Environment variables
βββ package.json # Dependencies
βββ README.md # This file
| Technology | Version | Purpose |
|---|---|---|
| Node.js | 16+ | JavaScript runtime |
| Express.js | 4.x | Web framework |
| MongoDB | Cloud/Local | NoSQL database |
| Mongoose | 7.x | MongoDB ODM |
| JWT | jsonwebtoken | Authentication |
| bcryptjs | 2.x | Password hashing |
| Nodemailer | 6.x | Email sending |
| jsPDF | 2.x | PDF generation |
| CORS | Latest | Cross-origin requests |
| dotenv | Latest | Environment variables |
- Node.js 16+ installed
- MongoDB (Cloud Atlas or Local)
- Gmail account (optional - for email OTP)
- Git
# Clone the repository
git clone [your-backend-repo-url]
cd backend
# Install dependencies
npm install
# Create .env file
cp .env.example .env
# Edit .env with your configuration (see below)
# Start development server
npm startServer will run on: http://localhost:5000
npm start # Start server
npm run dev # Start with nodemon (hot reload)
npm run lint # Check code quality
npm test # Run tests (if configured)Create a .env file in the backend root folder:
# Server
PORT=5000
NODE_ENV=development
# Database
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/clinic
# JWT Authentication
JWT_SECRET=your-super-secret-key-minimum-32-characters-long
JWT_EXPIRE=30d
# Email Configuration (Optional - Demo Mode Works Without)
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-16-char-app-password
# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:5173
# AI Configuration (Optional)
AI_API_KEY=your-api-key-if-using-external-ai- Go to https://www.mongodb.com/cloud/atlas
- Create free account
- Create a cluster
- Get connection string
- Replace with your credentials:
mongodb+srv://username:password@cluster.mongodb.net/clinic
- Install MongoDB: https://www.mongodb.com/try/download/community
- Start MongoDB service
- Use connection string:
mongodb://localhost:27017/clinic
Note: Demo mode works without email! This is for production OTP emails.
-
Enable 2-Step Verification on Google Account
- Go to https://myaccount.google.com/security
- Enable 2-Step Verification
-
Generate App Password
- Go to https://myaccount.google.com/apppasswords
- Select "Mail"
- Select "Other (custom name)"
- Choose your device
- Google generates 16-character password
-
Add to
.envEMAIL_USER=your-email@gmail.com EMAIL_PASS=xxxx xxxx xxxx xxxx
-
Restart server - OTP emails now work!
1. User registers/logs in
β
2. Backend hashes password with bcrypt
β
3. JWT token generated (30 days expiry)
β
4. Token sent to frontend
β
5. Frontend stores in localStorage/cookies
β
6. Every request includes: Authorization: Bearer <token>
β
7. Backend validates token with authMiddleware
β
8. Route handler executes
User clicks "Forgot Password"
β
Enters email address
β
Backend generates 6-digit OTP
β
DEMO MODE (No Email Configured):
ββ Logs to console: "π§ [DEMO MODE] OTP Code: 462849"
Frontend says: "Check backend console for OTP"
PRODUCTION MODE (Email Configured):
ββ Sends OTP via Gmail SMTP
User receives in email
β
User enters OTP on frontend
β
Backend validates OTP (expires in 10 minutes)
β
User sets new password
β
Backend hashes new password & updates DB
β
OTP deleted from database
β
User can login with new password
https://hackathon-server-4c7a.onrender.com/api
Or locally:
http://localhost:5000/api
POST /auth/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePassword123!",
"role": "patient" // patient, doctor, receptionist, admin
}
Response: { token, user: {...} }
POST /auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "SecurePassword123!"
}
Response: { token, user: {...} }
POST /auth/forgot-password
Content-Type: application/json
{
"email": "john@example.com"
}
Response: { message: "OTP sent to email / Check backend console" }
POST /auth/reset-password
Content-Type: application/json
{
"email": "john@example.com",
"otp": "462849",
"newPassword": "NewPassword123!"
}
Response: { message: "Password reset successfully" }
GET /auth/profile
Authorization: Bearer <token>
Response: { user: {...} }
PUT /auth/profile
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "John Updated",
"specialization": "Cardiology" // for doctors
}
Response: { user: {...} }
GET /auth/doctors
Authorization: Bearer <token>
Response: { doctors: [...] }
POST /appointments
Authorization: Bearer <token>
Content-Type: application/json
{
"doctorId": "507f1f77bcf86cd799439011",
"patientId": "507f1f77bcf86cd799439012",
"date": "2026-03-25",
"time": "10:00 AM",
"reason": "General checkup"
}
Response: { appointment: {...} }
GET /appointments
Authorization: Bearer <token>
Response: { appointments: [...] }
PUT /appointments/:appointmentId
Authorization: Bearer <token>
Content-Type: application/json
{
"status": "completed" // pending, confirmed, completed, cancelled
}
Response: { appointment: {...} }
DELETE /appointments/:appointmentId
Authorization: Bearer <token>
Response: { message: "Appointment cancelled" }
POST /prescriptions
Authorization: Bearer <token>
Content-Type: application/json
{
"patientId": "507f1f77bcf86cd799439012",
"medicines": [
{
"name": "Aspirin",
"dosage": "500mg",
"frequency": "Twice daily",
"duration": "7 days"
}
],
"instructions": "Take with food"
}
Response: { prescription: {...}, pdfUrl: "..." }
GET /prescriptions
Authorization: Bearer <token>
Response: { prescriptions: [...] }
GET /prescriptions/:prescriptionId/pdf
Authorization: Bearer <token>
Response: PDF file download
GET /patients
Authorization: Bearer <token>
Response: { patients: [...] }
GET /patients/:patientId
Authorization: Bearer <token>
Response: { patient: {...} }
PUT /patients/:patientId
Authorization: Bearer <token>
Content-Type: application/json
{
"bloodType": "O+",
"allergies": "Penicillin",
"medicalHistory": "Diabetes"
}
Response: { patient: {...} }
POST /ai/ask
Authorization: Bearer <token>
Content-Type: application/json
{
"question": "What are the symptoms of flu?"
}
Response: {
response: "Flu symptoms include...",
disclaimer: "This is not medical advice..."
}
GET /admin/users
Authorization: Bearer <token>
Role Required: admin
Response: { users: [...] }
PUT /admin/users/:userId/block
Authorization: Bearer <token>
Role Required: admin
Response: { user: {...} }
PUT /admin/users/:userId/unblock
Authorization: Bearer <token>
Role Required: admin
Response: { user: {...} }
DELETE /admin/users/:userId
Authorization: Bearer <token>
Role Required: admin
Response: { message: "User deleted" }
GET /analytics
Authorization: Bearer <token>
Response: {
totalUsers: 150,
totalAppointments: 342,
totalPrescriptions: 89,
usersByRole: {...},
appointmentsTrend: [...],
...
}
{
_id: ObjectId,
name: String,
email: String (unique),
password: String (hashed),
role: String, // admin, doctor, patient, receptionist
specialization: String, // for doctors
isBlocked: Boolean,
createdAt: Date,
updatedAt: Date
}{
_id: ObjectId,
userId: ObjectId (ref: User),
age: Number,
gender: String,
bloodType: String,
allergies: [String],
medicalHistory: String,
phoneNumber: String,
address: String,
emergencyContact: String,
createdAt: Date,
updatedAt: Date
}{
_id: ObjectId,
doctorId: ObjectId (ref: User),
patientId: ObjectId (ref: User),
date: Date,
time: String,
reason: String,
status: String, // pending, confirmed, completed, cancelled
notes: String,
createdAt: Date,
updatedAt: Date
}{
_id: ObjectId,
doctorId: ObjectId (ref: User),
patientId: ObjectId (ref: User),
medicines: [
{
name: String,
dosage: String,
frequency: String,
duration: String
}
],
instructions: String,
diagnosis: String,
pdfUrl: String,
createdAt: Date,
updatedAt: Date
}{
_id: ObjectId,
patientId: ObjectId (ref: User),
question: String,
response: String,
timestamp: Date
}β
JWT Authentication - Secure token-based auth
β
Password Hashing - bcryptjs with salt rounds
β
Role-Based Access Control - Admin-only endpoints protected
β
OTP Security - 6-digit codes, 10-minute expiration
β
CORS Configuration - Frontend-only access
β
Input Validation - All inputs sanitized
β
Error Handling - No sensitive data in error messages
β
Environment Variables - Secrets not hardcoded
β
Protected Routes - authMiddleware on sensitive endpoints
β
User Blocking - Admin can block user accounts
-
Register User
- Method: POST
- URL:
http://localhost:5000/api/auth/register - Body (JSON):
{ "name": "Test Patient", "email": "patient@test.com", "password": "TestPass123!", "role": "patient" } - Copy the token from response
-
Use Token for Protected Requests
- Add header:
Authorization: Bearer <token> - Example: Get Profile
GET http://localhost:5000/api/auth/profile
- Add header:
-
Test Forgot Password
- Method: POST
- URL:
http://localhost:5000/api/auth/forgot-password - Body:
{ "email": "patient@test.com" } - Check backend console for OTP (Demo Mode)
- Or check email (Production Mode)
Admin:
email: admin@clinic.com
password: admin123
Doctor:
email: doctor@clinic.com
password: doctor123
Patient:
email: patient@clinic.com
password: patient123
Receptionist:
email: receptionist@clinic.com
password: receptionist123
- Push code to GitHub
- Go to https://render.com
- Create new Web Service
- Connect GitHub repository
- Configure:
- Build Command:
npm install - Start Command:
npm start - Environment Variables: Add all from .env
- Build Command:
- Deploy!
Current Deployment: https://hackathon-server-4c7a.onrender.com
# Install Heroku CLI
npm install -g heroku
# Login
heroku login
# Create app
heroku create your-app-name
# Add environment variables
heroku config:set MONGODB_URI=your-connection-string
heroku config:set JWT_SECRET=your-secret
# Deploy
git push heroku main- Similar process with environment variable configuration
- Add MongoDB connection string
- Add JWT secret and email credentials
When: EMAIL_USER and EMAIL_PASS not configured
OTP Output:
Backend Console:
π§ [DEMO MODE] Password Reset OTP
Email: user@example.com
OTP Code: 462849
Expires in: 10 minutes
Frontend Shows: "Check backend console for OTP"
Use Case: Development, testing, quick demonstrations
When: EMAIL_USER and EMAIL_PASS added to .env
OTP Output:
User receives email with OTP code
Frontend shows generic "OTP sent" message
Use Case: Real deployments, actual user emails
Switch anytime: Just add/remove email variables, restart server!
- Check MONGODB_URI in .env
- Verify MongoDB is running (if local)
- Check IP whitelist on MongoDB Atlas (if cloud)
- Add JWT_SECRET to .env
- Make sure it's at least 32 characters
- Restart server
- Check if EMAIL_USER and EMAIL_PASS are configured
- Verify Gmail account has 2-Step Verification enabled
- Confirm using App Password (not regular password)
- Check spam folder
- Or use Demo Mode for testing
- Verify FRONTEND_URL in .env matches frontend URL
- Check frontend Origin header
- Restart backend server
- Verify OTP is correct (demo mode: check console)
- Confirm OTP hadn't expired (10 minutes)
- Check user email exists in database
- Change PORT in .env
- Or kill process:
lsof -ti:5000 | xargs kill -9
Complete API docs with live testing available at:
https://hackathon-server-4c7a.onrender.com/api-docs (if Swagger enabled)
Frontend Repository: (Separate GitHub repo)
- React + Vite SPA
- Consumes this API
- Deployed on Vercel/Netlify
API Status: https://hackathon-server-4c7a.onrender.com
GitHub: [Your reposit]
Issues: [Report on GitHub]
This project is open source and available under the MIT License.
- User authentication & registration
- Role-based access control
- JWT token management
- OTP-based password reset (Demo + Production modes)
- Appointment scheduling
- Prescription management
- PDF generation
- Patient records
- AI assistant integration
- Analytics data aggregation
- Error handling
- CORS configuration
- MongoDB integration
- Email notifications
- Deployed & live
Backend Ready for Production! π