VetRealm
A multi-tenant veterinary practice-management SaaS for the MENA market — appointments, medical records with interactive dental charts, inventory, prescriptions, billing, and real-time team coordination, backed by PayTabs recurring subscriptions across seven regions.
Vertical SaaS for veterinary clinics, built for MENA reality.
VetRealm is a full-stack, multi-tenant practice platform that replaces paper charts, spreadsheets, and WhatsApp bookings with a single auditable source of truth. Clinics get appointments, medical records, inventory, prescriptions, billing, team permissions, and analytics — in one system — while clinic owners get real revenue visibility and recurring PayTabs subscriptions priced in their own currency.
Where international veterinary PMS products ignore the region — no Arabic-first UX, no JOD/AED/SAR pricing, no local card-billing rails — VetRealm treats MENA as a first-class market, not an afterthought.
A modern vertical the region couldn't buy.
- Independent clinics juggle paper charts, spreadsheets, WhatsApp appointments, and fragmented point-of-sale tools.
- Medical history — vaccinations, surgeries, prescriptions, dental work — scatters across notebooks and drives stock-outs through missing data.
- International PMS products ignore MENA reality: no PayTabs, no JOD / AED / SAR pricing, no Arabic-first UX, overseas card-billing friction.
One multi-tenant platform — regionalised end-to-end.
VetRealm consolidates the full clinical workflow into a single React 19 SPA backed by an Express 5 + MongoDB API. Clinic data is isolated at the middleware layer, role and permission gates compose per route, and PayTabs-hosted recurring subscriptions with HMAC-verified webhooks close the billing loop across seven regions.
Real-time Socket.IO rooms keep every tab of every employee in sync — calendar changes, notifications, low-stock alerts — while an admin portal gives the platform team impersonation, plan CRUD, and MRR-level visibility.
Four roles, one platform.
Clinic owner
The buyer — needs a single source of truth for operations, revenue visibility, team control, and recurring subscription billing.
Veterinarian
Needs a fast appointment flow, complete pet medical history at the point of care, and a prescription workflow that dispenses against live inventory.
Receptionist
Needs quick client and pet onboarding, calendar booking, invoice generation, and payment collection in a single flow.
Platform admin
Onboards clinics, manages subscription plans, monitors MRR, impersonates for support, and broadcasts system-wide announcements.
What the platform does.
Clinical workflow
- Smart calendar (FullCalendar) — day, week, and month views with drag-to-schedule, multi-staff overlay, and real-time Socket.IO sync.
- Typed appointments (Grooming, Surgery, Medication, Boarding) with type-specific fields and a check-in → in-progress → completed state machine.
- Unified client and pet directory with a multi-step onboarding flow.
- Complete pet medical history — vaccinations, surgeries, medication logs, observation notes, medical documents, allergies, existing conditions.
- Interactive SVG dental chart in FDI notation — per-tooth state (healthy, missing, fractured, decay, extracted) with audit trail.
- Prescriptions linked to pet, appointment, and vet — dispense workflow auto-deducts stock from inventory.
Clinic operations
- Inventory across six categories (medicine, food, supply, vaccine, equipment, other) with SKU uniqueness per clinic.
- Reorder-level alerts pushed in real time.
- Stock-movement ledger — every transaction audited (stock_in, stock_out, dispensed, expired, adjustments).
- Supplier management and expiry-batch tracking.
- Line-item invoicing pulling from services and products — tax, subtotal, and a status machine (draft → sent → paid → overdue / void).
- Payment ledger (cash, card, bank transfer, other) with CSV and PDF export.
- Recharts reports — revenue trends, appointment volume, inventory usage — with streaming CSV export.
- Team management with granular per-module permissions (view / manage split) and invite → accept flow.
Platform layer
- Clinic owner self-signup with 10-minute single-use email verification tokens.
- TOTP two-factor authentication via Speakeasy with QR-code setup.
- Password reset and employee invitation flows.
- 15-minute access tokens plus 7-day rotating refresh tokens in httpOnly cookies.
- Tiered subscriptions (Starter / Pro / Business) with a 14-day free trial and monthly or yearly billing in JOD.
- PayTabs hosted payment page with HMAC-SHA256 webhook verification.
- Real-time clinic-scoped notifications with badge counter and categorized event types.
- Light/dark mode theming with an accessible component library.
Admin portal
- Platform KPI dashboard — total clinics, active subscriptions, MRR, churn, new clinics per 30 days.
- Clinics management with support impersonation (fully audit-logged).
- User management across every clinic.
- Subscription plan CRUD — name, price, currency, interval, trial days, features with limits.
- System-wide notification broadcasts — all clinics or a targeted audience, draft → published, Tiptap WYSIWYG authoring.
- Platform revenue and growth reports.
- Global pet-types catalog (Dog, Cat, Rabbit, Bird, and more).
- Audit log of sensitive admin actions — impersonation start, clinic status change, subscription change.
How it holds together.
Multi-tenant data isolation
Every non-auth request passes through an ensureClinicAccess middleware that attaches req.clinicId from the authenticated user and scopes every downstream query to it. Cross-tenant data leaks are structurally prevented at the middleware layer rather than sprinkled through controllers.
Layered authorization
Three composable gates per route — JWT auth (protect), role gate (authorize('owner' | 'employee' | 'admin')), and fine-grained permission gate (hasPermission('INVENTORY_MANAGE', …)). The client mirrors them with PrivateRoute, AdminRoute, SubscriptionGuard, PermissionGuard, and PlanGuard so forbidden UI never renders.
Refresh-token rotation
15-minute access tokens with 7-day refresh tokens stored as httpOnly cookies. An Axios response interceptor catches 401s, queues concurrent in-flight requests, fires a single refresh call, and replays the queue — users never see a login modal unless the refresh token itself has expired.
Clinic-scoped Socket.IO rooms
Rooms keyed by clinicId. On connect the client emits joinClinic(clinicId) and the server adds the socket to that room. Notifications and calendar events broadcast to the room, never globally — clinic A never sees clinic B's events, and every tab of every employee gets live updates.
PayTabs + HMAC-verified webhooks
Checkout spins up a PayTabs hosted page with regional cart metadata; on completion PayTabs calls back. The server captures the raw body via a bodyParser verify callback, recomputes HMAC-SHA256 over the exact signed bytes, and uses crypto.timingSafeEqual to compare — blocking timing-leak attacks before touching subscription state.
Domain-rich medical schemas
Pet carries six embedded sub-schemas — vaccinations, surgeries, medication logs, observation notes, medical documents, and FDI-notation dental records — plus a previousOwners trail for transferred pets. Embedded sub-documents (not separate collections) keep pet-profile reads fast while preserving full audit history.
Modern, proven, boring-where-it-matters.
Frontend
- React 19 (Create React App)
- React Router 6 with lazy-loaded routes
- Tailwind CSS 3 — semantic CSS-variable tokens + dark mode
- React Context API (Auth, AdminAuth, Socket)
- Axios with refresh-token interceptor
- socket.io-client 4
- Framer Motion 12
- FullCalendar (daygrid / timegrid / interaction)
- @tanstack/react-table 8 (headless)
- Recharts 2
- Zod 3 (per-entity schemas)
- Tiptap (WYSIWYG for admin broadcasts)
Backend
- Node.js + Express 5
- MongoDB + Mongoose 8
- Socket.IO 4 (clinic-scoped rooms)
- jsonwebtoken (15-min access + 7-day refresh)
- bcryptjs (salt rounds = 10)
- Speakeasy (TOTP 2FA) + qrcode
- paytabs_pt2 SDK (MENA hosted payment page)
- Multer (2 MB cap, image MIME only)
- Nodemailer (SMTP transactional email)
- express-validator, express-rate-limit
- json2csv (Transform streams)
- cookie-parser, cors
Infrastructure
- MongoDB — transaction-aware on replica sets and sharded clusters
- Express static serving of the React production build with SPA fallback
- File uploads served from a /uploads static endpoint
- Gmail SMTP (app password) for transactional email
- PayTabs hosted payment page (Jordan region by default)
- Standalone-vs-replica-set detector keeps local dev frictionless
The hard parts — and how they got solved.
Overlap-free scheduling at scale
A compound index (clinic, startTime, endTime) on Appointment turns overlap detection into an indexed range query rather than a full-collection scan — stays fast as clinics accumulate years of history.
Null-safe unique emails per clinic
MongoDB's unique index treats null as a value. A pre-save hook converts empty strings to null and manually validates email uniqueness among active clients only, so deleted clients' emails can be re-used by future signups.
PayTabs HMAC over raw body
Express's JSON parser consumes the body by default, which would break HMAC verification. A custom verify callback on bodyParser.json captures req.rawBody before parsing — HMAC computes over the exact bytes PayTabs signed.
Dev-friendly transactions
Mongoose sessions require replica sets. A smart connector checks isMaster() for setName or msg: 'isdbgrid' and stubs out session methods on standalone MongoDB — contributors can npm run dev without a replica set and the transactional code paths still work in dev.
Inventory integrity on dispense
Dispensing a prescription writes a StockTransaction (audit), decrements Product.stockQuantity, and updates the prescription status atomically. If any step fails the whole operation rolls back — stock ledgers and prescription state never drift apart.
Token refresh without UX disruption
The Axios response interceptor catches 401s, queues concurrent requests, fires a single /auth/refresh-token call, and replays the queue on success. Users never see a login modal unless the refresh token itself has expired.
Memory-efficient CSV exports
A custom csvStreamer middleware attaches res.csvStream() that pipes json2csv Transform streams directly to the response — exporting 100 k invoices doesn't buffer in memory.
Multi-tenant Socket.IO broadcasts
Every clinic has its own Socket.IO room; server-side helpers write notifications to MongoDB and emit to the room in a single operation. Cross-tenant leakage is impossible at the socket layer.
Seventeen core entities.
Schemas
- UserClinic owners, employees, and platform admins with bcrypt-hashed credentials and 2FA state.
- ClinicThe tenant boundary — every domain query is clinic-scoped via middleware.
- ClientPet owners belonging to a clinic, with unique-email handling that allows reuse after soft delete.
- PetMedical records hub with six embedded sub-schemas and a previous-owners trail.
- AppointmentTyped appointments with a compound (clinic, startTime, endTime) index for O(log n) overlap queries.
- AppointmentTypeConfigurable appointment categories with type-specific field definitions.
- InvoiceLine items + payments ledger with pre-save total recomputation and status machine.
- PrescriptionLinked to pet, appointment, and vet — dispensing atomically decrements product stock.
- ProductInventory across six categories with SKU uniqueness per clinic and expiry-batch tracking.
- SupplierInventory source records with soft delete for historical lookups.
- StockTransactionAudit ledger for every inventory movement — stock_in, stock_out, dispensed, expired, adjustments.
- SubscriptionPlanName, price, currency, interval, trial days, feature flags with limits — admin-editable without deploy.
- NotificationPer-user clinic-scoped events with badge counter, categorized by domain type.
- SystemNotificationAdmin-authored broadcasts to all clinics or a targeted audience, draft → published.
- InvitationEmployee invite flow with partial unique index on pending (email, clinic) — lets the same email re-invite after revocation.
- AuditLogImpersonation, status change, subscription change — immutable with admin id, target, IP, timestamp.
- PetTypeGlobal reference catalog (Dog, Cat, Rabbit, Bird, …) managed by platform admins.
Hardened by default.
Clinics hold real PII and recurring payment data, so security is treated as a first-class feature — rotation, 2FA, webhook integrity, tenant isolation, and audit logging are in the foundation, not retrofitted.
What's included
- bcryptjs password hashing (salt rounds = 10) with a pre-save hook that skips if already hashed
- 15-minute access tokens plus 7-day refresh tokens stored as httpOnly cookies with withCredentials
- TOTP two-factor authentication via Speakeasy with QR-code setup
- Rate limiting on auth endpoints (15-minute windows) to blunt brute-force attempts
- HMAC-SHA256 PayTabs webhook verification with crypto.timingSafeEqual comparison
- Email verification tokens — hashed, single-use, 10-minute expiry
- File upload restricted to JPEG / JPG / PNG / GIF with a 2 MB cap
- Clinic-scoped queries at the middleware layer — cross-tenant leaks structurally prevented
- Immutable admin audit log of sensitive actions (impersonation, status change, subscription change)
- Strict CORS locked to the configured CLIENT_URL with credentials mode
- Soft deletes on clients, pets, employees, suppliers, plans — audit trail preserved
What "production-grade" looked like.
What the team shipped.
- Full-stack veterinary SaaS live at vetrealm.com spanning public marketing, clinic dashboard, and admin portal.
- 17 domain models covering clinical workflow, inventory, billing, team, and platform concerns.
- Interactive SVG dental chart with FDI notation and per-tooth audit trail.
- Real-time clinic-scoped Socket.IO rooms for calendar and notification sync.
- PayTabs-backed recurring subscriptions with HMAC-verified webhooks across seven MENA regions.
- Admin portal with impersonation, platform KPIs, plan CRUD, and audit-logged sensitive actions.
- Streaming CSV exports that scale to 100 k-row reports without buffering in memory.
Capabilities proven at production scale.
- Multi-tenant SaaS architecture — clinic isolation enforced at the middleware layer, not sprinkled through controllers.
- Vertical SaaS depth — domain modelling that reflects how a real clinic actually operates.
- Regional payments integration — PayTabs hosted page, HMAC-verified webhooks, seven-currency support.
- Security engineering — 2FA, rotating refresh tokens, timing-safe HMAC, rate limiting, audit logging.
- Real-time coordination — Socket.IO rooms for calendar and notification broadcasts scoped to tenants.
- Design-system discipline — reusable /src/ui primitives, semantic CSS-variable theming, dark mode.
- Operational tooling — admin portal with impersonation and platform KPIs treated as a first-class surface.
- Developer ergonomics — standalone-MongoDB transaction shim so contributors work without a replica set.
Shipped to production.
- Production deployment serving a React 19 SPA from Express 5 with SPA-fallback routing.
- MongoDB with transaction-aware sessions and a standalone-mode detector for local dev.
- Transactional email pipeline — verification, password reset, invitations, appointment reminders.
- Real-time layer — Socket.IO rooms broadcasting calendar and notification events.
- Reusable /src/ui design system with 12+ base primitives and dark-mode tokens.
- Memory-safe CSV streaming for long reports.
Let's talk about your platform.
If VetRealm looks close to what you're building — multi-tenant SaaS, regional payment rails, real-time coordination, role-based admin tooling — we'd like to hear about it.