A robust RESTful API backend for the DailyPulse habit tracking application. Built with Node.js, Express, MongoDB, and JWT authentication, this API provides comprehensive endpoints for user management, habit tracking, mood logging, and analytics.
API Base URL: https://dailypulse-backend.onrender.com/api
Health Check: https://dailypulse-backend.onrender.com/api/health
- π JWT Authentication: Secure user registration and login
- π Habit Management: Create, read, update, and delete habits with categories
- π Progress Tracking: Log daily habit completion with notes
- π Mood Tracking: Daily mood logging with emoji-based interface
- π₯ Streak Calculation: Automatic streak tracking and updates
- π Analytics: Comprehensive statistics and trend analysis
- π― Category Breakdown: Organize habits by categories
- π‘ Motivational Content: Random quotes and habit-building tips
- β‘ Real-time Streak Updates: Automatic recalculation on progress logs
- π Protected Routes: JWT middleware for secure endpoints
- π Date Range Queries: Flexible date-based data retrieval
- π¨ Customizable Habits: Support for boolean and countable habit types
- π User Preferences: Theme and notification settings
- π Performance Analytics: Best performing habits tracking
| Technology | Version | Purpose |
|---|---|---|
| Node.js | v18+ | Runtime Environment |
| Express.js | v4.18.2 | Web Framework |
| MongoDB Atlas | Cloud | Database (Production) |
| Mongoose | v8.0.0 | ODM for MongoDB |
| JWT | v9.0.2 | Authentication |
| bcryptjs | v2.4.3 | Password Hashing |
| Helmet | v7.1.0 | Security Headers |
| CORS | v2.8.5 | Cross-Origin Resource Sharing |
| Morgan | v1.10.0 | HTTP Request Logger |
| Express Validator | v7.0.1 | Input Validation |
Before you begin, ensure you have the following installed:
- Node.js: v18.0.0 or higher
- npm: v9.0.0 or higher
- MongoDB: v6.0+ (local) or MongoDB Atlas account (production)
- Git: For cloning the repository
Check your versions:
node --version
npm --version
mongod --version
git clone https://github.com/mrpawarGit/DailyPulse-Backend.git
cd DailyPulse-Backend
npm install
Option A: Local MongoDB
# Start MongoDB service
mongod
Option B: MongoDB Atlas (Cloud - Recommended for Production)
- Create a free account at MongoDB Atlas
- Create a new cluster
- Create a database user
- Get your connection string
- Replace
<username>,<password>, and database name
Create a .env file in the root directory:
# Server Configuration
PORT=3000
NODE_ENV=development
# Database Configuration (Local)
MONGODB_URI=mongodb://localhost:27017/dailypulse
# Database Configuration (Production - MongoDB Atlas)
# MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/dailypulse?retryWrites=true&w=majority
# JWT Configuration
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production_min_32_chars
JWT_EXPIRE=7d
# CORS Configuration
CORS_ORIGIN=http://localhost:5000
# CORS_ORIGIN=https://daily-pulse-app.vercel.app (for production)
- Never commit your
.envfile to version control - Use a strong, random JWT_SECRET (at least 32 characters)
- Change all default credentials in production
- Use environment-specific CORS origins
Start the server with auto-reload using nodemon:
npm run dev
The API will be available at: http://localhost:3000
npm start
Verify the server is running:
curl http://localhost:3000/api/health
Or for production:
curl https://dailypulse-backend.onrender.com/api/health
Expected response:
{
"status": "OK",
"message": "DailyPulse API is running",
"timestamp": "2025-10-25T12:00:00.000Z"
}
Local Development: http://localhost:3000/api
Production: https://dailypulse-backend.onrender.com/api
POST /api/auth/signup
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"password": "password123"
}
Response:
{
"success": true,
"data": {
"user": {
"id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "john@example.com",
"currentStreak": 0,
"longestStreak": 0
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "password123"
}
GET /api/auth/me
Authorization: Bearer <token>
PUT /api/auth/profile
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "John Updated",
"settings": {
"theme": "dark",
"notificationsEnabled": true
}
}
GET /api/habits
Authorization: Bearer <token>
POST /api/habits
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "Drink Water",
"icon": "π§",
"category": "Health",
"type": "countable",
"target": 8,
"color": "blue"
}
PUT /api/habits/:id
Authorization: Bearer <token>
Content-Type: application/json
{
"name": "Drink More Water",
"target": 10
}
DELETE /api/habits/:id
Authorization: Bearer <token>
Response:
{
"success": true,
"message": "Habit and associated logs deleted successfully",
"data": {
"id": "507f1f77bcf86cd799439011"
}
}
PATCH /api/habits/:id/archive
Authorization: Bearer <token>
POST /api/logs
Authorization: Bearer <token>
Content-Type: application/json
{
"habitId": "507f1f77bcf86cd799439011",
"date": "2025-10-25",
"progress": 8,
"notes": "Feeling great!"
}
GET /api/logs/today
Authorization: Bearer <token>
GET /api/logs/date/2025-10-25
Authorization: Bearer <token>
GET /api/logs/habit/:habitId
Authorization: Bearer <token>
GET /api/logs/range?startDate=2025-10-01&endDate=2025-10-25
Authorization: Bearer <token>
POST /api/moods
Authorization: Bearer <token>
Content-Type: application/json
{
"date": "2025-10-25",
"mood": "π",
"notes": "Had a productive day!"
}
GET /api/moods/today
Authorization: Bearer <token>
GET /api/moods/range?startDate=2025-10-01&endDate=2025-10-25
Authorization: Bearer <token>
GET /api/analytics/overview
Authorization: Bearer <token>
Response:
{
"success": true,
"data": {
"totalHabits": 5,
"completedToday": 3,
"completionRate": 60,
"totalCompletions": 150,
"currentStreak": 7,
"longestStreak": 15
}
}
GET /api/analytics/trends?days=7
Authorization: Bearer <token>
GET /api/analytics/category-breakdown
Authorization: Bearer <token>
GET /api/analytics/mood-stats?days=30
Authorization: Bearer <token>
GET /api/analytics/best-habits?days=30
Authorization: Bearer <token>
GET /api/motivation/quote
GET /api/motivation/tips
{
name: String,
email: String (unique, required),
password: String (hashed),
currentStreak: Number,
longestStreak: Number,
lastCompletionDate: Date,
settings: {
theme: String (light/dark),
notificationsEnabled: Boolean
},
createdAt: Date,
updatedAt: Date
}
{
userId: ObjectId (ref: User),
name: String,
icon: String,
category: String (Health/Productivity/Mindfulness/Fitness/Learning/Other),
type: String (boolean/countable),
target: Number,
color: String,
isArchived: Boolean,
createdAt: Date,
updatedAt: Date
}
{
userId: ObjectId (ref: User),
habitId: ObjectId (ref: Habit),
date: String (YYYY-MM-DD),
progress: Number,
completed: Boolean,
notes: String,
createdAt: Date,
updatedAt: Date
}
{
userId: ObjectId (ref: User),
date: String (YYYY-MM-DD),
mood: String (π/π/π/π‘/π΄),
notes: String,
createdAt: Date,
updatedAt: Date
}
dailypulse-backend/
βββ config/
β βββ db.js # MongoDB connection
β βββ jwt.js # JWT token utilities
βββ models/
β βββ User.js # User model & schema
β βββ Habit.js # Habit model & schema
β βββ HabitLog.js # Habit log model & schema
β βββ Mood.js # Mood model & schema
βββ controllers/
β βββ authController.js # Authentication logic
β βββ habitController.js # Habit CRUD operations
β βββ logController.js # Log management
β βββ analyticsController.js # Analytics calculations
β βββ motivationController.js # Motivational content
βββ routes/
β βββ auth.routes.js # Auth endpoints
β βββ habit.routes.js # Habit endpoints
β βββ log.routes.js # Log endpoints
β βββ mood.routes.js # Mood endpoints
β βββ analytics.routes.js # Analytics endpoints
β βββ motivation.routes.js # Motivation endpoints
βββ middleware/
β βββ authMiddleware.js # JWT verification
β βββ errorHandler.js # Global error handler
β βββ validateRequest.js # Input validation
βββ utils/
β βββ streakCalculator.js # Streak calculation logic
βββ .env # Environment variables (not in repo)
βββ .gitignore
βββ package.json
βββ server.js # Application entry point
βββ README.md
This API implements multiple security measures:
- JWT Authentication: Secure token-based authentication with 7-day expiry
- Password Hashing: bcrypt with 10 salt rounds
- Helmet.js: Security headers (XSS, CSP, HSTS, etc.)
- CORS: Configured for specific frontend origins
- Input Validation: Express-validator for request validation
- Environment Variables: Sensitive data stored securely
- MongoDB Injection Protection: Mongoose built-in sanitization
- Rate Limiting: Protection against brute force attacks
# Health check (Production)
curl https://dailypulse-backend.onrender.com/api/health
# Register user
curl -X POST https://dailypulse-backend.onrender.com/api/auth/signup \
-H "Content-Type: application/json" \
-d '{"name":"Test User","email":"test@example.com","password":"password123"}'
# Login
curl -X POST https://dailypulse-backend.onrender.com/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"password123"}'
- Import the API endpoints into Postman
- Set up an environment variable for
authToken - Set base URL:
https://dailypulse-backend.onrender.com/api - Test all endpoints systematically
{
"info": {
"name": "DailyPulse API",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Health Check",
"request": {
"method": "GET",
"url": "{{baseUrl}}/health"
}
}
]
}
The API is live and deployed at: https://dailypulse-backend.onrender.com
Steps to deploy on Render:
-
Create a Render account at render.com
-
Create a new Web Service
- Click "New +" β "Web Service"
- Connect your GitHub repository
- Choose "Node" as environment
- Build command:
npm install - Start command:
npm start - Choose free plan or paid plan
-
Add Environment Variables in Render dashboard:
MONGODB_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/dailypulse JWT_SECRET=your_production_secret_key_at_least_32_characters_long NODE_ENV=production CORS_ORIGIN=https://daily-pulse-app.vercel.app PORT=3000 -
Deploy
- Click "Create Web Service"
- Render will automatically deploy your app
- Get your API URL:
https://your-app-name.onrender.com
-
Update Frontend
- Update
VITE_API_URLin frontend.envto your Render URL
- Update
-
Create MongoDB Atlas Account
- Visit MongoDB Atlas
- Sign up for free
-
Create a Cluster
- Choose Free Tier (M0)
- Select region (closest to your Render deployment)
- Create cluster
-
Create Database User
- Database Access β Add New Database User
- Set username and strong password
- Grant "Read and write to any database" role
-
Whitelist IP Address
- Network Access β Add IP Address
- Click "Allow Access from Anywhere" (0.0.0.0/0)
- For production, whitelist specific IPs
-
Get Connection String
- Click "Connect" on your cluster
- Choose "Connect your application"
- Copy connection string
- Replace
<username>,<password>, and database name
- Auto-Deploy: Enable auto-deploy from GitHub for automatic updates
- Health Checks: Render automatically pings
/api/health - Environment Variables: Never commit
.envto GitHub - Logs: View real-time logs in Render dashboard
- Cold Starts: Free tier apps sleep after inactivity (takes ~30s to wake)
- Use CommonJS module pattern (require/module.exports)
- Add JSDoc comments for functions
- Handle errors properly with try-catch blocks
- Use async/await for asynchronous operations
- Follow REST API naming conventions
- Write meaningful commit messages
- Free tier on Render experiences cold starts (~30 seconds)
- Rate limiting not yet implemented (coming soon)
For more issues, check GitHub Issues.
Mayur Pawar - @mrpawarGit
Akash Pandit - @Akashpandit01
Frontend: DailyPulse-Frontend
Live Demo: https://daily-pulse-app.vercel.app
- Express.js team for the excellent framework
- MongoDB team for the powerful database
- Render for reliable hosting
- All contributors who help improve this project
- Core API endpoints
- JWT authentication
- MongoDB integration
- Habit CRUD operations
- Mood tracking
- Analytics endpoints
- Deployment to Render
- Implement rate limiting for API endpoints
- Add WebSocket support for real-time updates
- Implement email notifications
- Add social features (friends, leaderboards)
- Add data export functionality
Built with β€οΈ using Node.js + Express + MongoDB 12. β Updated testing examples for production
Your Backend README is now complete and professional! πβ¨