- Project Overview
- System Architecture
- Technology Stack
- System Components
- Data Models & Relationships
- API Design
- Security Architecture
- Request Flow
- Middleware Pipeline
- Data Management & Seeding
- Deployment Architecture
- Scalability Considerations
- Future Improvements
DevCamper API is a RESTful backend API built with Node.js and Express.js for managing an educational bootcamp platform. The system allows users to:
- Manage Bootcamps: Create, read, update, and delete bootcamp listings
- Manage Courses: Associate courses with bootcamps
- User Reviews: Allow users to review and rate bootcamps
- User Authentication: JWT-based authentication with role-based access control
- Geospatial Search: Find bootcamps by location and radius
- File Upload: Upload photos for bootcamps
- RESTful API design
- JWT/Cookie-based authentication
- Role-based access control (User, Publisher, Admin)
- Geocoding integration for location-based searches
- Advanced querying (pagination, filtering, sorting)
- Comprehensive security measures
- File upload capabilities
- Email notifications for password reset
graph TD
subgraph ClientLayer [Client Layer]
C1[Web App]
C2[Mobile App]
C3[Postman/Insomnia]
end
subgraph AppLayer [Application Layer]
subgraph Express [Express.js Server]
MW[Middleware Pipeline]
RH[Routes Handler]
CL[Controller Logic]
MW --> RH
RH --> CL
end
subgraph BusinessLogic [Business Logic Layer]
Auth[Auth & Authorization]
Val[Validation]
Geo[Geocoding]
File[File Processing]
Mail[Email Service]
CL --> Auth
CL --> Val
CL --> Geo
CL --> File
CL --> Mail
end
end
subgraph DataLayer [Data Layer]
DB[(MongoDB Database)]
Coll1(Users Collection)
Coll2(Bootcamps Collection)
Coll3(Courses Collection)
Coll4(Reviews Collection)
DB --- Coll1
DB --- Coll2
DB --- Coll3
DB --- Coll4
end
subgraph ExternalServices [External Services]
ExtGeo[Geocoding API]
ExtMail[Email Service]
ExtFile[Local Filesystem]
end
ClientLayer -->|HTTP/HTTPS| AppLayer
BusinessLogic --> DataLayer
Geo -.-> ExtGeo
Mail -.-> ExtMail
File -.-> ExtFile
- Layered Architecture: Separation of concerns with distinct layers (Routes β Controllers β Models)
- MVC Pattern: Model-View-Controller pattern (though View is replaced by JSON responses)
- Middleware Pattern: Request processing through middleware pipeline
- Runtime: Node.js (v20.15.0+)
- Framework: Express.js (v5.2.1)
- Database: MongoDB with Mongoose ODM (v8.9.5)
- Language: JavaScript (ES6+)
helmet: Security headersexpress-rate-limit: Rate limiting (100 req/10min)hpp: HTTP Parameter Pollution protectioncors: Cross-Origin Resource Sharinglusca: CSRF protectionbcryptjs: Password hashingjsonwebtoken: JWT token generation/verificationexpress-session: Session managementlusca: CSRF protection
dotenv: Environment variable managementmorgan: HTTP request loggerexpress-fileupload: File upload handlingnode-geocoder: Geocoding service integrationnodemailer: Email sendingslugify: URL-friendly string generationjoi: Input validation
nodemon: Development server auto-reloadjest: Testing frameworksupertest: HTTP assertion libraryprettier: Code formatting
Defines API endpoints and maps them to controller functions.
Structure:
routes/
βββ bootcampsRoute.js # /api/v1/bootcamps
βββ coursesRoute.js # /api/v1/courses
βββ authRoute.js # /api/v1/auth
βββ usersRoute.js # /api/v1/users
βββ reviewsRoute.js # /api/v1/reviews
Responsibilities:
- Define HTTP methods (GET, POST, PUT, DELETE)
- Apply middleware (authentication, authorization, validation)
- Route requests to appropriate controllers
Contains business logic for handling requests.
Structure:
controllers/
βββ bootcampsController.js # Bootcamp CRUD operations
βββ coursesController.js # Course management
βββ authController.js # Authentication logic
βββ usersController.js # User management
βββ reviewsController.js # Review management
Responsibilities:
- Process request data
- Interact with models/database
- Handle business rules
- Return JSON responses
Mongoose schemas defining data structure and validation.
Structure:
models/
βββ BootcampModel.js # Bootcamp schema
βββ CourseModel.js # Course schema
βββ ReviewModel.js # Review schema
βββ UserModel.js # User schema
Features:
- Schema validation
- Pre/post hooks (e.g., password hashing, geocoding)
- Virtual fields
- Indexes for performance
Custom middleware functions for request processing.
Key Middleware:
auth.js: JWT authentication and role authorizationerror.js: Global error handleradvancedResults.js: Pagination, filtering, sortingvalidate.js: Request validationlogger.js: Request loggingasync.js: Async error wrapper
Helper functions and services.
Components:
geocoder.js: Geocoding service wrappersendMail.js: Email serviceErrorResponse.js: Custom error classvalidators/: Joi validation schemas
Database connection and configuration.
Components:
db.js: MongoDB connection logic- Handles test/production database switching
erDiagram
USER ||--o{ BOOTCAMP : "owns"
USER ||--o{ REVIEW : "writes"
BOOTCAMP ||--o{ COURSE : "contains"
BOOTCAMP ||--o{ REVIEW : "receives"
USER {
string id PK
string name
string email
string password
string role
string resetToken
}
BOOTCAMP {
string id PK
string name
string description
string address
object location
string careers
string user FK
string photo
string slug
}
COURSE {
string id PK
string title
string description
int weeks
int tuition
string bootcamp FK
}
REVIEW {
string id PK
string title
string text
int rating
string bootcamp FK
string user FK
}
{
name: String (required),
email: String (required, unique),
password: String (required, hashed),
role: Enum ['user', 'publisher'] (default: 'user'),
resetPasswordToken: String,
resetPasswordExpire: Date
}Features:
- Password hashing via bcrypt (pre-save hook)
- JWT token generation method
- Password reset token generation
- Password comparison method
{
name: String (required, max 100 chars),
slug: String (auto-generated),
description: String (required, max 500 chars),
website: String (URL validation),
phone: String (max 20 chars),
email: String,
address: String (required),
location: {
type: 'Point',
coordinates: [longitude, latitude],
formattedAddress: String,
street, city, state, zipcode, country
},
careers: [String] (enum: Web Dev, Mobile Dev, UI/UX, etc.),
averageRating: Number (1-10),
averageCost: Number,
photo: String,
housing: Boolean,
jobAssistance: Boolean,
jobGuarantee: Boolean,
acceptGi: Boolean
}Features:
- Auto-generates slug from name (pre-save hook)
- Geocodes address to coordinates (pre-save hook)
- 2dsphere index on location for geospatial queries
- Virtual field for courses (reverse populate)
- Cascade delete courses on bootcamp deletion
{
title: String (required),
description: String (required),
weeks: String (required),
tuition: Number (required),
minimumSkill: Enum ['beginner', 'intermediate', 'advanced'],
scholarshipAvailable: Boolean,
bootcamp: ObjectId (ref: Bootcamp, required)
}Features:
- References Bootcamp model
- Cascade delete when bootcamp is deleted
{
title: String (required),
text: String (required),
rating: Number (required, 1-10),
bootcamp: ObjectId (ref: Bootcamp, required),
user: ObjectId (ref: User, required)
}Features:
- One review per user per bootcamp (unique constraint)
- References both Bootcamp and User models
All endpoints follow RESTful conventions:
- Base URL:
/api/v1 - Resource-based URLs
- HTTP methods: GET, POST, PUT, DELETE
- JSON request/response format
The API is fully documented using Swagger (OpenAPI 3.0).
- Documentation URL:
/docs - Specification File:
docs/swagger.json - Interactive UI: Allows testing all endpoints directly from the browser.
POST /register # User registration
POST /login # User login
GET /logout # User logout
GET /me # Get current user
POST /forgotpassword # Request password reset
PUT /resetpassword/:resettoken # Reset password
PUT /updatedetails # Update user details
PUT /updatepassword # Update password
GET / # Get all bootcamps (paginated, filtered)
GET /:id # Get single bootcamp
POST / # Create bootcamp (auth required, publisher/admin)
PUT /:id # Update bootcamp (owner/admin)
DELETE /:id # Delete bootcamp (owner/admin)
PUT /:id/photo # Upload bootcamp photo (owner/admin)
GET /radius/:zipcode/:distance # Get bootcamps within radius
Query Parameters:
page: Page numberlimit: Results per pageselect: Fields to includesort: Sort fieldfilter: Filter criteria (e.g.,careers[in]=Web Development)
GET / # Get all courses
GET /bootcamp/:bootcampId # Get courses for bootcamp
GET /:id # Get single course
POST /bootcamp/:bootcampId # Create course (auth, publisher/admin)
PUT /:id # Update course (owner/admin)
DELETE /:id # Delete course (owner/admin)
GET / # Get all reviews
GET /bootcamp/:bootcampId # Get reviews for bootcamp
GET /:id # Get single review
POST /bootcamp/:bootcampId # Create review (auth, user/admin)
PUT /:id # Update review (owner/admin)
DELETE /:id # Delete review (owner/admin)
GET / # Get all users (admin only)
GET /:id # Get single user (admin only)
POST / # Create user (admin only)
PUT /:id # Update user (admin only)
DELETE /:id # Delete user (admin only)
Success Response:
{
"success": true,
"data": { ... },
"pagination": { ... } // For list endpoints
}Error Response:
{
"success": false,
"error": "Error message",
"source": "controller_name"
}- JWT Tokens: Stateless authentication
- Cookie-based: Alternative token storage
- Token Expiry: Configurable (default: 30 days)
- Password Hashing: bcrypt with salt rounds (10)
- Role-Based Access Control (RBAC):
user: Can create reviewspublisher: Can create/manage bootcamps and coursesadmin: Full access
- Resource Ownership: Users can only modify their own resources
Request β Helmet β CORS β Rate Limit β HPP β CSRF β Body Parser
Helmet: Sets security HTTP headers
- X-Content-Type-Options
- X-Frame-Options
- X-XSS-Protection
- Strict-Transport-Security
Rate Limiting:
- 100 requests per 10 minutes per IP
- Prevents brute force attacks
HPP (HTTP Parameter Pollution):
- Prevents duplicate parameter attacks
CSRF Protection:
- Enabled in production
- Uses Lusca middleware
CORS:
- Configurable origins
- Credentials support
- Joi Validation: Request body/query validation
- Mongoose Validation: Schema-level validation
- Sanitization: Prevents NoSQL injection
- Minimum 6 characters
- Bcrypt hashing (salt rounds: 10)
- Password reset tokens (SHA-256 hashed, 10-minute expiry)
sequenceDiagram
participant Client
participant Server as Express Server
participant SecMW as Security Middleware
participant BP as Body/Cookie Parser
participant Log as Logger
participant Router
participant Auth as Auth Middleware
participant Ctrl as Controller
participant DB as MongoDB
participant Ext as External APIs
Client->>Server: HTTP Request
Server->>SecMW: Process Security (Helmet, CORS, Rate Limit)
SecMW->>BP: Parse JSON & Cookies
BP->>Log: Log Request (Morgan)
Log->>Router: Match Route
Router->>Auth: Authenticate (JWT) & Authorize (Roles)
Auth->>Ctrl: Call Controller Function
Ctrl->>DB: Database Operations
DB-->>Ctrl: Data Results
Ctrl-->>Ext: External Services (Geocoding/Email)
Ext-->>Ctrl: Results
Ctrl-->>Client: Success/Error Response
Flow: POST /api/v1/bootcamps with Bearer Token
- Client sends request with Auth header.
- Rate Limiter checks IP & CORS validates origin.
- Helmet sets security headers & Body Parser extracts JSON.
- Auth Middleware verifies JWT and loads
req.user. - Authorize checks if user is 'publisher' or 'admin'.
- Controller creates bootcamp, triggers pre-save hooks (Geocoding, Slug).
- Success Response sent back to client.
graph LR
A[Start] --> B[Trust Proxy]
B --> C[Cookie Parser]
C --> D[Logger]
D --> E[File Upload]
E --> F[Security Stack]
F --> G[CORS/HPP]
G --> H[Session/CSRF]
H --> I[Routes]
I --> J[Error Handler]
- Extracts JWT from Authorization header or cookie
- Verifies token signature
- Loads user from database
- Attaches user to
req.user
- Checks user role against required roles
- Returns 403 if unauthorized
- Pagination:
page,limit - Field selection:
select - Sorting:
sort - Filtering: Query string parsing
- Populates related data
- Centralized error handling
- Formats error responses
- Logs errors for monitoring
- Handles specific error types:
- CastError (Invalid ID)
- ValidationError (Mongoose)
- Duplicate Key (11000)
Contains initial seed data in JSON format:
bootcamps.json: Initial bootcamp listingscourses.json: Course data associated with bootcampsusers.json: Default user accounts (Admin, Publisher, User)reviews.json: Sample reviews
A utility script to manage database state.
- Import Data:
node seeder.js -i - Destroy Data:
node seeder.js -d
Features:
- Clear existing collections before import
- Bulk insert using Mongoose
- Color-coded console output for status tracking
graph TD
subgraph Vercel [Vercel Platform]
Node[Node.js Runtime]
Express[Express Application]
Static[Static File Storage]
Node --> Express
end
subgraph MongoDBAtlas [MongoDB Atlas]
DB[(Cloud Database Clusters)]
Users(Users)
Bootcamps(Bootcamps)
Courses(Courses)
Reviews(Reviews)
DB --- Users
DB --- Bootcamps
DB --- Courses
DB --- Reviews
end
Express -->|MongoDB Connection| DB
- Development: Local MongoDB, file-based logging
- Test: Separate test database
- Production: MongoDB Atlas, Vercel serverless
config/config.json: Application configuration.env: Environment variables (not committed)vercel.json: Vercel deployment configuration
- File Storage: Local filesystem (not scalable)
- Single Server: No horizontal scaling
- Database: Single MongoDB instance
- No Caching: Every request hits database
- Current: Local filesystem
- Recommended: AWS S3, Cloudinary, or Azure Blob Storage
- Benefits: Scalable, CDN integration, backup
- Redis: Cache frequently accessed data
- Cache Strategies:
- Bootcamp listings (TTL: 5 minutes)
- User sessions
- Geocoding results
- Indexing: Ensure proper indexes on:
- User email (unique)
- Bootcamp location (2dsphere)
- Bootcamp slug
- Review bootcamp/user combination
- Read Replicas: For read-heavy operations
- Connection Pooling: Optimize MongoDB connections
- Multiple Instances: Deploy multiple server instances
- Load Balancer: Distribute traffic
- Session Management: Use Redis for shared sessions
- Per-User Limits: Beyond IP-based limiting
- Tiered Limits: Different limits for user roles
- Distributed Rate Limiting: Redis-based for multi-instance
- APM Tools: Elastic APM, New Relic
- Log Aggregation: ELK Stack, Splunk
- Error Tracking: Sentry, Rollbar
- Metrics: Prometheus, Grafana
- Queue System: Bull, RabbitMQ
- Use Cases:
- Email sending
- Image processing
- Geocoding (async)
- Report generation
- Current:
/api/v1 - Strategy: Maintain multiple versions during transitions
- Pagination: Prevents large dataset retrieval
- Field Selection: Reduces payload size
- Database Indexes: Faster queries
- Virtual Populate: Efficient related data loading
- Response Compression: gzip compression
- Database Query Optimization: Use
explain()to analyze queries - Connection Pooling: Reuse database connections
- Lazy Loading: Load related data only when needed
- Batch Operations: Group multiple operations
- Framework: Jest
- HTTP Testing: Supertest
- Test Files: Located in
tests/directory
- Unit tests for controllers
- Integration tests for routes
- Authentication/authorization tests
- E2E Tests: Full request/response cycle
- Load Testing: Artillery, k6
- Security Testing: OWASP ZAP
- Coverage Reports: Istanbul/nyc
The DevCamper API is a well-structured RESTful API following best practices for security, validation, and error handling. The layered architecture provides clear separation of concerns, making it maintainable and extensible.
β Clean architecture and code organization β Comprehensive security measures β Role-based access control β Geospatial search capabilities β Proper error handling β Input validation at multiple layers
π§ Cloud-based file storage (S3/Cloudinary) π§ Caching layer (Redis/Memcached) π§ Background job processing (Bull/RabbitMQ) π§ Enhanced monitoring (ELK/New Relic) π§ Horizontal scaling support
Document Version: 1.1
Last Updated: 2026-03-10
Maintained By: SOURAV ROY