https://sheo-mart.vercel.app/πGithub Repo Link!!
β https://github.com/riteshjat2004/SheoMart

SheoMart is an enterprise-grade, full-stack multi-vendor hyperlocal quick-commerce marketplace designed to connect local neighbourhood merchants with nearby customers. Engineered with a scalable micro-monorepo structure using Next.js 16 (App Router) and Express 5 (TypeScript), SheoMart provides real-time order dispatching, in-store Point-of-Sale (POS) counter billing, automated universal product catalog management, Cloudinary asset pipelines, and multi-tier role-based dashboards.
π Table of Contents
π Architectural Overview
SheoMart is crafted around the hyperlocal retail model:
- Geofenced Operations: Customers see verified stores and products delivering directly to their detected or selected pincode and GPS coordinates.
- Hybrid Commerce: Supports both online door-to-door delivery with time slots, customer in-store self-pickup, and merchant over-the-counter POS walk-in billing.
- Universal Catalog Engine: Eliminates redundant data entry across stores by maintaining an admin-curated universal master catalog with 1-click store cloning and deduplication.
- Resilient Security Pipeline: End-to-end defense-in-depth architecture adhering to OWASP recommendations with CSRF protection, strict Content-Type enforcement, NoSQL sanitization, rate limiting, and dual-token JWT rotation.
π System Architecture
Architecture & Workflow DiagramMermaid
Rendering system diagram... Interactive Vector DiagramUse zoom or expand to inspect nodes
β¨ Key Features
1. Customer Marketplace
- Hyperlocal Geocoding & Pincode Detection: Real-time pincode filter dynamically re-scopes stores, products, and estimated fulfillment times.
- Dynamic Homepage:
- Dynamic hero section with quick category navigation and local branding.
- Live Store Showcase & Pincode Filter: Seamlessly view stores serving your exact area.
- Real Customer Reviews & Testimonials: Displays verified customer feedback with ratings. Includes an interactive "See all reviews" modal with search, star filters, and verified badge indicators.
- Live Platform Metrics: Real-time counters showing registered stores, active catalog items, satisfied shoppers, and serviceable pincodes.
- SheoMart Story Section: Community-oriented narrative celebrating local commerce.
- Cart & Intelligent Checkout:
- Multi-item cart with store-level delivery rule validation (minimum order, free delivery thresholds, dynamic platform fee).
- Multi-address manager with geolocation mapping and tag selection (Home, Work, Other).
- Delivery time slot selector (Morning, Afternoon, Evening) or Self-Pickup option.
- Secure payments via Razorpay (UPI, Cards, NetBanking, Wallets) and Cash on Delivery (COD).
- Order Lifecycle & Tracking: Detailed order status tracking (
Placed β Confirmed β Preparing β Out for Delivery β Delivered).
- Support Desk & Live Chat: Built-in customer service ticketing system with live Socket.IO messaging and typing indicators.
2. Merchant & Store Owner Suite
- Interactive Merchant Dashboard: Live charts tracking daily revenue, weekly volume, top-selling SKUs, average order value, and order fulfillment ratios.
- Point of Sale (POS) & Counter Billing:
- Rapid counter sales billing interface designed for barcode scanners and keyboard shortcuts.
- Instant offline invoice creation with item lookup, custom tax, and discounts.
- Thermal receipt printing generator (80mm / 58mm POS formats).
- In-store pickup payment reconciler for online orders collected at the store.
- Universal Catalog Integration & Product Manager:
- Seamless product creation with rich attributes, MRP, selling price, units (kg, g, l, pcs), and stock tracking.
- Admin Universal Catalog Cloning: Browse master catalog items and clone directly into your store inventory with custom price and stock in one click, preventing duplicate entries.
- Store Branding & Settings:
- Direct Cloudinary Upload: Upload high-resolution store logo and banner covers directly from your local device to Cloudinary (
sheomart/store_assets).
- Direct Link Support: Preserves URL input for linking external images.
- Visual preview cards with instant remove/clear capability.
- Configure delivery radius (km), base delivery fee, free delivery threshold, and preparation times.
- Create and toggle customizable hourly delivery windows with capacity caps.
- Customer CRM & Plus Membership:
- Customer directory with lifetime spend, visit count, and order history.
- Grant VIP / Plus Membership privileges to loyal patrons.
- Executive Analytics: High-level platform GMV, commission margins, gross orders, active merchants, and registered users.
- Merchant Management & Verification:
- Review and approve new store vendor applications.
- Award verified trust badges:
Standard Store, Verified Store, and Royal Merchant.
- Suspend or activate stores in real-time.
- Universal Master Catalog:
- Curate and maintain platform-wide master product templates for quick merchant onboarding.
- Universal product deduplication engine.
- Financial & Platform Controls:
- Configure global platform convenience fees (flat or percentage-based).
- Global emergency Maintenance Mode switch that gracefully routes public traffic to maintenance notices while preserving admin access.
- Security & Audit Logs:
- Track admin actions, privilege escalations, and seller security requests.
- Secure seller and admin password reset management.
4. Real-Time Infrastructure
- Socket.IO Engine (
sheomart-backend/src/socket.ts):
- Room-based isolation:
join_store room for instant merchant order dispatching.
- Support ticket rooms:
join_ticket, leave_ticket, typing, stop_typing for real-time customer support chat.
- Auto-reconnect handling with JWT token synchronization.
- Cloudinary Integration: Cloud-hosted, high-performance image transformations with organized folder schemas (
sheomart/products, sheomart/stores, sheomart/categories).
- In-Memory Buffer Processing: Multer memory storage coupled with Sharp image optimization for fast, secure file handling without disk clutter.
- Magic Byte Validation: Validates actual binary file headers to block malicious file extension spoofing.
6. Security & Infrastructure Hardening
- Dual-Token JWT Authentication: Short-lived access tokens (15m) paired with long-lived rotating refresh tokens (7d) stored in secure HTTP-only cookies.
- Header Hardening via Helmet: Strict Content Security Policy (CSP), HTTP Strict Transport Security (HSTS 1 year with preload), Frameguard, and X-Content-Type-Options.
- Mozilla Observatory Optimizations: Dedicated
Permissions-Policy and X-Permitted-Cross-Domain-Policies headers.
- NoSQL Injection Guard: Deep recursive query sanitization stripping
$ and . operators from request bodies and query parameters.
- CSRF Protection & Enforced Content-Type: Strict request validation blocking forged cross-site payloads on mutating routes.
- Granular Rate Limiters: Dedicated rate limit thresholds for sensitive endpoints (
/search, /billing, /analytics, /auth).
π οΈ Tech Stack
Frontend
| Technology | Version | Purpose |
|---|
| Next.js | 16.2.9 | App Router, Server Components, Route Handlers |
| React | 19.2.4 | Core UI Component Library |
| TypeScript | 5.x | Strict Static Type Safety |
| Tailwind CSS | v4 | High-performance modern utility styling |
| TanStack React Query | 5.101.2 | Server-state caching, invalidation & sync |
| Zustand | 5.0.14 | Lightweight client state management (Auth, Cart, Geo) |
| Recharts | 3.10.1 | Analytics charts & telemetry dashboards |
| Socket.IO Client | 4.8.4 | Bi-directional real-time communication |
| Lucide React | 1.22.0 | Modern, consistent icon set |
| React Hook Form + Zod | 7.80.0 / 4.4.3 | Form management and runtime schema validation |
Backend
| Technology | Version | Purpose |
|---|
| Node.js | 20+ | Server Runtime Environment |
| Express.js | 5.2.1 | REST API Routing Framework |
| TypeScript | 6.0.3 | Backend Type Safety & Tooling |
| MongoDB & Mongoose | 9.7.3 | NoSQL Database & Schema Modeling |
| Socket.IO | 4.8.4 | Real-time WebSocket Gateway |
| Cloudinary SDK | 2.10.1 | Cloud asset upload & CDN delivery |
| Sharp | 0.35.3 | High-performance image conversion & optimization |
| Razorpay SDK | 2.9.6 | Payment orders & cryptographic webhook verification |
| Nodemailer | 10.0.8 | Transactional emails & verification workflows |
| Helmet & HPP | 8.2.0 / 0.2.3 | Security headers & parameter pollution prevention |
| express-rate-limit | 8.5.2 | Endpoint rate limiting & DDoS mitigation |
π Project Structure
SheoMart/
βββ sheomart-frontend/ # Next.js 16 Client Application
β βββ public/ # Static assets, branding, icons
β βββ src/
β β βββ app/ # App Router page routes
β β β βββ (auth)/ # Login, Register, Forgot Password
β β β βββ admin/ # Platform Admin control panel
β β β β βββ analytics/ # Platform metrics & GMV
β β β β βββ products/ # Universal catalog manager
β β β β βββ stores/ # Store approval & verification
β β β β βββ security/ # Security audit logs
β β β β βββ settings/ # Global platform fees & maintenance
β β β βββ cart/ # Shopping cart
β β β βββ checkout/ # Address selection & payment
β β β βββ orders/ # Customer order tracking
β β β βββ store/ # Merchant portal
β β β β βββ analytics/ # Merchant performance charts
β β β β βββ billing/ # POS terminal & receipt printer
β β β β βββ inventory/ # Stock levels & alerts
β β β β βββ orders/ # Live order queue
β β β β βββ products/ # Store catalog & catalog cloning
β β β β βββ settings/ # Cloudinary logo/banner & slots
β β β βββ stores/ # Public store directory
β β β βββ support/ # Real-time customer support chat
β β βββ components/ # Reusable UI components & layouts
β β βββ hooks/ # Custom React hooks
β β βββ lib/ # Socket client, formatters, utilities
β β βββ services/ # Axios API integration layer
β β βββ store/ # Zustand stores (auth, cart, location)
β β βββ types/ # TypeScript shared interfaces
β βββ package.json
β
βββ sheomart-backend/ # Express 5 REST & WebSocket Server
β βββ src/
β β βββ config/ # Database, Cloudinary, Razorpay, Env
β β βββ constants/ # Roles, status codes, folders
β β βββ controllers/ # Route business controllers
β β βββ errors/ # AppError & standard error handlers
β β βββ middleware/ # Auth, RBAC, Rate-limit, Sanitize, Upload
β β βββ models/ # Mongoose schemas (User, Store, Product, Order...)
β β βββ routes/ # Express modular route definitions
β β βββ scripts/ # Database seeders (seedAdmin.ts)
β β βββ services/ # Reusable business logic services
β β βββ types/ # Backend TypeScript typings
β β βββ utils/ # Password hashing, tokens, API response
β β βββ validators/ # Zod request payload schemas
β β βββ app.ts # Express application configuration
β β βββ server.ts # Server entrypoint & HTTP listener
β β βββ socket.ts # Socket.IO event handler initialization
β βββ package.json
β
βββ README.md # Project documentation
π Getting Started
Prerequisites
Ensure you have the following installed on your local machine:
- Node.js:
v20.0.0 or higher
- npm:
v10.0.0 or higher
- MongoDB: A running local instance or a MongoDB Atlas connection string
- Cloudinary Account: For image asset management
- Razorpay Account (Test Mode): For payment processing
Backend Setup
-
Navigate to the backend directory:
cd sheomart-backend
-
Install dependencies:
npm install
-
Configure environment variables:
Copy the example environment file and fill in your credentials:
cp .env.example .env
-
Seed the initial Platform Admin user:
Make sure MONGODB_URI and SEED_ADMIN_* variables are configured in .env, then run:
npm run seed
-
Start the backend development server:
npm run dev
The backend API will run at http://localhost:5000.
Frontend Setup
-
Navigate to the frontend directory:
cd ../sheomart-frontend
-
Install dependencies:
npm install
-
Configure environment variables:
Copy the example environment file:
cp .env.example .env.local
-
Start the Next.js development server:
npm run dev
Open http://localhost:3000 in your browser.
π Environment Variables
Backend (sheomart-backend/.env)
| Variable | Description | Example |
|---|
PORT | Backend server port | 5000 |
NODE_ENV | Application environment | development / production |
MONGODB_URI | MongoDB connection connection string | mongodb://localhost:27017/sheomart |
JWT_ACCESS_SECRET | Secret for short-lived access tokens | your_access_jwt_secret |
JWT_REFRESH_SECRET | Secret for rotating refresh tokens | your_refresh_jwt_secret |
JWT_ACCESS_EXPIRES_IN | Access token lifespan | 15m |
JWT_REFRESH_EXPIRES_IN | Refresh token lifespan | 7d |
CORS_ORIGIN | Allowed client origin for CORS | http://localhost:3000 |
FRONTEND_URL | Frontend client application URL | http://localhost:3000 |
CLOUDINARY_CLOUD_NAME | Cloudinary cloud account name | your_cloudinary_name |
CLOUDINARY_API_KEY | Cloudinary API Key | your_cloudinary_key |
CLOUDINARY_API_SECRET | Cloudinary API Secret | your_cloudinary_secret |
RAZORPAY_KEY_ID | Razorpay Key ID | rzp_test_... |
RAZORPAY_KEY_SECRET | Razorpay Key Secret | your_razorpay_secret |
SMTP_HOST | Mail server host | smtp.gmail.com |
SMTP_PORT | Mail server port | 587 |
SMTP_USER | Mail server username | your-email@gmail.com |
SMTP_PASSWORD | Mail server app password | your_app_password |
SMTP_FROM | Outgoing email address sender header | "SheoMart" <no-reply@sheomart.com> |
SEED_ADMIN_NAME | Initial administrator name for seeding | Platform Admin |
SEED_ADMIN_EMAIL | Initial administrator email for seeding | admin@sheomart.com |
SEED_ADMIN_MOBILE | Initial administrator phone for seeding | 9876543210 |
SEED_ADMIN_PASSWORD | Initial administrator password for seeding | Admin@12345 |
Frontend (sheomart-frontend/.env.local)
| Variable | Description | Example |
|---|
NEXT_PUBLIC_API_URL | Base URL of SheoMart Express backend | http://localhost:5000 |
NEXT_PUBLIC_RAZORPAY_KEY_ID | Public Razorpay Key ID for client checkout | rzp_test_... |
π‘ API Reference
All REST endpoints are prefixed with /api/v1 (with public health checks available at / and /health).
Authentication & Identity
POST /api/v1/auth/register β Register a customer account
POST /api/v1/auth/login β Login with credentials (receives access & refresh tokens)
POST /api/v1/auth/refresh β Rotate and obtain fresh access token
POST /api/v1/auth/logout β Invalidate session and clear auth cookies
GET /api/v1/auth/me β Fetch currently authenticated user profile
Stores & Merchant Management
GET /api/v1/stores β Query stores with optional pincode, city, and state filters
GET /api/v1/stores/:storeId β Retrieve single store details
POST /api/v1/stores β Submit vendor / store application
GET /api/v1/stores/me β Retrieve logged-in merchant's store details
PATCH /api/v1/stores/me β Update store metadata, delivery fees, radius, slots
POST /api/v1/stores/me/upload-asset β Upload store logo or banner cover to Cloudinary
GET /api/v1/stores/admin β Fetch all stores (Platform Admin)
PATCH /api/v1/stores/:storeId/status β Approve, suspend, or activate a store
PATCH /api/v1/stores/:storeId/badge β Update verification badge (normal, verified, royal)
Products & Universal Catalog
GET /api/v1/products β Browse products with search, category, and store filters
GET /api/v1/products/:productId β Get full product details
POST /api/v1/products β Create a new product (with optional image upload)
PATCH /api/v1/products/:productId β Update product details, pricing, and stock
DELETE /api/v1/products/:productId β Remove product from store
POST /api/v1/products/admin/clone-to-store β Clone products from Admin Master Catalog to a store
Point of Sale (POS) & In-Store Billing
POST /api/v1/billing/invoices β Create offline walk-in POS invoice
GET /api/v1/billing/invoices β List store billing invoices
GET /api/v1/billing/invoices/:invoiceId β Retrieve single invoice details
POST /api/v1/billing/invoices/:invoiceId/confirm-payment β Confirm offline payment
POST /api/v1/billing/pickup/:orderId/complete β Reconcile & mark store pickup order as paid
GET /api/v1/billing/customers β Get store customer directory & loyalty stats
Cart, Orders & Payments
GET /api/v1/cart β Retrieve customer cart
POST /api/v1/cart β Add or modify cart items
DELETE /api/v1/cart/:itemId β Remove item from cart
POST /api/v1/orders β Create new order
GET /api/v1/orders β List user's orders
GET /api/v1/orders/:orderId β View order details & status
PATCH /api/v1/orders/:orderId/status β Merchant order status transition
POST /api/v1/payments/razorpay/create-order β Initialize Razorpay checkout order
POST /api/v1/payments/razorpay/verify β Verify Razorpay payment signature
Reviews & Homepage
GET /api/v1/products/:productId/reviews β Fetch reviews for a specific product
POST /api/v1/products/:productId/reviews β Submit verified customer review
GET /api/v1/home/reviews β Fetch high-rating verified reviews for landing page
GET /api/v1/home/stats β Fetch real-time aggregate marketplace stats
β‘ WebSocket Events
SheoMart uses Socket.IO for low-latency live operations:
| Event Name | Direction | Payload | Description |
|---|
join_store | Client β Server | storeId: string | Merchant joins store room for live order events |
leave_store | Client β Server | storeId: string | Merchant leaves store room |
join_ticket | Client β Server | ticketId: string | Join support ticket room for live messaging |
leave_ticket | Client β Server | ticketId: string | Leave support ticket room |
typing | Client β Server | { ticketId, userName } | Broadcast typing indicator to ticket room |
stop_typing | Client β Server | { ticketId } | Broadcast stop typing indicator |
π Available Scripts
Backend (sheomart-backend)
npm run dev
npm run build
npm run start
npm run seed
npm run lint
npm run format
Frontend (sheomart-frontend)
npm run dev
npm run build
npm run start
npm run lint
Built with β€οΈ for local commerce and modern hyperlocal retail ecosystems.
An architectural breakdown of every technology, library, and framework powering SheoMart. This guide explains what each tool does, why we selected it, what alternatives exist, and the strategic advantages & trade-offs that made it the optimal choice for a high-performance hyperlocal multi-vendor grocery platform.
π Table of Contents
π― Executive Architectural Strategy
SheoMart combines three core personas into one unified ecosystem:
- Customers: Requiring sub-second mobile page loads, dynamic geo-fencing (pincode filtering), instant cart mutations, and live order tracking.
- Store Merchants: Requiring low-latency counter Point of Sale (POS), real-time live order dispatching, instant thermal billing, and catalog cloning.
- Platform Administrators: Requiring deep telemetry charts, live store verification, maintenance mode controls, and universal master catalog management.
To satisfy these distinct requirements without massive microservice overhead, we selected a Modular Micro-Monorepo pairing a Next.js 16 Client with an Express 5 (TypeScript) Backend.
π» Frontend Stack Breakdown
1. Next.js 16 (App Router)
| Attribute | Details |
|---|
| Role in SheoMart | Foundation framework powering SSR (Server-Side Rendering), SSG, client routing, layout hierarchies, and metadata optimization. |
| Used In | Marketplace landing page, SEO-critical product & store listings, merchant dashboard, admin portal. |
Why We Used It
- Hybrid Rendering Model: Marketplace storefronts need SEO and fast First Contentful Paint (FCP) via Server Rendering, while merchant dashboards need fast client interactivity via client components. Next.js 16 allows fine-grained
"use client" and Server Component boundaries.
- Nested Layouts & Route Groups: Distinct dashboard layouts for
/store (merchant sidebar), /admin (admin control bar), and /(marketplace) (customer navigation) without re-rendering common chrome.
- Image & Font Optimization: Automated WebP/AVIF generation and Zero-Layout-Shift Google Fonts loading.
Alternatives Considered
- Vite + React SPA: Faster local build times, but zero SEO out-of-the-box. Generating dynamic metadata for individual stores and products requires complex pre-rendering setups.
- Remix (React Router 7): Excellent data loading, but smaller ecosystem for production e-commerce plugins and hosting options compared to Vercel/Next.js.
Advantages & Trade-Offs
- β
Pros: Built-in code-splitting per route, automatic image optimization, nested layouts, production-grade routing.
- β οΈ Trade-off: App Router paradigm has a steeper learning curve than simple SPAs, requiring discipline around client vs. server boundaries.
2. React 19
| Attribute | Details |
|---|
| Role in SheoMart | Core component runtime and view layer. |
| Used In | Entire UI component tree across all portals. |
Why We Used It
- Modern Concurrent Engine: Smooth UI rendering when rapidly typing in search boxes or filtering store catalogs.
- Universal Ecosystem: Standardized component libraries, custom hook ecosystems, and tooling.
Alternatives Considered
- Vue 3: Simpler reactivity, but smaller enterprise component ecosystem for complex multi-vendor admin interfaces.
- Svelte 5: Minimal bundle size, but smaller typing and chart/component ecosystem.
3. TypeScript (Frontend)
| Attribute | Details |
|---|
| Role in SheoMart | Static type enforcement across all UI components, state stores, and API clients. |
| Used In | 100% of frontend codebase (.tsx, .ts). |
Why We Used It
- End-to-End Contract Safety: Shared data contracts (
ProductItem, StoreItem, OrderItem, UserRole) guarantee that backend response fields match what the UI expects, preventing TypeError: cannot read property of undefined at runtime.
- Refactoring Confidence: Large UI refactors (like migrating reviews to universal catalogs or updating delivery slot schemas) are immediately validated by the TypeScript compiler (
tsc --noEmit).
4. Tailwind CSS v4
| Attribute | Details |
|---|
| Role in SheoMart | Utility-first styling engine, dark/light theme switching, and responsive design. |
| Used In | Every view, modal, button, and responsive layout grid. |
Why We Used It
- Zero Runtime Overhead: Compiles directly to pure, atomic CSS during build timeβno JS-in-CSS performance penalties.
- Tailwind v4 Engine: Powered by Lightning CSS; delivers blazing fast builds with native
@theme CSS variable tokens and no need for bulky tailwind.config.js setups.
- Dark Mode & Theming: Easy toggling between clean modern light interfaces and dark mode for merchant night shifts.
Alternatives Considered
- Styled-Components / Emotion: Heavy runtime CSS-in-JS parsing penalty that degrades mobile shopping performance.
- Raw CSS / SCSS Modules: Lack of design token consistency; leads to massive CSS file sprawl and naming conflicts.
5. TanStack React Query v5
| Attribute | Details |
|---|
| Role in SheoMart | Async server-state caching, background synchronization, and optimistic UI updates. |
| Used In | Store data fetching, product catalogs, customer reviews, order tracking, admin store approvals. |
Why We Used It
- Server State vs Client State Separation: HTTP response caching should not live in global UI stores like Redux. React Query manages cache lifetimes, automated refetching on window focus, and background revalidation.
- Fine-Grained Cache Invalidation: After a merchant updates their store logo or adds a product, calling
queryClient.invalidateQueries({ queryKey: ["my-store"] }) immediately and silently syncs the UI without full page refreshes.
Alternatives Considered
- SWR: Lightweight, but lacks the robust mutation APIs, granular query filters, and devtools of TanStack Query v5.
- Handwritten
useEffect + useState: Prone to race conditions, memory leaks on unmounted components, missing deduplication, and boilerplates.
6. Zustand v5
| Attribute | Details |
|---|
| Role in SheoMart | Client-only global state management (Auth tokens, Cart items, and User Geolocation/Pincode). |
| Used In | auth-store.ts, cart-store.ts, location-store.ts. |
Why We Used It
- Minimalist Footprint (<2kB): Zero boilerplate; no providers, no reducers, no complex action dispatchers.
- Selector-Based Re-renders: Components only re-render when the exact piece of state they subscribe to changes (e.g. cart item badge only updates when
items.length changes).
- LocalStorage Persistence: Easily integrated with
persist middleware to preserve customer carts and user preferences across browser sessions.
Alternatives Considered
- Redux Toolkit: Powerful, but introduces unnecessary complexity and verbosity for state that is largely client-only (Cart, Token, Pincode).
- React Context API: Triggers full subtree re-renders whenever any value in the context changes, hurting mobile performance.
| Attribute | Details |
|---|
| Role in SheoMart | High-performance uncontrolled form handling and client-side schema validation. |
| Used In | Checkout forms, login/registration, merchant store profile settings, and product creation forms. |
Why We Used It
- Uncontrolled Inputs for Performance: Does not re-render the entire form on every keystroke, keeping large forms (like store settings with delivery slots) snappy.
- Zod Schema Reusability: Define validation rules once (e.g., phone regex, positive delivery fees, opening times) and share standard schemas between frontend validation and backend controllers.
8. Recharts
| Attribute | Details |
|---|
| Role in SheoMart | Declarative charting library for analytical dashboards. |
| Used In | /store/analytics (Merchant revenue, daily sales) and /admin/analytics (GMV, platform metrics). |
Why We Used It
- Native React + SVG: Built specifically for React components. Seamless responsive resizing, custom tooltips, and easy Tailwind styling.
- Lightweight Compared to D3: Provides ready-to-use BarCharts, LineCharts, and AreaCharts without having to hand-code low-level SVG path math.
9. Socket.IO Client
| Attribute | Details |
|---|
| Role in SheoMart | Real-time bi-directional WebSocket client. |
| Used In | Live customer support ticketing chat (join_ticket, typing), real-time merchant order dispatch queue (join_store). |
Why We Used It
- Automatic Fallback & Reconnection: If raw WebSocket connectivity is blocked by enterprise proxies or mobile firewalls, it automatically falls back to HTTP long-polling.
- Room-Based Isolation: Allows listening to specific events without broadcasting all updates to every connected browser.
10. Lucide React
| Attribute | Details |
|---|
| Role in SheoMart | Modern, uniform iconography. |
| Used In | Dashboard navigation, action buttons, status pills, and empty states. |
Why We Used It
- Tree-Shakeable: Only the specific icons imported (e.g.
Upload, Trash2, Store) are bundled, saving bundle size.
- Consistent Stroke & Aesthetic: Ensures visual harmony across both customer storefronts and dense admin dashboards.
11. Axios & Interceptors
| Attribute | Details |
|---|
| Role in SheoMart | HTTP client for all backend REST API communications. |
| Used In | src/services/api.ts and all API service modules. |
Why We Used It
- Global Interceptor Pipeline:
- Automatically attaches
Authorization: Bearer <token> to requests.
- Intercepts
401 Unauthorized responses and transparently handles token refresh via /api/v1/auth/refresh without interrupting the user.
- Automatically deletes manual
Content-Type headers for FormData so the browser computes the boundary hash properly.
βοΈ Backend Stack Breakdown
1. Node.js (LTS 20+)
| Attribute | Details |
|---|
| Role in SheoMart | Asynchronous, event-driven JavaScript server runtime. |
| Used In | Entire backend service layer. |
Why We Used It
- Non-blocking I/O: Hyperlocal commerce is heavy on I/O (handling concurrent WebSocket connections, database queries, and payment webhooks) rather than CPU-bound heavy math. Node's event loop handles thousands of concurrent requests with low memory overhead.
- Single Language Advantage: Shared data models, validation schemas, and types between Next.js and Express.
2. Express 5 (v5.2.1)
| Attribute | Details |
|---|
| Role in SheoMart | Core HTTP routing and middleware framework. |
| Used In | API endpoints, security pipelines, and request dispatchers. |
Why We Used It
- Native Async/Promise Error Handling: Express 5 natively handles rejected promises in route handlers without needing third-party wrappers to catch unhandled async exceptions.
- Vast Middleware Ecosystem: Instant compatibility with battle-tested security middleware (Helmet, Cookie-Parser, Rate-Limit, CORS).
- Minimalist & Transparent: Unopinionated architecture lets us organize modular controllers, services, and validators cleanly.
Alternatives Considered
- NestJS: Highly structured and Angular-like, but introduces heavy boilerplate, class-validator overhead, and dependency injection ceremony that slows down development.
- Fastify: Faster raw HTTP throughput, but has a smaller middleware ecosystem and slightly more complex integration with custom WebSocket setups.
3. TypeScript (Backend)
| Attribute | Details |
|---|
| Role in SheoMart | Type safety across models, middleware, controllers, and services. |
| Used In | 100% of backend files (sheomart-backend/src/**/*.ts). |
Why We Used It
- Strong Typing for Requests & Auth: Custom
AuthRequest interfaces guarantee that downstream controllers know req.user.userId and req.user.role are verified, eliminating undefined access bugs.
- Mongoose Document Safety: Types derived from Mongoose schemas ensure database queries never access non-existent fields.
4. MongoDB & Mongoose 9
| Attribute | Details |
|---|
| Role in SheoMart | Primary NoSQL document database and Object Data Modeling (ODM) layer. |
| Used In | Users, Stores, Products, Orders, Invoices, Reviews, Coupons, and Audit Logs. |
Why We Used It
- Polymorphic Product & Store Schemas: Grocery products have varying attributes (fruits sold by kg/g; packaged goods sold by ml/l/pcs; clothing/items with variants). MongoDB's flexible JSON-like documents handle semi-structured product catalogs effortlessly.
- Embedded Subdocuments: Delivery slots, address components, and order item snapshots are naturally embedded directly inside their parent documents, eliminating expensive multi-table joins.
- Mongoose 9 Modern Features: Robust schema validation, pre-save middleware for password hashing, and clean discriminator support.
Alternatives Considered
- PostgreSQL: Exceptional for strict relational financial ledgers, but requires migrations and table alteration for every custom grocery attribute or store delivery preference. (See detailed comparison below).
5. Socket.IO (Server)
| Attribute | Details |
|---|
| Role in SheoMart | Real-time WebSocket server engine. |
| Used In | sheomart-backend/src/socket.ts β Room management for live store orders and customer support. |
Why We Used It
- Channel / Room Primitive: Supports isolated rooms like
store_<storeId> and ticket_<ticketId>. Emitting events to specific rooms takes one line of code: io.to(ticketId).emit("new_message", message).
- Built-in Heartbeats & Reconnections: Transparently handles reconnects when users switch from Wi-Fi to cellular data.
Alternatives Considered
- Native
ws package: Extremely fast, but lacks built-in rooms, namespaces, fallback transports, and automated reconnection logic.
- Third-Party Hosted (Pusher / Ably): Adds recurring monthly cloud costs and introduces third-party data privacy dependencies. Self-hosted Socket.IO is free, flexible, and completely private.
6. Cloudinary + Sharp + Multer
| Attribute | Details |
|---|
| Role in SheoMart | Multi-vendor image upload, processing, and CDN hosting pipeline. |
| Used In | Store logo & banner uploads (POST /me/upload-asset), product images, and category icons. |
Why We Used It
- Multer Memory Storage: Stores files in RAM buffer (
req.file.buffer) rather than saving to local server disks. This makes the backend 100% stateless and ready for Docker / Kubernetes / Serverless hosting.
- Sharp Optimization: Inspects magic bytes, validates file integrity, strips EXIF metadata, and resizes large seller photos before uploading.
- Cloudinary CDN: Provides global image delivery, automatic WebP/AVIF format negotiation based on user browser, and on-the-fly transformations (e.g., squircle store logos, wide banners).
Alternatives Considered
- Direct S3 + CloudFront: Requires managing custom S3 buckets, CORS policies, IAM roles, and separate image resizing Lambdas. Cloudinary provides storage, transformation, and CDN in a single managed API.
7. Razorpay SDK
| Attribute | Details |
|---|
| Role in SheoMart | Primary payment gateway integration for online transactions in India. |
| Used In | Checkout order creation (/payments/razorpay/create-order) and signature verification. |
Why We Used It
- India Hyperlocal Market Fit: Seamless native support for UPI (Google Pay, PhonePe, Paytm), NetBanking across 50+ banks, RuPay, and credit/debit cards.
- Cryptographic Signature Verification: Backend validates HMAC SHA256 signatures (
razorpay_order_id|razorpay_payment_id) against RAZORPAY_KEY_SECRET to prevent payment tampering.
Alternatives Considered
- Stripe: Exceptional international developer experience, but higher friction and lower adoption for Indian domestic UPI and debit cards compared to Razorpay.
8. Zod (Backend Validation)
| Attribute | Details |
|---|
| Role in SheoMart | Strict request boundary validation and payload parsing. |
| Used In | All backend validators (validators/*.ts). |
Why We Used It
- TypeScript Type Inference:
type SettingsPayload = z.infer<typeof settingsSchema> eliminates duplicate type definitions between validation logic and TypeScript types.
- Strict Parsing (
safeParse): Rejects unexpected fields and coerces types safely before data reaches the controller layer.
Alternatives Considered
- Joi / Yup: Established libraries, but require duplicate interface maintenance because TypeScript static types cannot be inferred automatically as cleanly as with Zod.
9. JWT Dual-Token Authentication
| Attribute | Details |
|---|
| Role in SheoMart | Stateless, secure user authentication and session persistence. |
| Used In | Auth controllers, refresh token rotation, and role-based guards (authorize(...)). |
Why We Used It
- Short-Lived Access Token (15m): Even if an access token is compromised, the window of vulnerability is narrow.
- Long-Lived Rotating Refresh Token (7d): Stored in an
httpOnly, secure, sameSite: strict cookie, protecting against Cross-Site Scripting (XSS).
- Stateless Verification: The backend verifies tokens cryptographically using secret keys without querying the database on every single protected request.
10. Helmet, HPP, Sanitize & Rate Limiting
| Attribute | Details |
|---|
| Role in SheoMart | Comprehensive OWASP defense-in-depth security layer. |
| Used In | sheomart-backend/src/app.ts middleware pipeline. |
Component Breakdown
- Helmet: Enforces HSTS (1 year with preload), Frameguard (
deny clickjacking), CSP, and disables MIME type sniffing (noSniff).
- HPP (HTTP Parameter Pollution): Protects against attackers passing duplicate query parameters (e.g.
?role=user&role=admin).
- Custom
mongoSanitize: Recursively strips any key starting with $ or containing . to neutralize NoSQL injection attacks.
- Granular Rate Limiters:
- Global API limiter prevents brute-force traffic.
- Separate, generous rate limiters for POS Counter Billing (
billingPosLimiter) so high-frequency offline store billing is never blocked.
- Dedicated rate limiters for Search and Analytics to prevent resource exhaustion.
11. Nodemailer
| Attribute | Details |
|---|
| Role in SheoMart | Transactional email delivery. |
| Used In | Account verification, merchant password reset requests, and order notifications. |
Why We Used It
- Provider Agnostic: Connects seamlessly to Gmail, SendGrid, Amazon SES, or custom SMTP servers without locking into a proprietary proprietary vendor SDK.
βοΈ Cross-Cutting Architectural Comparisons
MongoDB vs PostgreSQL for Grocery Commerce
βββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β MongoDB (Mongoose) β PostgreSQL β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β β
Semi-structured grocery catalogs β β Rigid schemas require complex JOINs β
β (varying units, metrics, packages) β for arbitrary grocery item attributes β
β β β
β β
Embedded subdocuments for delivery β β Separate foreign-key tables needed for β
β slots, geo-coordinates & addresses β every nested array or time window β
β β β
β β
Rapid schema evolution for multi- β β Heavy database migration scripts for β
β vendor feature expansions β every minor column addition β
β β β
β β οΈ Relies on app-level transactions β β
Native multi-table ACID transactions β
β for complex multi-document updates β ideal for traditional bank ledgers β
βββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
Conclusion: For a fast-evolving multi-vendor marketplace where every vendor has different product types (loose vegetables, packaged items, dairy, home goods), MongoDB's flexible document model significantly reduced boilerplate and query complexity.
βββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββ
β Zustand β Redux Toolkit β
βββββββββββββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββ€
β β
<2 KB bundle footprint β β 25+ KB bundle footprint β
β β
Zero boilerplate (hooks-based) β β Requires Slices, Reducers, Actions β
β β
No top-level Context Provider β β Requires wrapping app in <Provider> β
β β
Granular atomic selector updates β β
Robust Redux DevTools time travel β
β β
Perfect for client state (Cart) β β οΈ Overkill when using React Query for APIβ
βββββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββ
Conclusion: Because TanStack React Query already manages 90% of our state (all server-side data), using Redux Toolkit for the remaining 10% (Cart items and auth token) would introduce unnecessary complexity. Zustand gave us instantaneous state reads with zero ceremony.
Express 5 vs NestJS vs Fastify
βββββββββββββββββββββββββ¬ββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β Express 5 β NestJS β Fastify β
βββββββββββββββββββββββββΌββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββ€
β β
Native async error β β οΈ Heavy TypeScript β β
Highest raw HTTP throughput β
β handling β decorators & OOP β β
β β β β
β β
World's largest β β οΈ Heavy boilerplate β β οΈ Smaller middleware ecosystem β
β middleware library β & dependency injectβ for specialized security tools β
β β β β
β β
Maximum team β β
Excellent for 100+ β β οΈ Slightly steeper learning curveβ
β flexibility β developer teams β for WebSocket integrations β
βββββββββββββββββββββββββ΄ββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββ
Conclusion: Express 5 eliminated the legacy pain points of Express 4 (unhandled promise rejections) while preserving complete freedom of architecture and instant compatibility with every Node.js package.
In-Memory Buffer Uploads vs Disk-Based Uploads
- The Traditional Approach (Disk Storage): Multer writes the uploaded file to
./uploads on the server disk, then a secondary script uploads it to the cloud and deletes the local file.
- Problems: Server storage fills up; files are lost if the server container restarts or scales horizontally (multi-instance).
- The SheoMart Approach (Memory Storage): Files are kept in a small memory buffer (
Buffer), checked for magic bytes by Sharp, and piped directly over HTTPS to Cloudinary.
- Benefits: The backend remains completely stateless, eliminating local disk dependencies and making multi-server cloud deployment effortless.
π Summary Decision Matrix
| Layer | Selected Tech | Key Reason | #1 Alternative Rejected | Reason for Rejection |
|---|
| Frontend Framework | Next.js 16 | SSR + Nested App Layouts | Vite React SPA | No native SEO or dynamic metadata |
| Styling | Tailwind CSS v4 | Zero-runtime CSS + Atomic tokens | Styled-Components | Heavy runtime JS-in-CSS performance penalty |
| Server State | TanStack Query v5 | Cache invalidation & revalidation | SWR | Less powerful mutation & invalidation APIs |
| Client State | Zustand v5 | Lightweight (<2kB), no providers | Redux Toolkit | Excessive boilerplate for simple client stores |
| Forms & Validation | React Hook Form + Zod | Uncontrolled inputs + Shared schemas | Formik + Yup | Formik causes high re-render latency |
| Backend Runtime | Node.js + Express 5 | Async native errors + vast ecosystem | NestJS | Unnecessary OOP & DI boilerplate |
| Database | MongoDB + Mongoose 9 | Flexible multi-vendor grocery schemas | PostgreSQL | Rigid schemas slow down attribute iteration |
| Real-time | Socket.IO | Channel rooms + auto-reconnection | Raw WebSockets | Lacks built-in rooms and reconnection logic |
| Image Pipeline | Cloudinary + Sharp | Stateless buffer upload + CDN | Local disk storage | Breaks stateless container scaling |
| Payment Gateway | Razorpay | Native Indian UPI & NetBanking | Stripe | Higher friction for domestic Indian cards/UPI |
| Security Layer | Helmet + Custom NoSQL | End-to-end OWASP header & query guard | Basic Express | Vulnerable to injection and header exploits |
SheoMart Tech Stack Documentation β Engineered for Performance, Scalability & Security.