masaruk Logo

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

ComponentTechnologyPurpose
RuntimeNode.js LTS (v24+)JavaScript runtime
LanguageTypeScript 5.xType-safe JavaScript
FrameworkExpress.js / FastifyHTTP server framework
ORMPrismaDatabase access and migrations
DatabasePostgreSQL 15+Primary data store
CacheRedisSession, API response caching
QueueBullMQBackground job processing
ValidationZodRuntime type validation
AuthenticationJWT (jsonwebtoken)Token-based auth
File StorageAWS S3 / CompatibleMedia assets storage

2.2 Development Tools

ToolPurpose
ESLintCode linting
PrettierCode formatting
Jest / VitestTesting framework
tsx / ts-nodeTypeScript execution
NodemonDevelopment hot-reload
DockerContainerization

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)

src/app.ts (Application entry point)
src/server.ts (Server bootstrap)
src/config/ (Configuration files)
src/modules/ (Feature modules)
src/middleware/ (Express middleware)
src/shared/ (Shared utilities, types, errors)
src/jobs/ (Queue workers)
prisma/schema.prisma (Database schema)
tests/ (Unit, integration, e2e)

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:

*.controller.ts - HTTP handlers
*.service.ts - Business logic
*.repository.ts - Database operations
*.routes.ts - Route definitions
*.schemas.ts - Zod validation schemas
*.types.ts - TypeScript types
*.test.ts - Unit tests

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_STAFFCUSTOMER

7. Request Lifecycle (API Flow)

  1. Request received by Express/Fastify
  2. Global middleware (cors, helmet, compression)
  3. Rate limiting middleware
  4. Route matched
  5. Auth middleware (if protected route)
  6. RBAC middleware (role check)
  7. Validation middleware (Zod schema)
  8. Controller method
  9. Service layer (business logic)
  10. Repository layer (database via Prisma)
  11. Response formatting
  12. Error handling middleware (if error)
  13. Response sent

8. Service Layer (Business Logic)

All MASARUK modules use dedicated service classes:

TripsServiceBookingsServicePaymentsServiceAdCampaignServiceProvidersServiceHotelsServiceBusesServiceRestStopsServiceRatingsServiceFinancialReportService

Each 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:

TripsRepositoryBookingsRepositoryPaymentTransactionsRepositoryHotelsRepositoryBusesRepositoryRestStopsRepositoryRatingsRepository

Responsibilities:

  • 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:

PerformanceReliabilityUser experience

13. Payment Processing Flow

Official integrations:

HyperPaySTC PayMadaApple Pay (iOS)
  1. User submits booking
  2. Backend creates pending payment transaction
  3. Redirect/proxy to payment gateway
  4. Gateway calls backend callback webhook
  5. Backend verifies signature
  6. If success: Confirm payment, Create booking, Reduce trip availability, Send notifications
  7. 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:

TypeScript-first for type safetyModular with clear separation of concernsService-based for testable business logicAPI-driven with consistent REST patternsSecure with multiple layers of protectionScalable with queue-based async processingObservable with structured loggingConsistent with all platform clients

This document defines the standard approach for all MASARUK backend development using Node.js.