The problem
Independent veterinary clinics juggle paper charts, spreadsheets, WhatsApp appointments and separate point-of-sale tools. A pet's medical history (vaccinations, surgeries, prescriptions, dental work) ends up spread across notebooks. International practice-management products don't support PayTabs or pricing in currencies like JOD, AED and SAR, and paying for them with an overseas card adds friction.
VetRealm serves four roles:
- Clinic owner. The buyer. Needs one source of truth for operations, revenue visibility, control over the team and a recurring subscription.
- Veterinarian. Needs a fast appointment flow, the full medical history at the point of care and prescriptions that dispense against live inventory.
- Receptionist. Needs quick client and pet onboarding, calendar booking, invoicing and payment collection in one flow.
- Platform admin. Onboards clinics, manages subscription plans, watches MRR, impersonates users for support and broadcasts announcements.
What I built
I designed and built VetRealm as a multi-tenant SaaS: a React 19 single-page app on an Express 5 and MongoDB API. It has three surfaces: the public marketing site, the clinic dashboard and a platform admin portal. Each clinic is a tenant, and its data is isolated at the middleware layer.
Clinical workflow
- A FullCalendar scheduler with day, week and month views, drag-to-schedule, a multi-staff overlay and live sync over Socket.IO.
- Typed appointments (grooming, surgery, medication, boarding) with type-specific fields and a
check-in → in-progress → completedstate machine. - One client and pet directory with a multi-step onboarding flow.
- A full pet medical history: vaccinations, surgeries, medication logs, observation notes, documents, allergies and existing conditions.
- An interactive SVG dental chart in FDI notation, with per-tooth state (healthy, missing, fractured, decay, extracted) and an audit trail.
- Prescriptions linked to the pet, appointment and vet. Dispensing deducts stock from inventory.
Clinic operations
- Inventory across six categories (medicine, food, supply, vaccine, equipment, other), with SKUs unique per clinic, suppliers and expiry-batch tracking.
- Reorder-level alerts pushed in real time.
- A stock ledger that records every stock-in, stock-out, dispense, expiry and adjustment.
- Line-item invoices built from services and products, with tax, subtotal and a
draft → sent → paid → overdue / voidstatus machine. - A payment ledger (cash, card, bank transfer, other) with CSV and PDF export.
- Recharts reports on revenue, appointment volume and inventory usage, with streaming CSV export.
- Team management with per-module permissions split into view and manage, and an invite-and-accept flow.
Platform layer
- Clinic owner self-signup with email verification, password reset, employee invitations and TOTP two-factor authentication.
- Starter, Pro and Business plans with a 14-day free trial and monthly or yearly billing in JOD, paid through a PayTabs hosted payment page.
- Clinic-scoped real-time notifications with a badge counter.
- Light and dark themes on a reusable component library.
Admin portal
- A KPI dashboard: total clinics, active subscriptions, MRR, churn and new clinics in the last 30 days.
- Clinic management with support impersonation, fully audit-logged.
- User management across every clinic.
- Subscription plan CRUD (name, price, currency, interval, trial days, feature limits) that takes effect without a deploy.
- Announcements to all clinics or a targeted group, written in a Tiptap editor with a draft and publish step.
- Platform revenue and growth reports, and a global pet-type catalog.
Architecture
Tenant isolation in one place
Every non-auth request passes through an ensureClinicAccess middleware. It reads the clinic from the authenticated user, attaches req.clinicId, and every downstream query is scoped to it. Isolation is enforced in one layer instead of being repeated in each controller.
Layered authorization
Each route composes three gates: JWT authentication (protect), a role gate (authorize('owner' | 'employee' | 'admin')) and a fine-grained permission gate such as hasPermission('INVENTORY_MANAGE'). The client mirrors them with PrivateRoute, AdminRoute, SubscriptionGuard, PermissionGuard and PlanGuard, so screens a user is not allowed to use never render.
Refresh-token rotation
Access tokens last 15 minutes. Refresh tokens last 7 days and are stored in httpOnly cookies. An Axios response interceptor catches a 401, queues any concurrent requests, fires a single refresh call and replays the queue. Users only see a login screen when the refresh token itself has expired.
Clinic-scoped real-time rooms
Socket.IO rooms are keyed by clinic ID. On connect the client emits joinClinic(clinicId) and the server adds the socket to that room. Calendar changes and notifications go to the room, never globally, so every open tab in a clinic stays in sync and no other clinic receives the event. Server-side helpers write a notification to MongoDB and emit it in one operation.
Medical records as embedded documents
A Pet carries six embedded sub-schemas (vaccinations, surgeries, medication logs, observation notes, medical documents and FDI dental records) plus a previousOwners trail for transferred pets. Embedding them instead of splitting them into collections keeps a pet profile to a single read and keeps the full history with it.
Hard problems
Overlap checks that stay indexed
A compound index on (clinic, startTime, endTime) turns appointment overlap detection into an indexed range query instead of a collection scan, so the cost of the check follows the index rather than the size of a clinic's appointment history.
HMAC over the bytes PayTabs signed
PayTabs signs its callbacks with HMAC-SHA256, and Express's JSON parser consumes the body before a handler sees it. A verify callback on bodyParser.json captures req.rawBody before parsing. The handler recomputes the HMAC over those exact bytes and compares with crypto.timingSafeEqual before it touches any subscription state.
Unique emails that survive deletes and blanks
MongoDB's unique index treats null as a value, and clients are soft-deleted. A pre-save hook converts empty strings to null and checks email uniqueness among active clients only, so a deleted client's email can be used again by a later signup.
Transactions without a replica set
Mongoose sessions require a replica set. A connector checks isMaster() for setName or msg: 'isdbgrid' and, on a standalone MongoDB, stubs out the session methods. Local development runs on a plain MongoDB and the transactional code paths still execute.
Inventory that cannot drift
Dispensing a prescription writes a StockTransaction, decrements Product.stockQuantity and updates the prescription status in one transaction. If any step fails, all three roll back, so the stock ledger and prescription state stay consistent.
CSV exports that stream
A csvStreamer middleware adds res.csvStream(), which pipes json2csv Transform streams straight to the response. A long invoice export is never assembled in memory first.
Data model
| Model | What it holds |
|---|---|
| User | Clinic owners, employees and platform admins, with bcrypt-hashed credentials and 2FA state |
| Clinic | The tenant boundary; every domain query is scoped to it by middleware |
| Client | Pet owners in a clinic, with email uniqueness that allows reuse after a soft delete |
| Pet | The medical record hub, with six embedded sub-schemas and a previous-owners trail |
| Appointment | Typed appointments with a compound (clinic, startTime, endTime) index for overlap queries |
| AppointmentType | Configurable appointment categories with type-specific field definitions |
| Invoice | Line items and a payments ledger, with totals recomputed on save and a status machine |
| Prescription | Linked to pet, appointment and vet; dispensing decrements stock atomically |
| Product | Inventory in six categories, SKU unique per clinic, with expiry-batch tracking |
| Supplier | Inventory sources, soft-deleted so history still resolves |
| StockTransaction | Ledger of every inventory movement |
| SubscriptionPlan | Name, price, currency, interval, trial days and feature limits, editable by admins |
| Notification | Per-user, clinic-scoped events categorized by domain type |
| SystemNotification | Admin-authored broadcasts to all clinics or a targeted audience |
| Invitation | Employee invites, with a partial unique index on pending (email, clinic) so a revoked invite can be re-sent |
| AuditLog | Immutable record of impersonation, status and subscription changes, with admin ID, target, IP and timestamp |
| PetType | Global catalog of species managed by platform admins |
Security
Token rotation, tenant scoping, webhook verification and the audit log are covered above. Alongside them:
- Passwords hashed with bcryptjs at 10 salt rounds, with a pre-save hook that skips values already hashed.
- TOTP two-factor authentication through Speakeasy, with QR-code setup.
- Rate limiting on auth endpoints in 15-minute windows.
- Email verification tokens that are hashed, single-use and expire in 10 minutes.
- Uploads limited to JPEG, PNG and GIF, capped at 2 MB.
- CORS locked to the configured client URL in credentials mode.
- Soft deletes on clients, pets, employees, suppliers and plans, so history survives.
In production
Express 5 serves the React build with SPA-fallback routing, and uploads from a static /uploads endpoint. Transactional email covers verification, password reset, invitations and appointment reminders. The UI sits on a /src/ui library of 12+ base primitives with dark-mode tokens.
What it demonstrates
- Multi-tenant isolation enforced in middleware, not spread across controllers.
- Domain modelling that follows how a clinic works: typed appointments, dental charting, prescriptions tied to stock.
- Regional payments: a PayTabs hosted page, verified webhooks and plans an admin can change without a deploy.
- Security built into the foundation: 2FA, rotating refresh tokens, timing-safe HMAC, rate limiting and audit logs.
- Admin tooling, including impersonation and platform KPIs, treated as part of the product.