Backend API
Overview
The Backend API (backend.siyahfy.com) is the central Node.js/Express server that powers every Siyahfy application. It handles vendor authentication, product management, order processing, payment integrations, storefront APIs, theme management, and more. All frontend apps — Dashboard, Editor, Studio, Marketing Site, and Storefront themes — communicate with this single backend.
Runtime: Node.js with Express Database: PostgreSQL Cache: Redis File Storage: Backblaze B2 / Cloudflare R2
Tech Stack
| Technology | Version | Purpose |
|---|---|---|
| Express | 4.x | HTTP server framework |
| PostgreSQL (pg) | 8.x | Primary database |
| Redis | 5.x | Caching and session store |
| JSON Web Token | 9.x | Authentication tokens |
| Multer | 1.4 | File upload handling |
| Nodemailer | 6.x | Transactional emails |
| Razorpay SDK | 2.x | Payment processing |
| Cashfree SDK | 4.x | Alternate payment processing |
| AWS SDK (S3) | 3.x | Object storage (R2 compatible) |
| Backblaze B2 | 1.x | File storage |
| Sharp | 0.34 | Image processing & optimization |
| node-cron | 3.x | Scheduled tasks |
| Firebase Admin | 13.x | Push notifications |
| PDFKit / pdf-lib | — | Invoice & document generation |
| Swagger UI | 5.x | API documentation |
| bcrypt | 5.x | Password hashing |
| slugify | 1.x | URL slug generation |
Folder Structure
backend.siyahfy.com/
├── index.js # Express app setup, middleware, route mounting
├── config/
│ ├── index.js # PostgreSQL pool + auto-migration runner
│ ├── redis.js # Redis client setup
│ ├── b2-config.js # Backblaze B2 configuration
│ └── r2-config.js # Cloudflare R2 configuration
├── middleware/
│ ├── index.js # authorizeVendor (JWT + API key auth)
│ └── user.js # authorizeCustomer (storefront user auth)
├── routes/ # Express route handlers (80+ files)
│ ├── admin.js # Admin authentication & management
│ ├── vendors.js # Vendor CRUD
│ ├── products.js # Product management
│ ├── orders.js # Order processing
│ ├── customer.js # Customer management
│ ├── collections.js # Collection management
│ ├── discount.js # Discount engine
│ ├── theme.js # Theme management
│ ├── theme-editor.js # Theme editor API
│ ├── theme-marketplace.js # Theme marketplace
│ ├── developer.js # Developer/Studio APIs
│ ├── studio-auth.js # Studio authentication
│ ├── plans/ # Subscription plan logic
│ ├── razorpay/ # Payment webhooks
│ ├── apis/ # Storefront client APIs (V1)
│ ├── template-v2-routes/ # Storefront APIs (V2)
│ ├── app_template_routes/ # Mobile app APIs
│ ├── marketing/ # Marketing automation
│ └── connect_store/ # External platform connectors
├── controller/
│ └── webhook-razorpay.js # Razorpay webhook handler
├── database/ # Database schemas & reference SQL
│ ├── cms.sql # Core CMS schema
│ ├── affiliate_system.sql # Affiliate tables
│ └── 2fa_migration.sql # Two-factor auth tables
├── migrations/ # Auto-run SQL migrations
│ ├── add-custom-fonts.sql
│ ├── create-theme-tables.sql
│ ├── developer-apps.sql
│ ├── developer-earnings.sql
│ ├── inventory-system-v2.sql
│ └── ... (20+ migration files)
├── lib/ # Shared utilities
│ ├── firebaseAdmin.js # Firebase push notifications
│ ├── generate-token-pair.js # JWT token generation
│ ├── inventoryService.js # Inventory management logic
│ ├── sendNotification.js # Notification dispatcher
│ ├── whatsappMessages.js # WhatsApp message templates
│ ├── amazon-utils.js # Amazon marketplace helpers
│ └── stockAlert.js # Low stock alerts
├── scripts/ # Maintenance & utility scripts
├── html/ # Email HTML templates
├── export/ # Generated export files
├── upload/ # Temporary upload directory
├── store_data/ # Store data snapshots
├── theme_json/ # Theme configuration JSONs
└── docs/ # Internal documentationMiddleware Chain
Requests pass through the following middleware stack in order:
Request
│
├─ express.json({ limit: '20mb' }) ── Body parsing (20MB limit)
│
├─ cors() ── CORS with *.siyahfy.com allowlist
│
├─ Rate Limiters
│ ├─ authLimiter (login routes) ── 5 requests / 15 minutes
│ ├─ storefrontLimiter (/storefront) ── 2000 requests / minute
│ └─ generalLimiter (/api/*) ── 500 requests / minute
│
├─ Route-level middleware
│ ├─ authorizeVendor ── JWT/API-key auth for vendor routes
│ └─ authorizeCustomer ── JWT auth for storefront user routes
│
└─ Route HandlerVendor Authorization (middleware/index.js)
Extracts a Bearer token from the Authorization header. If the token is longer than 20 characters, it is treated as a JWT and verified against the secret. Otherwise, it is treated as a raw API key. The middleware then looks up the stores table to resolve store_slug, vendor_id, and store_name, attaching them to req.
Customer Authorization (middleware/user.js)
Reads the Authorization-Customer header (or fallback Authorization), verifies the JWT using process.env.SECRET_KEY, and attaches req.userId for downstream route handlers.
Route Mounting
All routes are mounted under the /api prefix. Below is an overview of the major route groups:
Admin & Vendor Management
| Route File | Mount Point | Purpose |
|---|---|---|
admin.js | /api | Admin login, dashboard data |
vendors.js | /api | Vendor CRUD operations |
vendor-store.js | /api | Store creation & settings |
vendor-access.js | /api | Staff access & permissions |
userRoles.js | /api | Role management |
globalSettings.js | /api | Platform-wide settings |
Product & Catalog
| Route File | Mount Point | Purpose |
|---|---|---|
products.js | /api | Product CRUD, variants, images |
category.js | /api | Category management |
subcategory.js | /api | Subcategory management |
collections.js | /api | Manual & automated collections |
catalog.js | /api | Product catalog exports |
attributes.js | /api | Product attributes & options |
inventory.js | /api | Inventory tracking & alerts |
product_metafield.js | /api | Custom product metafields |
bulkupload.js | /api | CSV/Excel bulk import |
shopifyBulkUpload.js | /api | Shopify product import |
Orders & Fulfillment
| Route File | Mount Point | Purpose |
|---|---|---|
orders.js | /api | Order listing & management |
draftorder.js | /api | Draft order creation |
refund.js | /api | Refund processing |
return.js | /api | Return management |
cancel.js | /api | Order cancellation |
pdfcreation.js | /api | Invoice PDF generation |
abandon_checkouts.js | /api | Abandoned cart recovery |
Payments
| Route File | Mount Point | Purpose |
|---|---|---|
payment-methods.js | /api | Payment gateway configuration |
razorpay/ | /api/razorpay | Razorpay integration & webhooks |
plans/ | /api | Subscription plan management |
app-credits.js | /api | App credit system |
Storefront APIs
| Route File | Mount Point | Purpose |
|---|---|---|
apis/product.js | /api | Public product endpoints |
apis/usercart.js | /api | Cart management |
apis/checkout.js | /api | Checkout flow |
apis/customerapis.js | /api | Customer auth & profile |
apis/collections.js | /api | Public collection endpoints |
apis/order.js | /api | Customer order history |
apis/wishlist.js | /api | Wishlist management |
template-v2-routes/ | /api/v2 | V2 storefront APIs |
app_template_routes/ | /api/app | Mobile app APIs |
Theme & Editor
| Route File | Mount Point | Purpose |
|---|---|---|
theme.js | /api | Theme assignment & settings |
theme-editor.js | /api | Theme editor save/load |
theme-marketplace.js | /api | Theme marketplace listing |
studio-auth.js | /api | Developer Studio authentication |
developer.js | /api | Theme development APIs |
developer-earnings.js | /api/developer | Developer payout tracking |
Content & Marketing
| Route File | Mount Point | Purpose |
|---|---|---|
blogs.js | /api | Blog post management |
pages.js | /api | Custom page management |
banner.js / banner-v2.js | /api | Banner management |
marketing/ | /api | Email & WhatsApp campaigns |
home_layout.js | /api | Homepage section layout |
Database Connection
PostgreSQL is configured through a connection pool in config/index.js:
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});Migration System
Siyahfy uses a file-based auto-migration system that runs on every server startup:
- A
_migrationstracking table records which.sqlfiles have been executed - On boot, the system scans the
migrations/directory for.sqlfiles - Any file not yet in
_migrationsis executed and logged - Migrations run in alphabetical filename order
-- migrations/_migrations tracking table
CREATE TABLE IF NOT EXISTS _migrations (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) UNIQUE NOT NULL,
executed_at TIMESTAMP DEFAULT NOW()
);To add a new migration, place a .sql file in migrations/ — it will run automatically on the next server restart.
Redis Cache
Redis is used for caching frequently accessed data:
// config/redis.js
const client = redis.createClient({
url: isProd ? 'redis://redis:6379' : 'redis://127.0.0.1:6379',
});Common use cases include caching product listings, store configurations, and rate-limiting counters.
File Upload Handling
File uploads are handled by Multer with storage backends:
- Backblaze B2 — Legacy file storage
- Cloudflare R2 — Primary storage (S3-compatible)
- Local
/upload— Temporary staging directory
The global error handler catches Multer-specific errors (file size limits, unexpected fields, invalid types) and returns structured error responses.
Error Handling
The backend includes a comprehensive global error handler at the bottom of index.js that catches:
| Error Type | HTTP Code | Response |
|---|---|---|
MulterError (file too large, wrong field) | 400 | Descriptive file upload error |
| Invalid file type | 400 | File type rejection message |
| Request body too large | 413 | Payload size exceeded |
Timeout (ETIMEDOUT) | 503 | Request timed out |
| Invalid JSON | 400 | Parse error message |
| Unhandled errors | 500 | Generic internal error |
Cron Jobs
The backend uses node-cron for scheduled tasks, managed through routes/cronJob.js. Tasks include abandoned checkout reminders (WhatsApp messages), subscription renewal checks, and inventory low-stock alerts.
API Documentation
Swagger UI is available at /api-docs and is auto-generated using swagger-autogen during development.
Environment Variables
| Variable | Description |
|---|---|
PORT | Server port (default: 3003) |
DB_USER / DB_HOST / DB_DATABASE / DB_PASSWORD / DB_PORT | PostgreSQL connection |
SECRET_KEY | JWT secret for customer tokens |
NODE_ENV | production or development |
B2_APPLICATION_KEY_ID / B2_APPLICATION_KEY | Backblaze B2 credentials |
R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY / R2_ENDPOINT | Cloudflare R2 credentials |
RAZORPAY_KEY_ID / RAZORPAY_KEY_SECRET | Razorpay payment credentials |
CASHFREE_APP_ID / CASHFREE_SECRET_KEY | Cashfree payment credentials |
FIREBASE_* | Firebase Admin SDK configuration |
SMTP_HOST / SMTP_USER / SMTP_PASS | Email sending configuration |