A Production-Ready E-Commerce Backend API
A sophisticated, fully-featured e-commerce backend built with NestJS, MongoDB, and TypeScript. Africa Store Backend provides a complete REST API with real-time capabilities, secure authentication, payment processing, and advanced business logic for modern e-commerce applications.
- Overview
- Tech Stack
- Key Features
- Architecture
- Quick Start
- Environment Setup
- Project Structure
- API Modules
- Database Models
- Authentication & Security
- File Management
- Payment Processing
- Email Notifications
- Real-time Features
- Testing
- Docker Deployment
- Development
- Troubleshooting
- Contributing
Africa Store Backend is a comprehensive e-commerce API solution designed with scalability, security, and developer experience in mind. It supports multi-user management, complex product catalogs, shopping cart operations, order processing with payment integration, promotional campaigns via coupons, and real-time inventory updates.
Built for production-grade applications requiring robust authentication, secure payment handling, and real-time communication channels.
| Layer | Technology |
|---|---|
| Runtime | Node.js 18+ |
| Framework | NestJS 11.0+ |
| Language | TypeScript 5.7+ |
| Database | MongoDB 4.0+ (via Mongoose ODM) |
| API GraphQL | Apollo Server 5.4 |
| Authentication | JWT + OTP |
| Caching | Redis + In-Memory Cache Manager |
| File Storage | Cloudinary |
| Real-time | Socket.IO |
| Payments | Stripe |
| Resend & Brevo (Brevo/Sendinblue) | |
| Validation | class-validator, class-transformer |
| Testing | Jest, Supertest |
| Security | bcrypt, dotenv, CORS |
- OTP-Based Registration: Secure registration flow with one-time passwords sent via email
- JWT Authentication: Dual-token system with access tokens and refresh tokens
- Access Token: Short-lived (configurable, default 1h)
- Refresh Token: Long-lived (configurable, default 7 days)
- Role-Based Access Control (RBAC): User and Admin roles with permission-based guards
- Password Security: bcrypt hashing with salt rounds for secure password storage
- Token Management: Token whitelist/blacklist for logout functionality
- Complete user profile management
- Flexible authentication flows (registration, login, refresh tokens)
- Password reset functionality with secure OTP verification
- User metadata and preference storage
- Role-based user distinction (standard users vs administrators)
- Product Catalog: Full CRUD operations for products
- Product details: name, description, price, SKU
- Multi-image support with Cloudinary integration
- Stock level tracking with real-time updates
- Product status management (active/inactive)
- Search, filter, and sorting capabilities
- Hierarchical category organization
- Category-to-product relationships
- Bulk category operations
- Category-based product filtering
- Session-based or user-specific shopping carts
- Add, update, and remove cart items
- Real-time cart total calculations (subtotal, tax, discounts)
- Cart persistence across sessions
- Automatic calculation of pricing with applied coupons
- Complete order lifecycle management
- Multiple order statuses (pending, processing, shipped, delivered, cancelled)
- Order history tracking with detailed order information
- Relationship mapping to users, products, and cart items
- Order summary with pricing breakdown
- Stripe Checkout Sessions: Create checkout sessions for secure payment processing
- Webhook Handling: Secure webhook processing for payment confirmations
- Automatic order confirmation on successful payment
- Invoice generation and delivery
- Handle various Stripe events (payment succeeded, failed, etc.)
- Payment Reconciliation: Automatic synchronization of payment status with orders
- Webhook Verification: HMAC-SHA256 signature verification for secure webhooks
- Create and manage discount coupons
- Coupon validation and application
- Discount percentage or fixed amount support
- Usage limit tracking per coupon
- Expiration date management
- Automatic discount calculation on cart/orders
- Multi-Provider Support:
- Resend: Modern email delivery service
- Brevo (Sendinblue): Traditional email marketing platform
- Email Templates: Handlebars-based templating for dynamic email generation
- Automated Emails:
- OTP verification emails
- Order confirmation emails
- Payment receipt emails
- Password reset instructions
- User welcome emails
- Cloudinary Integration: Cloud-based image storage
- Upload Types:
- Product images and thumbnails
- User profile pictures
- Dynamic file resizing and optimization
- URL Generation: Auto-generated CDN URLs for optimized delivery
- Folder Organization: Organized cloud folder structure for easy management
- Socket.IO Integration: Bi-directional communication channel
- Real-time Inventory Updates: Instant stock level synchronization
- Live Notifications: User notifications for order status changes
- Broadcast Events: System-wide announcements
- Connection Management: Automatic reconnection and fallback handling
- Homepage configuration and management
- Featured products showcase
- Promotional banner management
- Dynamic content updates
- Multi-Level Caching:
- Redis-backed distributed cache
- In-memory cache for immediate lookups
- Cache Invalidation: Automatic cache update on data changes
- Performance Optimization: Reduced database queries
- Unit Tests: Jest-based unit test suite with high coverage
- End-to-End Tests: Supertest integration tests
- Mocking: Complete mock support for external dependencies
- Coverage Reports: Code coverage analysis
- Faker-Based Data Generation: Realistic test data generation
- Seed Scripts:
- User seed script (admin + regular users)
- Product seed script (with categories)
- Category seed script
- Development Convenience: Quick database population for development
- CORS Configuration: Cross-origin resource sharing setup
- HTTP Exception Handling: Centralized exception filtering
- Response Standardization: Consistent API response format
- Input Validation: Class-validator based DTO validation
- Error Handling: Global error handling with descriptive messages
- Middleware: Request logging and authentication middleware
- Non-Whitelisted Field Rejection: Strict request payload validation
- RESTful API design with clear endpoint structure
- GraphQL support via Apollo Server
- Request/Response standardization
- Comprehensive error messages
The application follows a modular, layered architecture:
┌─────────────────────────────────────┐
│ REST API / GraphQL Layer │
├─────────────────────────────────────┤
│ Controllers & Routes │
├─────────────────────────────────────┤
│ Services & Business Logic │
├─────────────────────────────────────┤
│ Data Access Layer (Repositories) │
├─────────────────────────────────────┤
│ MongoDB / Mongoose Models │
├─────────────────────────────────────┤
│ External Services: Stripe, Resend │
│ Cloudinary, Socket.IO │
└─────────────────────────────────────┘
Design Patterns Used:
- Repository Pattern: Abstracted database access
- Dependency Injection: NestJS built-in DI system
- Module Pattern: Feature-based module organization
- Guard & Interceptor Pattern: Cross-cutting concerns (auth, logging, error handling)
- DTO Pattern: Type-safe request/response validation
Before you begin, ensure you have the following installed:
- Node.js 18.0.0 or higher
- npm 8.0.0 or higher (or yarn/pnpm)
- MongoDB instance (Atlas, Docker, or self-hosted)
- Git for version control
-
Clone the repository
git clone <repository-url> africa-store-backend cd africa-store-backend
-
Install dependencies
npm install
-
Create environment configuration
cp .env.example .env # Edit .env with your configuration (see Environment Setup below) -
Start the development server
npm run start:dev
The API will be available at:
http://localhost:3000 -
(Optional) Seed the database with sample data
npm run seed
Check if the server is running:
curl http://localhost:3000/healthExpected response:
{
"status": "ok",
"timestamp": "2026-02-13T10:30:00Z"
}Create a .env file in the root directory with the following variables:
# ============================================
# Application Configuration
# ============================================
NODE_ENV=development
PORT=3000
API_BASE_URL=http://localhost:3000
# ============================================
# Database Configuration
# ============================================
MONGODB_URI=mongodb+srv://username:[email protected]/africa_store?retryWrites=true&w=majority
# ============================================
# JWT Authentication
# ============================================
TOKEN_SECRET=your_super_secret_jwt_key_change_this_in_production
TOKEN_EXPIRES_IN=1h
REFRESH_TOKEN_SECRET=your_super_secret_refresh_token_key
REFRESH_TOKEN_EXPIRES_IN=7d
# ============================================
# Cloudinary (File Upload)
# ============================================
CLOUD_NAME=your_cloudinary_cloud_name
CLOUD_API_KEY=your_cloudinary_api_key
CLOUD_API_SECRET=your_cloudinary_api_secret
CLOUD_ROOT_FOLDER=africa-store
# ============================================
# Email Configuration - Resend
# ============================================
RESEND_API_KEY=re_your_resend_api_key
RESEND_FROM=[email protected]
# ============================================
# Email Configuration - Brevo (Sendinblue)
# ============================================
BREVO_API_KEY=your_brevo_api_key
MAIL_FROM=[email protected]
# ============================================
# Stripe Payment Processing
# ============================================
STRIPE_SECRET_KEY=sk_test_your_test_secret_key
STRIPE_PUBLIC_KEY=pk_test_your_test_public_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
# ============================================
# Redis Cache (Optional)
# ============================================
REDIS_URL=redis://localhost:6379/0
REDIS_TTL=3600
# ============================================
# OTP Configuration
# ============================================
OTP_EXPIRY_TIME=10m
OTP_LENGTH=6| Variable | Purpose | Example |
|---|---|---|
| NODE_ENV | Application environment | development, production |
| PORT | Server port | 3000 |
| MONGODB_URI | MongoDB connection string | MongoDB Atlas or local instance |
| TOKEN_SECRET | JWT signing secret (access token) | Use a strong random string |
| TOKEN_EXPIRES_IN | Access token expiration | 1h, 24h |
| CLOUD_NAME | Cloudinary account name | Find in Cloudinary dashboard |
| CLOUD_API_KEY/SECRET | Cloudinary credentials | Cloudinary dashboard |
| RESEND_API_KEY | Resend email service key | Resend dashboard |
| STRIPE_SECRET_KEY | Stripe secret key | Stripe test/live keys |
| STRIPE_WEBHOOK_SECRET | Stripe webhook signing secret | From Stripe webhook settings |
MongoDB Atlas:
- Visit https://www.mongodb.com/cloud/atlas
- Create a free cluster
- Get connection string from "Connect" button
Cloudinary:
- Visit https://cloudinary.com (free tier available)
- Sign up and navigate to dashboard
- Copy Cloud Name, API Key, and API Secret
Stripe:
- Visit https://stripe.com
- Create account and navigate to API Keys
- Use test keys for development
Resend:
- Visit https://resend.com (free tier available)
- Create account and generate API key
- Verify sender email domain
africa-store-backend/
│
├── src/
│ ├── main.ts # Application entry point
│ ├── app.module.ts # Root module
│ ├── app.controller.ts # Root controller
│ ├── app.service.ts # Root service
│ │
│ ├── common/ # Shared utilities & cross-cutting concerns
│ │ ├── constants/
│ │ │ └── constants.ts # Application constants
│ │ ├── decorators/ # Custom decorators
│ │ │ ├── auth/ # Auth-related decorators
│ │ │ └── validation/ # Validation decorators
│ │ ├── exceptions/
│ │ │ └── validation.exception.ts # Custom validation exceptions
│ │ ├── filters/ # Exception filters
│ │ │ ├── all-exceptions.filter.ts # Global exception handler
│ │ │ └── httpexception.filter.ts # HTTP exception handler
│ │ ├── guards/ # Authentication & Authorization
│ │ │ ├── authentication.guard.ts # JWT verification guard
│ │ │ └── authorization.guard.ts # Role-based access control
│ │ ├── interceptors/ # Request/response processing
│ │ │ ├── error-handler.interceptor.ts # Error handling
│ │ │ └── success-response.interceptor.ts # Response standardization
│ │ ├── middlewares/
│ │ │ └── logger.middleware.ts # Request logging middleware
│ │ ├── pipes/
│ │ │ └── objectid-validation.pipe.ts # MongoDB ObjectId validation
│ │ ├── security/
│ │ │ └── hash.util.ts # Password hashing utilities
│ │ ├── services/ # External service integrations
│ │ │ ├── fileupload/ # Cloudinary integration
│ │ │ └── payment/ # Stripe integration
│ │ ├── types/
│ │ │ └── image.type.ts # Type definitions
│ │ └── utils/
│ │ └── validation.mapper.ts # Validation error mapping
│ │
│ ├── db/ # Database layer
│ │ ├── enums/ # Enumeration types
│ │ │ ├── token.enum.ts # Token-related enums
│ │ │ └── user.enum.ts # User-related enums
│ │ ├── models/ # Mongoose schemas & models
│ │ │ ├── user.model.ts # User schema
│ │ │ ├── product.model.ts # Product schema
│ │ │ ├── category.model.ts # Category schema
│ │ │ ├── cart.model.ts # Shopping cart schema
│ │ │ ├── order.model.ts # Order schema
│ │ │ ├── coupon.model.ts # Coupon/discount schema
│ │ │ ├── token.model.ts # Token blacklist schema
│ │ │ ├── otp.model.ts # OTP storage schema
│ │ │ └── home.model.ts # Homepage content schema
│ │ └── repos/ # Repository layer (data access)
│ │ ├── abstract.repository.ts # Base repository class
│ │ ├── user.repository.ts # User repository
│ │ ├── product.repository.ts # Product repository
│ │ ├── category.repository.ts # Category repository
│ │ ├── cart.repository.ts # Cart repository
│ │ ├── order.repository.ts # Order repository
│ │ ├── coupon.repository.ts # Coupon repository
│ │ ├── token.repository.ts # Token repository
│ │ ├── otp.repository.ts # OTP repository
│ │ └── home.repository.ts # Homepage repository
│ │
│ ├── modules/ # Feature modules
│ │ ├── auth/ # Authentication module
│ │ │ ├── auth.service.ts # Auth business logic
│ │ │ ├── auth.controller.ts # Auth endpoints
│ │ │ ├── auth.module.ts # Auth module definition
│ │ │ └── dto/ # Auth DTOs (login, register, etc.)
│ │ │
│ │ ├── user/ # User management module
│ │ │ ├── user.service.ts # User business logic
│ │ │ ├── user.controller.ts # User endpoints
│ │ │ ├── user.module.ts # User module definition
│ │ │ └── dto/ # User DTOs
│ │ │
│ │ ├── product/ # Product catalog module
│ │ │ ├── product.service.ts # Product business logic
│ │ │ ├── product.controller.ts # Product endpoints
│ │ │ ├── product.module.ts # Product module definition
│ │ │ └── dto/ # Product DTOs
│ │ │
│ │ ├── category/ # Category management module
│ │ │ ├── category.service.ts # Category business logic
│ │ │ ├── category.controller.ts # Category endpoints
│ │ │ ├── category.module.ts # Category module definition
│ │ │ └── dto/ # Category DTOs
│ │ │
│ │ ├── cart/ # Shopping cart module
│ │ │ ├── cart.service.ts # Cart business logic
│ │ │ ├── cart.controller.ts # Cart endpoints
│ │ │ ├── cart.module.ts # Cart module definition
│ │ │ └── dto/ # Cart DTOs
│ │ │
│ │ ├── order/ # Order processing module
│ │ │ ├── order.service.ts # Order business logic
│ │ │ ├── order.controller.ts # Order endpoints
│ │ │ ├── order.module.ts # Order module definition
│ │ │ └── dto/ # Order DTOs
│ │ │
│ │ ├── coupon/ # Coupon & discount module
│ │ │ ├── coupon.service.ts # Coupon business logic
│ │ │ ├── coupon.controller.ts # Coupon endpoints
│ │ │ ├── coupon.module.ts # Coupon module definition
│ │ │ └── dto/ # Coupon DTOs
│ │ │
│ │ ├── mail/ # Email sending module
│ │ │ ├── mail.service.ts # Mail business logic
│ │ │ ├── mail.controller.ts # Mail endpoints
│ │ │ └── mail.module.ts # Mail module definition
│ │ │
│ │ ├── mailer/ # Email provider configuration
│ │ │ ├── mailer.module.ts # Base mailer setup
│ │ │ ├── resend-mail.module.ts # Resend provider config
│ │ │ └── ... # Other email providers
│ │ │
│ │ ├── home/ # Homepage content module
│ │ │ ├── home.service.ts # Home business logic
│ │ │ ├── home.controller.ts # Home endpoints
│ │ │ ├── home.module.ts # Home module definition
│ │ │ └── dto/ # Home DTOs
│ │ │
│ │ ├── socket/ # WebSocket/Socket.IO module
│ │ │ └── ... # Real-time features
│ │ │
│ │ └── test/ # Testing module
│ │ └── schema.gql # GraphQL schema
│ │
│ ├── seeds/ # Data seeding scripts
│ │ ├── seed.ts # Main seed script entry
│ │ ├── seed-users.ts # User data seeding
│ │ ├── seed-categories.ts # Category data seeding
│ │ ├── seed-products.ts # Product data seeding
│ │ └── generators/ # Faker-based data generators
│ │
│ └── templates/ # Email templates
│ └── otp.hbs # Handlebars email templates
│
├── test/ # End-to-end tests
│ ├── app.e2e-spec.ts # E2E test suite
│ └── jest-e2e.json # Jest E2E configuration
│
├── dist/ # Compiled output (generated)
├── node_modules/ # Dependencies
│
├── .env.example # Environment variables template
├── .gitignore # Git ignore rules
├── Dockerfile # Docker containerization
├── docker-compose.yml # Docker compose (if available)
├── eslint.config.mjs # ESLint configuration
├── nest-cli.json # NestJS CLI configuration
├── package.json # Dependencies & scripts
├── package-lock.json # Dependency lock file
├── tsconfig.json # TypeScript configuration
├── tsconfig.build.json # TypeScript build configuration
└── README.md # This file
Handles user authentication and token management.
Endpoints:
POST /auth/register- Register new user with OTPPOST /auth/verify-otp- Verify OTP and create accountPOST /auth/login- Login and get JWT tokensPOST /auth/refresh- Refresh access tokenPOST /auth/logout- Logout and invalidate tokensPOST /auth/forgot-password- Initiate password resetPOST /auth/reset-password- Reset password with OTP
Key Features:
- OTP-based secure registration
- Dual JWT token system
- Automatic token refresh mechanism
- Secure password handling
Manages user profiles and account settings.
Endpoints:
GET /users/:id- Get user detailsPUT /users/:id- Update user profileGET /users- List all users (admin only)DELETE /users/:id- Delete user account
Key Features:
- User profile management
- Role tracking (admin/user)
- User metadata storage
Manages product catalog and inventory.
Endpoints:
GET /products- List products with filters, search, paginationGET /products/:id- Get product detailsPOST /products- Create new product (admin)PUT /products/:id- Update product (admin)DELETE /products/:id- Delete product (admin)GET /products/search- Search products by name/descriptionPUT /products/:id/stock- Update product stock levels
Key Features:
- Full-text search capabilities
- Stock level tracking
- Price and discount management
- Image management via Cloudinary
- Product status (active/inactive)
- Filtering by category, price range, etc.
Manages product categories.
Endpoints:
GET /categories- List all categoriesGET /categories/:id- Get category detailsPOST /categories- Create category (admin)PUT /categories/:id- Update category (admin)DELETE /categories/:id- Delete category (admin)GET /categories/:id/products- Get products in category
Key Features:
- Hierarchical category support
- Product association
- Category-based filtering
Manages shopping carts and cart items.
Endpoints:
GET /carts/:id- Get cart contentsPOST /carts/:id/items- Add item to cartPUT /carts/:id/items/:itemId- Update item quantityDELETE /carts/:id/items/:itemId- Remove item from cartDELETE /carts/:id- Clear cartGET /carts/:id/total- Get cart total with taxes/discounts
Key Features:
- Real-time price calculations
- Coupon application
- Tax calculation
- Cart persistence
Manages order processing and fulfillment.
Endpoints:
GET /orders- List user ordersGET /orders/:id- Get order detailsPOST /orders- Create new orderPUT /orders/:id/status- Update order status (admin)POST /orders/webhook/stripe- Stripe payment webhookGET /orders/:id/invoice- Download order invoice
Key Features:
- Order lifecycle management
- Status tracking (pending, processing, shipped, delivered)
- Payment status integration
- Invoice generation
Manages discount coupon system.
Endpoints:
GET /coupons- List active couponsPOST /coupons- Create coupon (admin)PUT /coupons/:id- Update coupon (admin)DELETE /coupons/:id- Delete coupon (admin)POST /coupons/:code/validate- Validate coupon code
Key Features:
- Percentage and fixed-amount discounts
- Usage limits and expiration dates
- Code-based validation
- Usage tracking
Handles email notifications.
Endpoints:
POST /mail/send- Send email (admin)POST /mail/send-bulk- Send bulk emails (admin)
Automatic Emails Sent:
- OTP registration emails
- Order confirmation emails
- Payment receipt emails
- Password reset emails
- Shipment tracking updates
Manages homepage content and featured items.
Endpoints:
GET /home- Get homepage configurationPUT /home- Update homepage (admin)GET /home/featured-products- Get featured productsPOST /home/featured-products- Add featured product (admin)
All models are defined using Mongoose with TypeScript support.
{
email: string (unique)
firstName: string
lastName: string
passwordHash: string (bcrypt hashed)
role: 'user' | 'admin'
isEmailVerified: boolean
profilePicture?: string (Cloudinary URL)
phoneNumber?: string
address?: object
createdAt: Date
updatedAt: Date
lastLogin?: Date
}{
name: string
description: string
slug: string (URL-friendly)
sku: string (unique)
price: number
comparePrice?: number (original price)
discount?: number (percentage)
images: string[] (Cloudinary URLs)
thumbnail: string
category: ObjectId (reference to Category)
stock: number
isActive: boolean
rating?: number
reviews?: object[]
metadata?: object (custom fields)
createdAt: Date
updatedAt: Date
}{
name: string
slug: string (unique)
description?: string
image?: string (Cloudinary URL)
isActive: boolean
parentCategory?: ObjectId (for hierarchical structure)
createdAt: Date
updatedAt: Date
}{
orderNumber: string (unique)
user: ObjectId (reference to User)
items: object[] (product references with quantities)
subtotal: number
tax: number
discountAmount: number
appliedCoupon?: ObjectId (reference to Coupon)
total: number
status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled'
paymentStatus: 'pending' | 'succeeded' | 'failed'
paymentMethod: 'stripe' | 'cash'
stripeSessionId?: string
shippingAddress: object
trackingNumber?: string
notes?: string
createdAt: Date
updatedAt: Date
}{
user: ObjectId (reference to User)
items: object[] (product references with quantities)
subtotal: number
tax: number
discount: number
appliedCoupon?: ObjectId (reference to Coupon)
total: number
expiresAt: Date
createdAt: Date
updatedAt: Date
}{
code: string (unique, uppercase)
description?: string
discountType: 'percentage' | 'fixed'
discountValue: number
minPurchaseAmount?: number
maxUsageCount?: number
currentUsageCount: number
usedBy: ObjectId[] (references to Users)
expiryDate: Date
isActive: boolean
createdAt: Date
updatedAt: Date
}1. User registers/logs in
2. Server generates:
- Access Token (short-lived, 1h default)
- Refresh Token (long-lived, 7d default)
3. Client stores tokens
4. For protected routes:
- Client sends access token in Authorization header
- Server validates token signature & expiration
5. When access token expires:
- Client uses refresh token to get new access token
- Server validates refresh token in database
1. User initiates action (register, reset password)
2. Server generates 6-digit OTP
3. Email sent via Resend/Brevo
4. User enters OTP in app
5. Server validates OTP (must match & not expired)
6. Upon successful validation, action is completed
- CORS: Enabled for cross-origin requests
- HTTPS: Recommended for production
- Password Hashing: bcrypt with 10 salt rounds
- Rate Limiting: Recommended via API gateway
- Input Validation: Class-validator on all DTOs
- SQL/NoSQL Injection Prevention: Mongoose schema validation
All file uploads are handled through Cloudinary cloud storage.
- Client uploads file
- Server validates file type & size
- File sent to Cloudinary
- Cloudinary returns secure URL
- URL stored in MongoDB
- CDN URL returned to client
- Images: JPG, PNG, GIF, WebP
- Max Size: 10MB (configurable)
africa-store/
├── products/
│ ├── images/
│ └── thumbnails/
├── users/
│ └── profiles/
└── documents/
└── invoices/
Checkout Flow:
- User clicks "Proceed to Payment"
- Server creates Stripe Checkout Session
- Server returns session ID to client
- Client redirects to Stripe Checkout
- User enters payment details
- Stripe processes transaction
Webhook Handling:
- Stripe sends webhook event to
/order/webhook - Server verifies webhook signature
- Order status updated based on payment result
- Invoice and confirmation email sent
- Inventory updated
Supported Payment Methods:
- Credit/Debit Cards (Visa, Mastercard, Amex)
- Digital Wallets (Apple Pay, Google Pay)
- Bank Transfers (region-specific)
Resend (Recommended)
- Modern email delivery
- Great deliverability rates
- Free tier available
- Real-time email logs
Brevo (Sendinblue)
- Traditional email marketing
- Higher volume support
- SMTP integration available
- Free tier with limited sends
All emails use Handlebars templating engine for dynamic content.
Available Templates:
otp.hbs- OTP verification emailsorder-confirmation.hbs- Order confirmationspayment-receipt.hbs- Payment receiptspassword-reset.hbs- Password reset linkswelcome.hbs- Welcome emails
Client → Server:
// Real-time notifications
socket.on('order:trackingUpdate', (data) => {})
// Live product updates
socket.on('product:viewed', (productId) => {})Server → Client:
// Broadcast product stock update
io.emit('product:stocked', { productId, newStock })
// Order status update
socket.emit('order:statusChanged', { orderId, status })
// System announcements
io.emit('announcement:broadcast', { message })# Unit tests
npm run test
# Unit tests with coverage
npm run test:cov
# E2E tests
npm run test:e2e
# Tests in watch mode
npm run test:watch
# Debug tests
npm run test:debug- Unit Tests:
*.spec.tsfiles alongside source code - E2E Tests: Located in
/testdirectory - Configuration:
jest.config.jsandjest-e2e.json
Generate coverage report:
npm run test:covReport location: coverage/ directory
docker build -t africa-store-backend:latest .docker run \
-e MONGODB_URI="your_mongodb_uri" \
-e STRIPE_SECRET_KEY="your_stripe_key" \
-e PORT=3000 \
-p 3000:3000 \
africa-store-backend:latestdocker-compose up -ddocker logs -f container_id# Development
npm run start # Start server (production)
npm run start:dev # Start with hot reload
npm run start:debug # Start with debugger
# Building
npm run build # Compile TypeScript to JavaScript
# Code Quality
npm run lint # Run ESLint
npm run format # Format code with Prettier
# Database
npm run seed # Seed database with sample data
npm run mongo:cli # Connect to MongoDB CLI
# Testing
npm run test # Run unit tests
npm run test:e2e # Run E2E tests
npm run test:cov # Generate coverage report- ESLint: Enforces code standards
- Prettier: Code formatting
- TypeScript: Type safety
# Fix all linting issues
npm run lint
# Format all files
npm run formatDevelopment mode includes automatic restart on file changes:
npm run start:devIssue 1: MongoDB Connection Error
Error: connect ECONNREFUSED
Solution:
- Verify
MONGODB_URIin.env - Ensure MongoDB instance is running
- Check network/firewall settings
Issue 2: Stripe Webhook Not Working
Error: Invalid signature from Stripe
Solution:
- Verify
STRIPE_WEBHOOK_SECRETmatches Stripe dashboard - Ensure webhook endpoint is publicly accessible
- Check webhook signing in Stripe settings
Issue 3: Cloudinary Upload Fails
Error: Cloudinary authentication failed
Solution:
- Verify
CLOUD_NAME,CLOUD_API_KEY,CLOUD_API_SECRET - Check Cloudinary account is active
- Verify API key permissions
Issue 4: Email Not Sending
Error: Email service unavailable
Solution:
- Verify
RESEND_API_KEYorBREVO_API_KEY - Check sender email is verified
- Verify email template exists
- Check spam folder
Issue 5: Port Already in Use
Error: EADDRINUSE: address already in use :::3000
Solution:
# Find process using port
netstat -ano | findstr :3000 # Windows
lsof -i :3000 # Mac/Linux
# Kill process (Windows)
taskkill /PID <PID> /F
# Change PORT in .env
PORT=3001Start server with debugging enabled:
npm run start:debugOpen Chrome DevTools or VS Code debugger:
- VS Code: Press F5 or go to Debug menu
Check application logs:
# If deployed on cloud
docker logs -f container_id
# Local development
# Check terminal output- Fork the repository
- Create a feature branch
git checkout -b feature/awesome-feature
- Make your changes
- Test your changes
npm run test npm run lint - Commit with clear messages
git commit -m "feat: add awesome feature" - Push to your fork
git push origin feature/awesome-feature
- Create a Pull Request
- Follow existing code style
- Write meaningful commit messages
- Add tests for new features
- Update documentation
- Keep PRs focused and small
- Never commit
.envor secrets
When reporting issues, please include:
- Clear description of the problem
- Steps to reproduce
- Expected vs. actual behavior
- Environment details (OS, Node version, etc.)
- Relevant error messages or logs
© 2026 Africa Store. All rights reserved.
This repository is currently marked as UNLICENSED in package.json. Please review and update the license when publishing this project.
Recommended Licenses:
- MIT: Permissive, widely used
- Apache 2.0: Patent protection included
- UNLICENSED: Proprietary (current)
For support:
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues tab
- 💬 Discussions: GitHub Discussions
Built with ❤️ using:
- NestJS - Progressive Node.js framework
- MongoDB - NoSQL database
- Stripe - Payment processing
- Cloudinary - Image management
- Resend - Email delivery
Last Updated: February 13, 2026 Version: 0.0.1