FitPulse — High-Performance Gym Management & Community Platform
FitPulse is an end-to-end fitness management platform engineered to resolve the operational bottlenecks of boutique fitness studios and athletic clubs: fragmented scheduling, manual trainer onboarding, payment tracking, and disconnected member communities.
The platform operates on a decoupled client-server architecture—pairing a Next.js 16 App Router frontend with a standalone Express 5 microservice—secured via decentralized cryptographic verification (Remote JWKS) and backed by the native MongoDB driver.
The Challenge & Core Problem
Independent fitness centers frequently rely on fragmented third-party tools: one tool for scheduling, a separate payment gateway, spreadsheets for trainer compensation, and social channels for member retention. This leads to:
- Scheduling Conflicts & Overbooking: Lack of atomic transaction checks when multiple members reserve limited-capacity classes simultaneously.
- Access Security Gaps: Insecure role handling where members can access restricted trainer or admin dashboards without server-side validation.
- Session Latency & Database Overhead: Traditional monoliths repeatedly hit the database to validate sessions across distributed microservices.
System Architecture & Technical Decisions
[ User Browser / Client ]
│
▼
Next.js 16 Frontend (App Router, React 19)
│
┌──────┴──────────────────────────┐
▼ ▼
Better Auth Engine Edge / Node Proxy Guard
(Native Mongo Adapter) (Role-Based Route Interception)
│ │
▼ ▼
Issues Signed JWTs Directs Traffic / Renders UI
│ │
└────────────┬────────────────────┘
│ Bearer Token
▼
Express 5 REST Microservice
│
┌──────────────┴──────────────┐
▼ ▼
Remote JWKS Verification Native MongoDB Driver
(JOSE: Local Cryptographic (MongoClient Connection Pool,
Public Key Caching) Raw Aggregations)
1. Decoupled Auth via Remote JWKS
Instead of sharing database sessions or making synchronous internal API calls for every request, authentication is federated:
- Next.js + Better Auth handles credential and Google OAuth sign-in, persisting users directly via the native MongoDB adapter and exposing a public JSON Web Key Set (
/api/auth/jwks).
- Express 5 Backend implements
jose-cjs with createRemoteJWKSet. Incoming Bearer tokens are validated cryptographically against cached public keys in memory, cutting inter-service latency and database load down to zero for auth checks.
2. High-Throughput Native MongoDB Driver
To eliminate ORM/ODM serialization overhead (such as Mongoose document hydration), the backend communicates directly with MongoDB using MongoClient and connection pooling:
- Fast read/write throughput on high-frequency tables (forum reactions, class queries, enrollment increments).
- Complex queries use native aggregation pipelines for multi-field search, category regex filtering, and real-time revenue rollups.
Key System Pillars (Top Features)
1. Multi-Tiered Role-Based Access Control (RBAC)
FitPulse separates platform capabilities into three strict authorization tiers enforced via both Next.js edge route interceptors (src/proxy.js) and Express route-level middleware:
- Members (Students): Query classes with category/schedule filters, execute atomic bookings, bookmark favorites, interact on forum threads, and submit trainer applications.
- Certified Trainers: Access dedicated management views, publish and update curriculum schedules, author workout protocols on the forum, and track student enrollments.
- Platform Admins: Central command to inspect platform-wide metrics (total revenue, active trainers, booking volume), approve/reject trainer applications with custom feedback, demote trainers, ban abusive accounts, and moderate community threads.
2. Atomic Class Scheduling & Capacity Management
To guarantee class integrity:
- Class bookings enforce uniqueness at the database level (
classId + userEmail) to prevent double-booking.
- Enrollments execute atomic increments (
$inc: { totalEnrollment: 1 }) upon reservation, maintaining real-time capacity thresholds.
- Client-side optimistic feedback combined with server validation blocks unauthorized administrative bookings or over-capacity entries.
3. Stripe Checkout & Financial Auditing
- End-to-end checkout flow built on Stripe Checkout Sessions.
- Captures and logs every successful transaction (transaction ID, class ID, amount, currency, timestamp) in a dedicated transactions ledger.
- Express admin endpoints calculate aggregate gross revenue on-demand using MongoDB
$group pipelines.
4. In-App Streaming AI Fitness Coach
- Powered by Google Gemini (
gemini-3.5-flash-lite) integrated through the Vercel AI SDK (@ai-sdk/google and ai/streamText).
- Optimized TTFT: Sub-1.5-second Time-To-First-Token performance.
- Domain Guardrails: Strict system prompting restricts the assistant to exercise mechanics, split programming, nutritional guidance, and direct deep-linking to FitPulse classes, rejecting out-of-scope queries.
5. Community Protocol & Discussion Forum
- Rich community feed supporting structured training logs, categorization, and full-text search.
- Thread interactions feature atomic array modifications (
$addToSet and $pull) for mutual exclusivity between likes and dislikes.
- Real-time comment threading tied to author role badges (
admin, trainer, student).
Technical Challenges & Solutions
Challenge 1: Cross-Origin Token Validation Without Shared Sessions
- Problem: Storing session IDs in HTTP-only cookies on the Next.js domain prevented the external Express server from reading user context without complex cookie forwarding or database queries.
- Solution: Implemented JWT plugin emission in Better Auth and verified incoming headers using
jwtVerify(token, JWKS). The Express server caches the JWKS public keys in memory and validates signatures locally. If a token is revoked or tampered with, the request is rejected immediately.
Challenge 2: Eliminating Route Flashing & Unauthorized Role Access
- Problem: In single-page applications, client-side route guarding causes content layout shifts or brief flickers of protected screens before redirecting.
- Solution: Engineered server-side routing guards in
src/proxy.js. Requests to /dashboard/* evaluate the encrypted session cookie on the server prior to rendering HTML. Non-authenticated users or users with invalid roles are redirected with redirectUrl preserved before any client bundle downloads.
Challenge 3: Eliminating Double Bookings During Concurrent Requests
- Problem: Rapid multi-clicking on booking buttons could lead to duplicate entries for the same student in a single class session.
- Solution: Implemented a composite query check prior to document creation, coupled with UI button state lockouts and server-level rejection (
400 Already booked this class) if an active document exists with matching classId and userEmail.
Key Metrics & Engineering Outcomes
- 100% Stateless Backend Auth: Zero database queries required for user identity validation on protected Express API routes.
- Sub-1.5s AI Latency: Replaced heavy reasoning models with
gemini-3.5-flash-lite stream responses for instant coach suggestions.
- Decoupled Deployment Pipeline: Independent deployment of frontend (Vercel) and backend microservice without version lock-in or shared code dependencies.
- Strict Role Segregation: Complete coverage across 20+ API endpoints guarding administrative, trainer, and student workflows.