analysis/07-architecture/backend-architecture-nodejs.md
Backend Architecture – Node.js
Node.js (TypeScript) backend architecture powering MASARUK's RESTful API layer
1. Purpose of This Document
This document describes the backend architecture powering MASARUK's RESTful API layer built with Node.js. It outlines:
- Node.js internal structure and patterns
- Modules and service layers
- Authentication flow
- Request lifecycle
- Caching, queues, notifications
- Payments integration handling
- Deployment considerations
- Security practices
This file provides the architectural foundation for backend developers and API integrators.
2. Technology Stack
2.1 Core Technologies
| Component | Technology | Purpose |
|---|---|---|
| Runtime | Node.js LTS (v24+) | JavaScript runtime |
| Language | TypeScript 5.x | Type-safe JavaScript |
| Framework | Express.js / Fastify | HTTP server framework |
| ORM | Prisma | Database access and migrations |
| Database | PostgreSQL 15+ | Primary data store |
| Cache | Redis | Session, API response caching |
| Queue | BullMQ | Background job processing |
| Validation | Zod | Runtime type validation |
| Authentication | JWT (jsonwebtoken) | Token-based auth |
| File Storage | AWS S3 / Compatible | Media assets storage |
2.2 Development Tools
| Tool | Purpose |
|---|---|
| ESLint | Code linting |
| Prettier | Code formatting |
| Jest / Vitest | Testing framework |
| tsx / ts-node | TypeScript execution |
| Nodemon | Development hot-reload |
| Docker | Containerization |
3. Architectural Principles
3.1 Modular, Service-Oriented Design
The backend follows Controller → Service → Repository architecture:
- Controllers → thin, API-only (handle HTTP concerns)
- Services → handle business logic
- Repositories → DB operations (abstracted data access)
- DTOs/Schemas → strict data validation contracts (Zod)
- Models → Prisma schema definitions
This ensures:
- Testability
- No business logic in controllers
- Predictable API behavior
- Reusable logic for Admin, Provider, and B2C clients
3.2 TypeScript-First Approach
- Type safety
- Better IDE support
- Self-documenting code
- Reduced runtime errors
4. Directory Structure (High-Level)
Key points:
- All API requests enter at src/app.ts
- All versioned endpoints use /api/v1/...
- Controllers never contain business rules
- Each module is self-contained with its own routes, controllers, services
5. Module Structure Pattern
Each module follows a consistent structure:
6. Authentication Architecture
6.1 JWT-Based Authentication
MASARUK uses JWT (JSON Web Tokens) for authentication:
- Access Token stored in memory/header (15 min - 1 hour expiry)
- Refresh Token stored in HTTP-only cookie (7-30 days expiry)
- Token payload includes: userId, email, role, providerId
6.2 Role-Based Access Control (RBAC)
- Implemented via RBAC Middleware
- Permissions matrix documented in 08-rbac/roles-and-permissions-matrix.md
SUPER_ADMINADMINFINANCE_ADMINSUPPORT_AGENTPROVIDER_ADMINPROVIDER_STAFFCUSTOMER7. Request Lifecycle (API Flow)
- Request received by Express/Fastify
- Global middleware (cors, helmet, compression)
- Rate limiting middleware
- Route matched
- Auth middleware (if protected route)
- RBAC middleware (role check)
- Validation middleware (Zod schema)
- Controller method
- Service layer (business logic)
- Repository layer (database via Prisma)
- Response formatting
- Error handling middleware (if error)
- Response sent
8. Service Layer (Business Logic)
All MASARUK modules use dedicated service classes:
TripsServiceBookingsServicePaymentsServiceAdCampaignServiceProvidersServiceHotelsServiceBusesServiceRestStopsServiceRatingsServiceFinancialReportServiceEach service handles:
- Validation rules (beyond basic schema validation)
- Domain logic
- State transitions & lifecycle rules
- Triggering notifications or events
- Ensuring data consistency
9. Repository Layer (Data Access)
Repositories encapsulate all database interactions using Prisma:
TripsRepositoryBookingsRepositoryPaymentTransactionsRepositoryHotelsRepositoryBusesRepositoryRestStopsRepositoryRatingsRepositoryResponsibilities:
- Build optimized Prisma queries
- Enforce soft deletes
- Filter by Provider/Admin/User when needed
- Ensure proper relations & eager loading
Repositories must never expose internal DB structures to controllers.
10. Validation with Zod
All input validation uses Zod schemas for type-safe runtime validation:
- Composable schema definitions
- TypeScript type inference
- Custom error messages
- Middleware integration
11. Caching Strategy
What is cached:
- Trips list (with TTL)
- Trip details
- Popular destinations
- Provider shared assets
- Configurable settings
Where cached: Redis (ioredis)
Invalidation:
- When a trip is updated
- After new booking affects availability
- After price update
- After provider edits resources
12. Queue System (BullMQ)
Used for:
- Sending emails (nodemailer)
- Triggering SMS/OTP
- Push notifications (FCM via firebase-admin)
- Payment confirmations
- Generating financial exports
- Heavy aggregation (ratings, revenue stats)
Improves:
13. Payment Processing Flow
Official integrations:
- User submits booking
- Backend creates pending payment transaction
- Redirect/proxy to payment gateway
- Gateway calls backend callback webhook
- Backend verifies signature
- If success: Confirm payment, Create booking, Reduce trip availability, Send notifications
- If failed: Mark transaction as failed, No booking created
14. Notifications Architecture
Push Notifications (Mobile)
- Firebase Cloud Messaging (FCM) via firebase-admin
- Triggered by: Booking confirmation, Trip reminders, Rating invitations, Cancellation notices
Email Notifications
- nodemailer with SMTP
- Transactional emails: Payment receipts, Booking confirmation, Itinerary details
SMS
- OTP (if used)
- Payment / booking confirmations (optional)
15. Logging & Monitoring
Logger: Pino (structured JSON logging)
- Log levels (error, warn, info, debug)
- Request/response logging via pino-http
- Sensitive data redaction
- Pretty printing in development
16. Deployment Architecture (Backend)
Hosting
- Linux server (Ubuntu recommended)
- Docker containers
- Node.js LTS (v24+)
Processes
- Node.js API server (clustered via PM2)
- BullMQ workers
- Redis service
- Cron jobs for: Periodic cleanup, Settlement processes, Rating reminders
Delivery
- CI/CD pipeline
- Zero-downtime deployment
- Environment variables stored securely
- Docker images built per release
17. Security Policies
- HTTPS everywhere
- Input validation (Zod - never trust client)
- SQL injection prevention (Prisma parameterized queries)
- XSS prevention (helmet)
- CSRF protection (where applicable)
- Rate limiting (express-rate-limit)
- Password hashing (bcrypt/argon2)
- JWT secure configuration
- Sensitive data not logged
- Environment variables for secrets
18. Testing Strategy
Unit Tests
Jest/Vitest for service and repository unit tests
Integration Tests
Supertest for API endpoint testing
E2E Tests
Full flow tests with test database
19. Summary
The MASARUK Node.js backend architecture is:
This document defines the standard approach for all MASARUK backend development using Node.js.