Skip to Content
Apps & ServicesBackend API

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

TechnologyVersionPurpose
Express4.xHTTP server framework
PostgreSQL (pg)8.xPrimary database
Redis5.xCaching and session store
JSON Web Token9.xAuthentication tokens
Multer1.4File upload handling
Nodemailer6.xTransactional emails
Razorpay SDK2.xPayment processing
Cashfree SDK4.xAlternate payment processing
AWS SDK (S3)3.xObject storage (R2 compatible)
Backblaze B21.xFile storage
Sharp0.34Image processing & optimization
node-cron3.xScheduled tasks
Firebase Admin13.xPush notifications
PDFKit / pdf-libInvoice & document generation
Swagger UI5.xAPI documentation
bcrypt5.xPassword hashing
slugify1.xURL 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 documentation

Middleware 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 Handler

Vendor 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 FileMount PointPurpose
admin.js/apiAdmin login, dashboard data
vendors.js/apiVendor CRUD operations
vendor-store.js/apiStore creation & settings
vendor-access.js/apiStaff access & permissions
userRoles.js/apiRole management
globalSettings.js/apiPlatform-wide settings

Product & Catalog

Route FileMount PointPurpose
products.js/apiProduct CRUD, variants, images
category.js/apiCategory management
subcategory.js/apiSubcategory management
collections.js/apiManual & automated collections
catalog.js/apiProduct catalog exports
attributes.js/apiProduct attributes & options
inventory.js/apiInventory tracking & alerts
product_metafield.js/apiCustom product metafields
bulkupload.js/apiCSV/Excel bulk import
shopifyBulkUpload.js/apiShopify product import

Orders & Fulfillment

Route FileMount PointPurpose
orders.js/apiOrder listing & management
draftorder.js/apiDraft order creation
refund.js/apiRefund processing
return.js/apiReturn management
cancel.js/apiOrder cancellation
pdfcreation.js/apiInvoice PDF generation
abandon_checkouts.js/apiAbandoned cart recovery

Payments

Route FileMount PointPurpose
payment-methods.js/apiPayment gateway configuration
razorpay//api/razorpayRazorpay integration & webhooks
plans//apiSubscription plan management
app-credits.js/apiApp credit system

Storefront APIs

Route FileMount PointPurpose
apis/product.js/apiPublic product endpoints
apis/usercart.js/apiCart management
apis/checkout.js/apiCheckout flow
apis/customerapis.js/apiCustomer auth & profile
apis/collections.js/apiPublic collection endpoints
apis/order.js/apiCustomer order history
apis/wishlist.js/apiWishlist management
template-v2-routes//api/v2V2 storefront APIs
app_template_routes//api/appMobile app APIs

Theme & Editor

Route FileMount PointPurpose
theme.js/apiTheme assignment & settings
theme-editor.js/apiTheme editor save/load
theme-marketplace.js/apiTheme marketplace listing
studio-auth.js/apiDeveloper Studio authentication
developer.js/apiTheme development APIs
developer-earnings.js/api/developerDeveloper payout tracking

Content & Marketing

Route FileMount PointPurpose
blogs.js/apiBlog post management
pages.js/apiCustom page management
banner.js / banner-v2.js/apiBanner management
marketing//apiEmail & WhatsApp campaigns
home_layout.js/apiHomepage 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:

  1. A _migrations tracking table records which .sql files have been executed
  2. On boot, the system scans the migrations/ directory for .sql files
  3. Any file not yet in _migrations is executed and logged
  4. 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 TypeHTTP CodeResponse
MulterError (file too large, wrong field)400Descriptive file upload error
Invalid file type400File type rejection message
Request body too large413Payload size exceeded
Timeout (ETIMEDOUT)503Request timed out
Invalid JSON400Parse error message
Unhandled errors500Generic 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

VariableDescription
PORTServer port (default: 3003)
DB_USER / DB_HOST / DB_DATABASE / DB_PASSWORD / DB_PORTPostgreSQL connection
SECRET_KEYJWT secret for customer tokens
NODE_ENVproduction or development
B2_APPLICATION_KEY_ID / B2_APPLICATION_KEYBackblaze B2 credentials
R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY / R2_ENDPOINTCloudflare R2 credentials
RAZORPAY_KEY_ID / RAZORPAY_KEY_SECRETRazorpay payment credentials
CASHFREE_APP_ID / CASHFREE_SECRET_KEYCashfree payment credentials
FIREBASE_*Firebase Admin SDK configuration
SMTP_HOST / SMTP_USER / SMTP_PASSEmail sending configuration