Skip to content

Repository files navigation

🚀 SaaSify – Enterprise Domain & Hosting Management Platform

A full-featured MERN-stack SaaS platform for domain registration, web hosting, and automated billing – inspired by WHMCS.

Node.jsMongoDBReactLicense: MITStatusCode Coverage

📌 Personal Project – Building a production-grade SaaS platform to master full-stack development, system design, and real-world challenges in payment processing, domain management, and background job scheduling.


📊 Current Progress

Development Status

  • Phase 1 (Complete): Core authentication, security, and user management
  • Phase 2 (Complete): Domain management & GoDaddy API integration
  • Phase 3 (Complete): Payment processing (Razorpay, Stripe) & billing automation
  • Phase 4 (Complete): React frontend with responsive UI
  • 🔄 Phase 5 (In Progress): Performance optimization & analytics dashboard
  • 📋 Phase 6 (Upcoming): White-label solution & advanced reporting

What's Being Built This Week

  • API response caching layer (Redis optimization)
  • Advanced analytics dashboard with real-time metrics
  • Payment reconciliation system
  • Email template redesign
  • Mobile app (React Native) planning

🏗️ Architecture & Design Decisions

Why This Stack?

DecisionReasoningTrade-offs
MongoDBFlexible schema for evolving business requirements (invoices, orders, services)Less suitable for complex joins; needed denormalization strategy
Redis + BullMQReliable background job processing with retry logic; essential for domain renewals & paymentsAdded complexity; required monitoring for queue health
JWT + Refresh TokensStateless auth scales better; refresh tokens reduce exposureMust manage token rotation & blacklisting
Express + Modular RoutesClear separation of concerns (auth, domains, payments modules); easier to testRequires discipline to maintain folder structure
React + ZustandSimple state management vs Redux complexity; Zustand is lightweightLimited for highly complex state trees

Key Architectural Patterns Used

  • Modular Architecture – Each feature (auth, domains, payments) is self-contained
  • Repository Pattern – Data access layer (Mongoose models) separated from business logic
  • Service Layer – Business logic in services (email, payment, domain services)
  • Queue-Worker Pattern – Background jobs via BullMQ for async operations
  • Middleware Pipeline – Express middleware for auth, validation, rate limiting, error handling
  • Factory Pattern – Payment gateway selection (Razorpay vs Stripe) at runtime

Why BullMQ Over Simple Queues?

Challenge: Domain registrations sometimes fail; need retry mechanism
Solution: BullMQ provides:
✅ Automatic retries with exponential backoff
✅ Persistent job storage in Redis
✅ Dead-letter queues for failed jobs
✅ Job progress tracking
✅ Webhook reliability for payment callbacks

🎯 Key Technical Decisions & Learnings

1. Payment Gateway Integration (Most Complex)

Challenge: How to support multiple payment gateways (Razorpay & Stripe) without duplicating code?

Solution Implemented:

// Abstract payment interfaceclassPaymentGateway{createOrder(){}verifyPayment(){}handleWebhook(){}}classRazorpayServiceextendsPaymentGateway{}classStripeServiceextendsPaymentGateway{}// Factory pattern for selectionconstgetPaymentService=(gateway)=>gateway==='razorpay' ? newRazorpayService() : newStripeService();

What I Learned:

  • Webhook security is critical (signature verification)
  • Idempotency keys prevent duplicate payments
  • Payment reconciliation is complex (payment vs invoice reconciliation)

2. Domain Auto-Renewal (Background Job Optimization)

Challenge: Check 50,000+ domains daily for renewal. How to avoid timeout & database overload?

Solution Implemented:

• Cron job at 2 AM UTC (low traffic time)
• Batch processing: Process 1000 domains per batch
• Use pagination with cursor (not skip/limit)
• Update only domains within 30 days of expiry
• Log metrics: processed/failed/renewed counts

Result: Reduced job time from 15 mins → 80 seconds

What I Learned:

  • Database indexing is critical (created index on expiryDate)
  • Batch processing prevents memory spikes
  • Cursor pagination > skip/limit for large datasets

3. Rate Limiting Strategy

Challenge: Prevent abuse on domain search endpoint (expensive GoDaddy API calls)

Solution:

• User-based rate limiting: 10 searches/hour
• IP-based limiting: 100 requests/15 mins
• Redis-backed rate limiter (fast, distributed-ready)
• Different limits for authenticated vs public

What I Learned:

  • Rate limiting must be multi-layered
  • Sliding window vs fixed window algorithms matter
  • Redis is essential for distributed rate limiting

4. DNS Record Management (AWS Route53 Integration)

Challenge: User creates DNS record, but also needs to manage it in Route53. How to keep them in sync?

Solution:

  • Primary source: MongoDB (user-facing)
  • Secondary: Route53 (actual DNS)
  • Sync job runs every hour
  • Conflict resolution: MongoDB wins (allows local changes)

What I Learned:

  • DNS propagation isn't instant
  • Need health checks for DNS records
  • Eventual consistency is acceptable here

5. Invoice PDF Generation

Challenge: Generate 100+ invoices/day. Direct PDF generation is slow.

Solution:

  • Queue-based PDF generation (BullMQ)
  • Template caching (Handlebars)
  • S3 storage for PDFs
  • Email trigger after generation

Performance: From 2 seconds/invoice → 200ms


🔒 Security Implementation

Authentication Flow

User Login → JWT (15m expiry) + Refresh Token (7d)
↓
Rate limiting: 5 attempts/minute
↓
2FA verification (optional but recommended)
↓
Session stored in Redis (allows logout anywhere)
↓
Refresh token rotation on each use

Data Protection

  • Passwords: Bcrypt (10 rounds salt)
  • Sensitive Data: AES-256-GCM encryption (API keys, payment tokens)
  • CORS: Whitelist specific origins, block in production
  • Helmet.js: Security headers (CSP, X-Frame-Options, etc.)
  • Input Validation: Joi schemas on all endpoints
  • SQL Injection: None (using Mongoose ODM)

Third-Party Integrations

  • GoDaddy API key: Encrypted in database
  • Razorpay/Stripe keys: Environment variables only, never logged
  • Webhook secrets: Verified via HMAC-SHA256 signature

⚡ Performance Optimizations

Current Metrics

MetricTargetAchieved
API Response Time<200ms✅ 120ms avg
Domain Search<500ms✅ 350ms avg
Invoice Generation<2s✅ 200ms (queued)
Dashboard Load<1s✅ 600ms
Database QueriesN/A✅ Indexed

Optimizations Implemented

  1. Database Indexing

    • Compound indexes on frequently queried fields
    • TTL index on verification tokens (auto-cleanup)
    • Text index on domain names
  2. Redis Caching

    • TLD pricing: Cached 1 hour
    • User profile: Cached 30 minutes
    • Domain availability: Cached 5 minutes
  3. Frontend Optimizations

    • Lazy loading routes with React.lazy()
    • Image optimization with Vite
    • CSS purging via Tailwind
    • Production build: ~85KB (gzipped)
  4. Backend Query Optimization

    • Lean queries (select only needed fields)
    • Pagination with cursor
    • Batch operations where possible
    • Connection pooling (MongoDB min: 2, max: 10)

🧪 Testing Strategy

What's Tested

  • Unit Tests: Services, utilities, helpers
  • Integration Tests: API endpoints with mocked external APIs
  • E2E Tests: Critical user flows (registration, domain search, payment)
  • Security Tests: Rate limiting, JWT validation, CORS

Test Coverage

Backend: 85% coverage
- Services: 95%
- Middleware: 90%
- Utils: 100%
- Controllers: 75%

Running Tests

npm test# Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Generate coverage report

Known Issues & Solutions

IssueImpactStatusSolution
Domain renewal sometimes fails silently🔴 High🔄 In ProgressImplementing retry mechanism with Slack notifications
GoDaddy API rate limiting🟡 Medium✅ SolvedCache domain availability for 5 mins
Webhook timeout (Razorpay)🟡 Medium✅ SolvedQueue payment verification, immediate acknowledgment
MongoDB slow on large datasets🟡 Medium✅ SolvedPagination + compound indexes
PDF generation memory leak🔴 High✅ SolvedStream-based PDF generation + worker pool

Monitoring & Debugging

  • ✅ Structured logging with Winston (JSON format for ELK stack)
  • ✅ Error tracking ready (can integrate Sentry)
  • ✅ Database query profiling enabled in development
  • ✅ BullMQ dashboard for job monitoring
  • ✅ Custom metrics: API latency, job success rate, payment success rate

💡 What I'm Learning & Still Improving

Current Learning Priorities

  1. Scaling: How to handle 100k+ concurrent users (caching strategies, load balancing)
  2. Distributed Systems: Multi-region deployment, eventual consistency
  3. Payment Systems: PCI compliance, recurring billing, tax calculations
  4. Analytics: Real-time dashboards, BigQuery integration for reporting
  5. DevOps: Kubernetes, CI/CD pipelines, infrastructure as code

Books/Resources I'm Studying

  • Designing Data-Intensive Applications (by Martin Kleppmann)
  • System Design Interview (by Alex Xu)
  • Production-Ready Microservices (by Susan Fowler)

✨ Features Breakdown


✨ Key Features

🔐 Authentication & Security

  • JWT Authentication with refresh token rotation
  • Role-Based Access Control (RBAC) – Admin & Client roles
  • Two-Factor Authentication (2FA) – TOTP-based security
  • Email Verification – Secure account creation
  • Password Reset – Token-based recovery
  • Rate Limiting – Brute force & DDoS protection
  • Account Suspension – Admin controls

🌐 Domain Management

  • Domain Search – Real-time availability checking across multiple TLDs
  • GoDaddy API Integration – Automated domain registration
  • Domain Transfer – Seamless domain migration with status tracking
  • DNS Management – Full control over A, AAAA, CNAME, MX, TXT, SRV records
  • Domain Contacts – Registrant, Admin, Tech, Billing contact management
  • Domain Security – Lock/Unlock, privacy protection options
  • Auto-Renewal – Automatic domain renewal before expiry
  • Expiry Tracking – Email notifications for upcoming renewals
  • Email Forwarding – Configure email forwarding rules

💳 Billing & Payments

  • Multi-Gateway Support – Razorpay (India) & Stripe (International)
  • Wallet System – Customer balance management
  • Invoice Management – Automated PDF generation & delivery
  • Payment Processing – Secure payment handling with validation
  • Invoice History – Complete transaction tracking
  • Payment Reminders – Automated email notifications (3 days before due)
  • Late Fees – Automatic calculation and application
  • Service Suspension – Automatic suspension after 7 days overdue
  • Service Termination – Automatic termination after 30 days suspended

🏠 Hosting Services

  • Dynamic Hosting – Managed cloud hosting with SSH/Database access
  • Static Hosting – AWS S3 + CloudFront CDN deployment
  • Infrastructure Management – EC2, RDS, Route53 integration
  • SSL Certificates – AWS ACM integration
  • Database Access – MySQL/MariaDB provisioning
  • SSH Access – Secure shell credentials
  • Service Status – Real-time instance monitoring

🤖 Automation & Background Jobs

  • Cron Jobs – Scheduled domain management tasks
  • Background Workers – BullMQ-powered job queue
  • Domain Expiry Monitoring – Daily checks (24-hour cycle)
  • Auto-Renewal Processing – Automatic renewal execution
  • Transfer Status Updates – Hourly status tracking
  • Email Notifications – Transactional email delivery
  • Service Lifecycle Management – Suspension & termination automation

📊 Admin Dashboard

  • User Management – View, edit, suspend users
  • Dashboard Stats – Revenue, MRR, active services overview
  • Audit Logs – Complete activity tracking
  • Client Credit Management – Add/deduct wallet balance
  • Invoice Management – Create & manage invoices
  • System Health – AWS & Database connection status

💰 Wallet & Transactions

  • Balance Management – Real-time wallet balance
  • Add Funds – Top-up via payment gateways
  • Pay Invoices – Direct wallet payment option
  • Transaction History – Complete transaction log
  • Admin Adjustments – Manual credit/debit operations

📱 User Interface

  • Responsive Design – Mobile-first approach
  • Dark/Light Mode Ready – Modern UI with Tailwind CSS
  • Real-time Updates – Instant feedback on actions
  • Dashboard – User overview & quick stats
  • Domain Management – Intuitive domain control panel
  • Invoice Portal – Download & track payments
  • User Settings – Profile management & preferences

🛠 Tech Stack

Frontend

TechnologyPurpose
React 19UI library
Vite 7Build tool & dev server
React Router 7Client-side routing
Tailwind CSS 4Utility-first styling
ZustandState management
AxiosHTTP client
React Hook FormForm management
ZodSchema validation
Lucide ReactIcon library
Date-fnsDate formatting
React Hot ToastToast notifications

Backend

TechnologyPurpose
Node.js 20+Runtime
Express 4Web framework
MongoDBPrimary database
MongooseODM for MongoDB
RedisCaching & sessions
BullMQJob queue system
JWTAuthentication tokens
BcryptPassword hashing
WinstonLogging
MorganHTTP request logger
JoiSchema validation
dotenvEnvironment variables

Integrations & Services

ServicePurpose
GoDaddy APIDomain registration & management
RazorpayPayment processing (India)
StripePayment processing (International)
SendGrid/NodemailerEmail delivery
AWS ServicesEC2, S3, RDS, Route53, CloudFront, ACM
SpeakeasyTwo-factor authentication (TOTP)

Dev Tools

ToolPurpose
JestUnit testing
SupertestAPI testing
ESLintCode linting
NodemonDev auto-reload
ConcurrentlyMulti-process management

📁 Folder Structure

Backend Structure

backend/
├── src/
│ ├── app.js # Express app configuration
│ ├── server.js # Server entry point
│ ├── config/
│ │ ├── database.js # MongoDB connection
│ │ ├── redis.js # Redis configuration
│ │ └── indexes.js # Database indexes
│ ├── constants/
│ │ └── enums.js # Shared enumerations
│ ├── middleware/
│ │ ├── auth.middleware.js # JWT verification
│ │ ├── errorHandler.middleware.js # Error handling
│ │ ├── rateLimit.middleware.js # Rate limiting
│ │ └── validation.middleware.js # Input validation
│ ├── models/
│ │ ├── User.js, Client.js, Domain.js
│ │ ├── Invoice.js, Transaction.js, Order.js
│ │ ├── Service.js, HostingService.js
│ │ ├── Infrastructure.js, Server.js
│ │ ├── Product.js, ActivityLog.js
│ │ └── ...
│ ├── modules/ # Feature modules
│ │ ├── auth/ # Authentication logic
│ │ ├── domains/ # Domain management
│ │ ├── hosting/ # Hosting services
│ │ ├── payments/ # Payment processing
│ │ ├── invoices/ # Invoice management
│ │ ├── wallet/ # Wallet operations
│ │ ├── clients/ # Client management
│ │ ├── cart/ # Shopping cart
│ │ ├── admin/ # Admin operations
│ │ └── aws/ # AWS integration
│ ├── services/
│ │ ├── email.service.js # Email delivery
│ │ ├── godaddy.service.js # Domain API
│ │ ├── razorpay.service.js # Razorpay payments
│ │ ├── stripe.service.js # Stripe payments
│ │ └── invoice.service.js # Invoice generation
│ ├── queues/
│ │ ├── domain.queue.js # Domain job queue
│ │ ├── hosting.queue.js # Hosting job queue
│ │ ├── dynamicHosting.queue.js
│ │ └── infra.queue.js # Infrastructure queue
│ ├── workers/ # Background job processors
│ │ ├── domainRegistration.worker.js
│ │ ├── domainRenewal.worker.js
│ │ ├── domainTransfer.worker.js
│ │ ├── infraProvision.worker.js
│ │ ├── emailNotification.worker.js
│ │ └── ...
│ ├── cron/ # Scheduled tasks
│ │ ├── domainExpiry.cron.js
│ │ ├── autoRenew.cron.js
│ │ ├── paymentReminders.cron.js
│ │ ├── serviceSuspension.cron.js
│ │ └── ...
│ ├── utils/
│ │ ├── logger.js # Logging utility
│ │ ├── response.js # Response formatting
│ │ ├── encryption.js # Data encryption
│ │ └── helpers.js # Helper functions
│ ├── templates/
│ │ └── emails/ # Email templates
│ └── constants/
│ └── enums.js # Shared enums
├── scripts/
│ ├── seed.js # Database seeding
│ ├── create-indexes.js # Create DB indexes
│ └── rebuild-indexes.js # Rebuild indexes
├── storage/
│ └── invoices/ # Invoice file storage
└── package.json

Frontend Structure

frontend/
├── src/
│ ├── App.jsx, main.jsx # App entry point
│ ├── config/
│ │ └── api.js # API configuration
│ ├── store/ # Zustand state store
│ ├── services/
│ │ ├── authService.js
│ │ ├── apiService.js
│ │ └── ...
│ ├── layouts/
│ │ ├── DashboardLayout.jsx
│ │ └── MainLayout.jsx
│ ├── pages/
│ │ ├── Home.jsx, Cart.jsx, Checkout.jsx
│ │ ├── DomainSearch.jsx
│ │ ├── auth/ # Auth pages
│ │ └── dashboard/ # Dashboard pages
│ ├── components/
│ │ ├── layout/ # Layout components
│ │ ├── common/ # Reusable components
│ │ ├── forms/ # Form components
│ │ └── ...
│ ├── assets/ # Images, icons
│ └── index.css, App.css
├── vite.config.js # Vite configuration
├── eslint.config.js # ESLint rules
└── package.json

⚙️ Installation & Setup

Prerequisites

  • Node.js 18.0.0 or higher
  • npm 9.0.0 or higher
  • MongoDB (local or Atlas cloud)
  • Redis (local or cloud instance)
  • Git

1. Clone the Repository

git clone https://github.com/yourusername/saasify.git
cd SaaSify

2. Install all Dependencies

npm run install:all

This installs dependencies for root, backend, and frontend.

3. Backend Setup

Navigate to the backend directory:

cd backend

Create a .env file:

cp .env.example .env

Configure your .env file with appropriate values (see Environment Variables section).

Create database indexes:

npm run db:indexes

(Optional) Seed sample data:

npm run db:seed

4. Frontend Setup

Navigate to the frontend directory:

cd frontend

Create a .env file:

cp .env.example .env

Configure your API URL in .env:

VITE_API_URL=http://localhost:5000/api
RAZORPAY_KEY_ID=your_razorpay_key_id

5. Run the Application

Option A: Development Mode (Full Stack)

From the root directory:

npm run dev

This starts both frontend and backend concurrently.

Option B: Development Mode (Full Stack + Workers + Cron)

npm run dev:full

Starts API, workers, cron jobs, and frontend.

Option C: Individual Services

Backend API:

cd backend
npm run dev

API runs on http://localhost:5000

Background Workers:

cd backend
npm run worker

Cron Jobs:

cd backend
npm run cron

Frontend:

cd frontend
npm run dev

Frontend runs on http://localhost:5173


🔐 Environment Variables

Backend (.env)

VariableDescriptionExample
Node Environment
NODE_ENVEnvironment (development/production)development
PORTAPI server port5000
Database
MONGO_URIMongoDB connection stringmongodb://localhost:27017/saasify
MONGO_MAX_POOL_SIZEMax connection pool size10
MONGO_MIN_POOL_SIZEMin connection pool size2
Redis
REDIS_HOSTRedis server hostlocalhost
REDIS_PORTRedis server port6379
REDIS_PASSWORDRedis password (if any)``
REDIS_DBRedis database number0
REDIS_TLSEnable TLS for Redisfalse
JWT Authentication
JWT_SECRETSecret key for JWT signingyour-super-secret-key
JWT_EXPIRES_INToken expiration time15m
JWT_REFRESH_SECRETRefresh token secretyour-refresh-secret
JWT_REFRESH_EXPIRES_INRefresh token expiration7d
Cookies
COOKIE_SECRETSession cookie secretyour-cookie-secret
SESSION_SECRETSession secretyour-session-secret
CORS
CORS_ORIGINAllowed origins (comma-separated)http://localhost:5173
Frontend
FRONTEND_URLFrontend application URLhttp://localhost:5173
Email Service
EMAIL_PROVIDEREmail provider (sendgrid/smtp)smtp
SMTP_HOSTSMTP server hostsmtp.gmail.com
SMTP_PORTSMTP server port587
SMTP_USERSMTP usernameyour-email@gmail.com
SMTP_PASSSMTP passwordyour-app-password
SMTP_SECUREUse TLS?false
SENDGRID_API_KEYSendGrid API keySG.xxxxx
EMAIL_FROMSender email addressnoreply@saasify.com
EMAIL_FROM_NAMESender display nameSaaSify Support
COMPANY_NAMEYour company nameSaaSify
SUPPORT_EMAILSupport emailsupport@saasify.com
GoDaddy API
GODADDY_API_KEYGoDaddy API keyyour-api-key
GODADDY_API_SECRETGoDaddy API secretyour-api-secret
GODADDY_ENVEnvironment (OTE/production)OTE
Razorpay
RAZORPAY_KEY_IDRazorpay Key IDrzp_test_xxxxx
RAZORPAY_KEY_SECRETRazorpay Key Secretyour_secret_key
RAZORPAY_WEBHOOK_SECRETRazorpay Webhook Secretyour_webhook_secret
Stripe
STRIPE_SECRET_KEYStripe Secret Keysk_test_xxxxx
STRIPE_PUBLISHABLE_KEYStripe Publishable Keypk_test_xxxxx
STRIPE_WEBHOOK_SECRETStripe Webhook Secretwhsec_xxxxx
AWS Services
AWS_REGIONAWS regionus-east-1
AWS_ACCESS_KEY_IDAWS access keyAKIAXXXXXXX
AWS_SECRET_ACCESS_KEYAWS secret keyxxxxxxxxxxxxx
Rate Limiting
RATE_LIMIT_WINDOW_MSRate limit window (ms)900000
RATE_LIMIT_MAX_REQUESTSMax requests per window100
RATE_LIMIT_DOMAIN_SEARCHDomain search limit10
Logging
LOG_LEVELLog level (info/debug/error)info
LOG_MAX_SIZEMax log file size10m
LOG_MAX_FILESLog retention7d
Encryption
ENCRYPTION_KEY32-byte hex key for AES-256-GCMyour-64-char-hex-string
ENCRYPTION_ALGORITHMEncryption algorithmaes-256-gcm
Admin Credentials
ADMIN_EMAILDefault admin emailadmin@saasify.com
ADMIN_PASSWORDDefault admin passwordAdmin@12345
2FA
TWO_FACTOR_APP_NAME2FA app name for TOTPSaaSify

Frontend (.env)

VariableDescriptionExample
VITE_API_URLBackend API URLhttp://localhost:5000/api
RAZORPAY_KEY_IDRazorpay Public Keyrzp_test_xxxxx

📡 API Documentation

Base URL

http://localhost:5000/api

Authentication

All authenticated endpoints require a Bearer token in the Authorization header:

Authorization: Bearer <jwt_token>

Response Format

{
"success": true,
"message": "Operation successful",
"data": {},
"statusCode": 200
}

Core API Endpoints

🔐 Authentication (/api/auth)

MethodEndpointDescriptionAuth
POST/registerUser registration
POST/loginUser login
POST/refresh-tokenRefresh JWT token
POST/logoutUser logout
POST/verify-emailVerify email address
POST/resend-verificationResend verification email
POST/forgot-passwordRequest password reset
POST/reset-passwordReset password via token
POST/enable-2faEnable two-factor authentication
POST/verify-2faVerify 2FA token
POST/disable-2faDisable 2FA

👤 Clients (/api/clients)

MethodEndpointDescriptionAuth
GET/meGet user profile
PATCH/meUpdate user profile
GET/me/walletGet wallet balance
POST/me/wallet/addAdd wallet funds
GET/me/activityGet activity logs

🌐 Domains (/api/domains)

MethodEndpointDescriptionAuth
GET/searchSearch domains⚠️ Optional
GET/availability/:domainCheck domain availability⚠️ Optional
GET/tldsGet supported TLDs
GET/pricing/:tldGet TLD pricing
POST/registerRegister a domain
GET/my-domainsList user's domains
GET/:idGet domain details
POST/transferInitiate domain transfer
POST/renew/:idRenew a domain
PUT/dns/:domainUpdate DNS records
GET/dns/:domainGet DNS records
DELETE/dns/:domain/:type/:nameDelete DNS record
PATCH/contacts/:domainUpdate domain contacts
POST/lock/:domainLock domain
PUT/forwarding/:domainSet email forwarding

💳 Payments (/api/payments)

MethodEndpointDescriptionAuth
POST/razorpay/create-orderCreate Razorpay order
POST/razorpay/verifyVerify Razorpay payment
POST/stripe/create-intentCreate Stripe payment intent
POST/stripe/verifyVerify Stripe payment
GET/transaction-historyGet payment history

🛒 Cart (/api/cart)

MethodEndpointDescriptionAuth
GET/Get cart items
POST/addAdd item to cart
PATCH/:itemIdUpdate cart item
DELETE/:itemIdRemove from cart
DELETE/clearClear entire cart
POST/couponApply coupon code
POST/checkoutProceed to checkout

📄 Invoices (/api/invoices)

MethodEndpointDescriptionAuth
GET/List invoices
GET/:idGet invoice details
GET/:id/pdfDownload invoice PDF
POST/:id/payPay invoice
GET/statsInvoice statistics

💰 Wallet (/api/wallet)

MethodEndpointDescriptionAuth
GET/balanceGet wallet balance
GET/transactionsGet transactions
POST/add-fundsAdd funds via payment
POST/pay-invoicePay invoice from wallet

🏠 Hosting (/api/hosting)

MethodEndpointDescriptionAuth
POST/dynamic/createCreate dynamic hosting
GET/dynamic/List hosting services
GET/dynamic/:idGet hosting details
GET/dynamic/:id/sshGet SSH credentials
GET/dynamic/:id/databaseGet database info
POST/static/createCreate static hosting
GET/static/List static sites
POST/dns/zonesCreate hosted zone
GET/dns/records/:domainIdGet DNS records
POST/dns/records/:domainIdCreate DNS record

👨‍💼 Admin (/api/admin)

MethodEndpointDescriptionAuth
GET/usersList all users✅ Admin
GET/users/:idGet user details✅ Admin
PATCH/users/:idUpdate user✅ Admin
DELETE/users/:idDelete user✅ Admin
POST/users/:id/suspendSuspend user✅ Admin
POST/clients/:id/creditAdd client credit✅ Admin
GET/audit-logsGet audit logs✅ Admin
GET/statsDashboard statistics✅ Admin

💡 Usage

1. Domain Search & Registration

Search for domains:

curl -X GET "http://localhost:5000/api/domains/search?query=example&extensions=com,net" \
-H "Authorization: Bearer YOUR_TOKEN"

Register a domain:

curl -X POST "http://localhost:5000/api/domains/register" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "domain": "example.com", "period": 1, "registrant": { "firstName": "John", "lastName": "Doe", "email": "john@example.com" } }'

2. Wallet Management

Check wallet balance:

curl -X GET "http://localhost:5000/api/wallet/balance" \
-H "Authorization: Bearer YOUR_TOKEN"

Add funds:

curl -X POST "http://localhost:5000/api/wallet/add-funds" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "amount": 100, "gateway": "razorpay" }'

3. Invoice Management

Get invoices:

curl -X GET "http://localhost:5000/api/invoices" \
-H "Authorization: Bearer YOUR_TOKEN"

Pay an invoice:

curl -X POST "http://localhost:5000/api/invoices/{invoiceId}/pay" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "method": "wallet" }'

4. DNS Management

Get DNS records:

curl -X GET "http://localhost:5000/api/hosting/dns/records/{domainId}" \
-H "Authorization: Bearer YOUR_TOKEN"

Add DNS record:

curl -X POST "http://localhost:5000/api/hosting/dns/records/{domainId}" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "name": "@", "type": "A", "value": "192.168.1.1", "ttl": 3600 }'

5. Admin Operations

Get dashboard stats:

curl -X GET "http://localhost:5000/api/admin/stats" \
-H "Authorization: Bearer ADMIN_TOKEN"

Suspend a user:

curl -X POST "http://localhost:5000/api/admin/users/{userId}/suspend" \
-H "Authorization: Bearer ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "reason": "Terms violation" }'

🧪 Testing

Unit Tests

cd backend
npm test

Watch Mode

npm run test:watch

Coverage Report

npm run test:coverage

API Testing with Postman

A Postman collection is provided:

  • Import SaaSify_API_Collection.postman_collection.json
  • Import SaaSify_Environment.postman_environment.json
  • Configure environment variables
  • Run requests against your API

🚀 Deployment

Prerequisites

  • Hosting provider (AWS, Heroku, DigitalOcean, etc.)
  • Environment variables properly configured
  • MongoDB Atlas or self-hosted MongoDB
  • Redis instance
  • Domain name

Deployment Steps

1. Backend Deployment

Build for Production:

cd backend
npm install
npm run build # If applicable

Environment Setup: Ensure all production .env variables are set:

NODE_ENV=production
PORT=5000
MONGO_URI=<production_mongodb_uri>
REDIS_HOST=<production_redis_host>
JWT_SECRET=<strong_random_key>
...

Database Setup:

npm run db:indexes # Create indexes

Start Server:

npm start

2. Frontend Deployment

Build for Production:

cd frontend
npm install
npm run build

Deploy Static Files:

  • Upload contents of dist/ folder to:
    • Netlify, Vercel, AWS S3 + CloudFront, or
    • Your web server's static directory

Environment Configuration:

VITE_API_URL=https://api.yourdomain.com
RAZORPAY_KEY_ID=your_production_key

3. Background Services

Deploy Workers (for domain registration, renewals, etc.):

cd backend
npm run worker

Deploy Cron Jobs (for scheduled tasks):

cd backend
npm run cron

4. Docker Deployment (Optional)

Create Backend Dockerfile:

FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 5000
CMD ["npm", "start"]

Create Frontend Dockerfile:

FROM node:20-alpine as builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Docker Compose:

version: '3.8'services:
mongodb:
image: mongo:7ports:
- "27017:27017"volumes:
- mongo_data:/data/dbredis:
image: redis:7-alpineports:
- "6379:6379"backend:
build: ./backendports:
- "5000:5000"environment:
MONGO_URI: mongodb://mongodb:27017/saasifyREDIS_HOST: redisdepends_on:
- mongodb
- redisfrontend:
build: ./frontendports:
- "80:80"depends_on:
- backendvolumes:
mongo_data:

Run with Docker:

docker-compose up -d

5. SSL/HTTPS Setup

Use Let's Encrypt:

# With Certbot
sudo certbot certonly --standalone -d yourdomain.com

🤝 Contributing

We welcome contributions! Here's how to get involved:

1. Fork the Repository

git clone https://github.com/yourusername/saasify.git
cd SaaSify
git checkout -b feature/your-feature-name

2. Create a Branch

git checkout -b feature/your-feature

3. Make Changes

  • Follow the existing code style
  • Write clean, maintainable code
  • Add comments for complex logic
  • Use meaningful commit messages

4. Test Your Changes

# Backend testscd backend && npm test# Manual testing
npm run dev:full

5. Commit & Push

git add .
git commit -m "Add feature: brief description"
git push origin feature/your-feature

6. Create a Pull Request

  • Describe changes clearly
  • Link related issues
  • Request review from maintainers

Code Style Guidelines

  • Naming: camelCase for variables/functions, PascalCase for classes/components
  • Comments: JSDoc for functions, inline comments for logic
  • Environment: Use .env.example as template
  • Error Handling: Try-catch blocks with proper logging
  • Validation: Joi schemas for API input validation

📸 Screenshots & Demos

Landing Page

  • Domain search hero section
  • Features showcase
  • Pricing display
  • Call-to-action buttons

User Dashboard

  • Domain overview widget
  • Recent activities
  • Wallet balance
  • Quick actions

Domain Management

  • List all owned domains
  • Domain details panel
  • DNS management interface
  • Renewal status tracking

Billing Interface

  • Invoice list with filters
  • Payment history
  • Wallet management
  • Payment gateway options

📜 License

This project is licensed under the MIT License – see the LICENSE file for details.

You are free to:

  • ✅ Use commercially
  • ✅ Modify the code
  • ✅ Distribute copies
  • ✅ Include in proprietary projects

With the only requirement:

  • ⚠️ Include license and copyright notice

🆘 Troubleshooting

MongoDB Connection Issues

# Check MongoDB is running
mongosh
# Verify connection stringecho$MONGO_URI

Redis Connection Issues

# Check Redis is running
redis-cli ping
# Should respond: PONG

Port Already in Use

# Find process using port
lsof -i :5000
# Kill processkill -9 <PID>

JWT Token Errors

Error: Invalid token
# Generate new encryption key:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# Update JWT_SECRET in .env

Email Not Sending

  • Verify SMTP credentials
  • Enable "Less secure apps" for Gmail
  • Use app-specific passwords
  • Check SendGrid API key if using SendGrid

Payment Gateway Issues

  • Verify API keys are correct
  • Check webhook secrets
  • Ensure test mode is enabled for development
  • Review payment gateway logs


🎯 Roadmap

v1.0 - Foundation (Completed ✅)

  • ✅ Core authentication & authorization
  • ✅ Domain search & registration
  • ✅ Payment processing (Razorpay, Stripe)
  • ✅ Invoice & billing system
  • ✅ Wallet functionality
  • ✅ Basic React frontend

v1.5 - Performance & Polish (In Progress 🔄)

  • 🔄 API response caching optimization
  • 🔄 Advanced analytics dashboard
  • 🔄 Payment reconciliation UI
  • 📋 Mobile app (React Native) - Q2 2026
  • 📋 Support ticket system - Q2 2026
  • 📋 Advanced reporting with CSV export - Q2 2026

v2.0 - Scale & Enterprise (Q3 2026)

  • Multi-currency support
  • White-label solution (custom branding)
  • Affiliate/reseller program
  • Recurring billing with subscriptions
  • Advanced security (IP whitelisting, API keys)
  • GraphQL API alternative
  • Kubernetes deployment ready

v3.0 - AI & Intelligence (Q4 2026)

  • ML-based pricing optimization
  • AI support chatbot
  • Automated domain suggestions
  • Predictive analytics dashboard
  • Smart renewal recommendations

🚀 Code Review Guide (For Interviewers)

Highlights to Review

For Backend Architecture:

  • 📁 backend/src/modules/ – Feature modules showing separation of concerns
  • 📄 backend/src/middleware/auth.middleware.js – JWT & 2FA implementation
  • 📄 backend/src/services/razorpay.service.js – Payment gateway abstraction
  • 📄 backend/src/workers/domainRenewal.worker.js – Background job complex logic
  • 📄 backend/src/cron/ – Scheduled job implementations with error handling

For Frontend Quality:

  • 📁 frontend/src/pages/ – Complex pages like Checkout showing form handling
  • 📄 frontend/src/services/authService.js – API integration & error handling patterns
  • 📁 frontend/src/components/ – Reusable component architecture with props drilling avoided
  • 🎨 Tailwind CSS – Mobile-first responsive design implementation

What Shows Developer Maturity:

  • Error Handling: Specific error messages, try-catch blocks, error logging
  • Logging Strategy: Winston with daily rotation, structured JSON logs
  • Input Validation: Joi schemas on all endpoints, frontend validation too
  • Code Organization: Modular structure, single responsibility, easy to test
  • Configuration Management: 12-factor app principles, environment variables
  • Security-First: Encryption, rate limiting, CORS, helmet.js headers

💬 Support & Community

  • Documentation: Check technicaldoc.md for technical details
  • Questions/Feedback: Open an issue on GitHub
  • Email:aryan@saasify.com

🙏 Acknowledgments

Built with passion for mastering full-stack development. Inspired by industry standards like WHMCS, but built from scratch to understand real-world SaaS challenges.

Technologies Used:

  • Express.js community & best practices
  • MongoDB & Mongoose documentation
  • AWS comprehensive cloud services
  • GoDaddy API documentation
  • React ecosystem & patterns

👨‍💻 About This Project

Why I Built This: This project is my deep dive into building production-grade systems. It's not just CRUD operations—it's about understanding:

  • How payment systems handle idempotency and reconciliation
  • Why background jobs need retry mechanisms and monitoring
  • How to design APIs that scale
  • Real security concerns (not just auth)
  • Performance optimization at scale
  • Automated testing and CI/CD

What I'm Most Proud Of:

  1. Payment gateway abstraction that supports multiple providers
  2. Robust background job system with retry logic
  3. Clean separation of concerns across modules
  4. Security-first implementations (encryption, rate limiting, input validation)
  5. Handling real-world problems (DNS sync issues, webhook reliability, etc.)

📧 Get in Touch

If you're interested in discussing this project, system design, or opportunities:


Currently Seeking: Full-Stack Developer roles / System Design discussions

Last Updated: March 2026
Active Development: Yes, still building and learning! 🚀


Feel free to star ⭐ if this project helped you learn something new!

About

SaaSify is an all-in-one SaaS management and billing platform that simplifies subscriptions, client management, and business automation—similar to WHMCS but built for modern scalability. It enables businesses to manage customers, automate recurring billing, handle secure payments, and streamline operations from a single dashboard.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages