Platform Documentation
Complete technical reference for the House of Transformation Church management and engagement platform.
Project Overview
House of Transformation (H.O.T) is a full-stack church management and community engagement platform built for a church congregation in Busia County, Kenya. It serves two primary audiences through a single unified system:
- Public visitors — who access the church's website to discover services, watch livestreams, read sermons and blog posts, register for events, submit feedback, and make donations.
- Authenticated members and staff — who use a role-gated portal to manage all platform content, moderate community interaction, and administer the organization.
| Application | Technology | Deployment |
|---|---|---|
| Frontend (public site + portal) | Next.js App Router | Netlify |
| Backend API | Node.js + Express | Render / Railway |
System Purpose and Goals
Primary Purpose
Provide the church with a self-managed digital infrastructure that replaces fragmented tools (separate admin panels, third-party form services, manual spreadsheets) with a single integrated platform.
Public Engagement
SEO-optimized public website with structured data, fast SSR pages, PWA installability
Member Self-Service
Portal with profile management, saved sermons, announcement access
Content Management
Admin-managed blog, sermons, events, gallery, and livestreams
Financial Transparency
Donation campaigns with progress tracking, M-Pesa integration, pledge system
Community Feedback
Five-category feedback system with anonymous submission and moderation
Mobile Accessibility
Fully responsive UI, PWA installability, mobile-optimized portal
Key Platform Features
Public Website Features
Portal Features (Role-Based Access)
Technology Stack
Frontend
Backend
Infrastructure
High-Level System Architecture
┌──────────────────────────────────────────────────────────────────┐
│ CLIENT BROWSER │
│ │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Next.js Application │ │
│ │ │ │
│ │ ┌──────────────────────┐ ┌──────────────────────────────┐ │ │
│ │ │ Public Site │ │ Member Portal │ │ │
│ │ │ /(public) │ │ /portal/* │ │ │
│ │ │ │ │ │ │ │
│ │ │ SSR pages (SEO) │ │ CSR only, auth-gated │ │ │
│ │ │ CSR pages (dynamic) │ │ role-filtered sidebar │ │ │
│ │ └──────────┬───────────┘ └──────────────┬───────────────┘ │ │
│ │ │ │ │ │
│ │ └──────────────┬──────────────┘ │ │
│ │ │ │ │
│ │ ┌────────▼────────┐ │ │
│ │ │ AuthContext │ │ │
│ │ │ (Supabase JS) │ │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ ┌────────▼────────┐ │ │
│ │ │ Axios (api.js) │ │ │
│ │ │ JWT injection │ │ │
│ │ │ 401 refresh │ │ │
│ │ └────────┬────────┘ │ │
│ └────────────────────────────│────────────────────────────────┘ │
└───────────────────────────────│──────────────────────────────────┘
│
┌───────────▼────────────┐
│ HTTPS REST API │
│ + SSE (/stream) │
└───────────┬────────────┘
│
┌───────────────────────────────▼──────────────────────────────────┐
│ Node.js / Express Server │
│ │
│ Trust Proxy → Body Parser → CORS → Audit Middleware → Limiter │
│ ↓ │
│ ┌──────────────┐ ┌──────────────┐ ┌────────────────────────┐ │
│ │ Public Routes│ │ Mixed Routes │ │ Protected Routes │ │
│ │ (no JWT) │ │ (optionalAuth│ │ (protect + requirePerm)│ │
│ │ │ │ protectSSE) │ │ │ │
│ └──────┬───────┘ └──────┬───────┘ └───────────┬────────────┘ │
│ └─────────────────┴──────────────────────┘ │
│ │ │
│ Controllers → Services → Models │
│ │ │
│ Error Handler (global, last) │
└────────────────────────────┬─────────────────────────────────────┘
┌──────────────┼──────────────────┐
│ │ │
┌──────────▼───┐ ┌───────▼──────┐ ┌────────▼──────────┐
│ MongoDB Atlas│ │ Supabase │ │ Cloudinary CDN │
│ (content, │ │ (auth, │ │ (images, │
│ users, │ │ idempotency│ │ gallery) │
│ roles, │ │ keys) │ │ │
│ audit) │ └──────────────┘ └───────────────────┘
└──────────────┘
│
┌──────────▼────────────┐
│ Safaricom Daraja API │
│ (M-Pesa STK Push) │
└───────────────────────┘Frontend Architecture
The Next.js App Router organizes the application into two route groups serving distinct audiences while sharing common infrastructure:
Application Structure
src/app/ ├── (public)/ ← Public website, mixed SSR/CSR │ ├── layout.jsx ← NoticeBar + Header + Footer + Chatbot │ └── page.jsx ← Homepage (SSR) ├── portal/ ← Member portal, all CSR │ ├── layout.jsx ← Auth check + sidebar + portal header │ └── page.jsx ← Dashboard ├── auth/callback/ ← Supabase OAuth callback ├── maintenance/ └── layout.jsx ← Root: providers, fonts, metadata
Context Providers
The root layout wraps the application in a layered provider tree:
State Architecture
Backend Architecture
Middleware Execution Order
- 01.app.set('trust proxy', 1) // reads real IP behind proxy
- 02.express.json() // parses JSON body
- 03.express.urlencoded() // parses form data
- 04.cors(allowedOrigins) // enforces origin whitelist
- 05.app.use('/uploads', static) // serves local upload fallback
- 06.app.use('/api', auditMiddleware)// logs all API requests
- 07.app.use('/api/', apiLimiter) // rate limits all API routes
- 08.routeSpecificAuthMiddleware() // protect / optionalAuth / protectSSE
- 09.requirePermission(...) // enforces permission strings
- 10.asyncHandler() // catches async errors
- 11.Controller()
- 12.Response()
- 13.404 handler // no route matched
- 14.errorHandler // global, last
Service Layer
mpesaService.js
Safaricom Daraja OAuth + STK Push + status query
mpesaVerificationService.js
Callback validation, receipt verification
emailService.js
Nodemailer singleton, SMTP config from Settings
auditService.js
Audit log write helpers (logAuth, logError)
transcriptService.js
YouTube transcript extraction
aiSummaryFromTranscript.js
Claude/Gemini sermon summarization
aiCaptionsService.js
AI-generated gallery photo captions
captionWorker.js
Background job runner for caption generation
Authentication Flow
The platform delegates all identity verification to Supabase. The backend issues no JWTs of its own.
Email / Password Flow
Frontend Supabase Backend (MongoDB)
│ │ │
│── signInWithPassword() ─────────▶ │
│◀─ session { access_token } ─────│ │
│ │ │
│── tokenService.setToken() ───────────────────────────────▶ (stored)
│ │ │
│── GET /api/auth/verify ──────────────────────────────────▶
│ │ supabase.auth.getUser()
│ │◀───────────────────────│
│ │──── verified user ─────▶
│ │ │ User.findOne()
│ │ │ populate role
│◀── { user, role, permissions } ──────────────────────────│Token Lifecycle
- 1Request interceptor injects
Authorization: Bearer <token> - 2
supabaseAuth.protect()validates token with Supabase - 3On 401: refresh token flow triggered, in-flight requests queued and retried
- 4On refresh failure: all tokens cleared, redirect to login
Role-Based Permission System
The permission system is a flat string-based RBAC model. Each user holds one Role. Each role contains an array of permission strings. The admin role bypasses all checks entirely.
Permission String Taxonomy
manage:{resource}Broad, covers all sub-operationsaction:{resource}Specific actionaction:{resource}:{subtype}Most granular levelBroad Permissions
manage:eventsmanage:sermonsmanage:gallerymanage:donationsmanage:usersmanage:rolesmanage:blogmanage:livestreammanage:feedbackmanage:volunteersmanage:settingsmanage:announcementsGranular Examples (Donations)
view:campaignscreate:campaignsedit:campaignsdelete:campaignsactivate:campaignsfeature:campaignsview:pledgesapprove:pledgesview:paymentsprocess:paymentsverify:paymentsBroad Permission Expansion
When requirePermission middleware detects a broad permission like manage:feedback, it automatically expands to all related granular strings. This prevents needing to assign both the broad permission and every individual sub-permission.
Portal Architecture
Unified Portal Principle
There are no separate admin pages. All authenticated users — members and administrators — access the same portal routes. What differs is which sidebar items appear and which actions are available, controlled by the user's role permissions.
/portalDashboard overview
All users
/portal/profileOwn profile management
All users
/portal/bookmarksSaved sermons
All users
/portal/announcementsAnnouncements
All view, manage:announcements edit
/portal/blogBlog management
manage:blog
/portal/sermonsSermon publishing
manage:sermons
/portal/eventsEvent management
manage:events
/portal/galleryGallery management
manage:gallery
/portal/livestreamLivestream control
manage:livestream
/portal/feedbackFeedback moderation
read:feedback:*
/portal/volunteersVolunteer approvals
manage:volunteers
/portal/donationsFinancial management
Any donation perm
/portal/usersUser management
manage:users
/portal/rolesRole configuration
manage:roles
/portal/analyticsPlatform analytics
view:analytics
/portal/settingsSystem configuration
manage:settings
/portal/audit-logsAudit trail
view:audit_logs
Notification Bell (SSE)
The NotificationBell component in the portal header maintains a persistent SSE connection to /api/announcements/stream?token=<jwt>. It displays an unread count badge and increments it on new_announcement events without requiring page reload.
Reconnection uses exponential backoff (base 2s, max 30s, up to 5 attempts). Auth errors halt reconnection permanently. A REST fallback fetches the initial count on mount independently of SSE state.
Public Website Structure
| Route | Rendering | Data Source |
|---|---|---|
| / | SSR | Featured sermon, live status |
| /about | CSR | Static content |
| /blog | SSR | All approved blogs |
| /blog/[id] | SSR | Blog detail by ID |
| /sermons | SSR | Sermon archive |
| /sermons/[id] | CSR | Sermon detail |
| /events | SSR | Upcoming events |
| /events/[id] | CSR | Event detail + registration |
| /gallery | SSR | All photos |
| /donate | SSR | Active campaigns |
| /campaigns/[id] | CSR | Campaign detail, pledges |
| /livestream | CSR | Livestream sessions |
| /feedback | CSR | Feedback forms |
| /volunteer | CSR | Application forms |
| /contact | CSR | Map + contact form |
Database Structure Overview
All data except authentication identities is stored in MongoDB Atlas. Mongoose provides ODM with schema validation, virtuals, hooks, and index management.
usersMember profilessupabase_uid, role (ref), isBanned, authProvider
rolesPermission groupsname, permissions (enum array), isSystemRole
blogsBlog poststitle, content, author, likes, views, category, slug
sermonsSermon entriestitle, type, content, mediaUrl, likes, bookmarks, views
eventsChurch eventstitle, date, capacity, registrations, status
galleryPhotosimageUrl, cloudinaryPublicId, category, likes
feedbackAll feedback typescategory, feedbackData, status, isAnonymous, isDeleted
volunteersApplicationsministry, status, applicant, hours
campaignsDonation campaignsgoalAmount, currentAmount, status, milestones
announcementsSSE-driven noticespriority, targetAudience, readBy, expiresAt
noticesSticky header noticemessage, style, backgroundColor, dismissible
settingsSingleton configemailSettings, paymentSettings, maintenanceMode, features
bannedusersBan recordsemail, ipAddresses, reason, bannedBy
auditlogsAction logaction, userId, ip, method, path, statusCode
livestreamsStream sessionsembedUrl, platform, status, metadata
API Communication
REST Communication
All REST communication goes through the Axios instance in src/lib/api.js.
Request Interceptor
Injects Authorization: Bearer <token> on every outgoing request.
Response Interceptor Logic
- 200-299: Pass through seamlessly.
- 401 (first attempt): Mark as _retry, queue request, attempt token refresh.
- 401 (_retry set): Reject immediately to prevent loops.
- 503: Redirect immediately to /maintenance.
- 429: Surface rate limit error to user (no auto-retry).
Server-Sent Events (SSE)
SSE is used for the announcement notification system only.
Frontend (NotificationBell) Backend (announcementController)
│ │
│── new EventSource('/api/ │
│ announcements/stream?token=...') │
│ │── protectSSE middleware
│ │── add to connections Map
│◀── event: connected ───────────────────│
│◀── event: unreadCount ─────────────────│
│ │
│ [Admin creates announcement] │
│ │── broadcast to all connections
│◀── event: new_announcement ────────────│
│── increment badge count │
│ │
│ [Client disconnects] │
│ │── remove from connections MapLivestream Integration
The platform supports embedding active and archived livestreams from YouTube and Facebook.
How It Works
- 1Admin creates livestream record in portal with embed URL, platform, and status
- 2When status === 'live', homepage LiveStreamSection renders automatically
- 3/livestream page lists all sessions with live one featured at top
- 4Viewers can pop video into Picture-in-Picture mode via PiPContext
Picture-in-Picture (PiP)
PiP state persists across page navigation using a combination of technologies:
- PiPContext — global React context tracking active video
- GlobalPiP.jsx — floating player outside page tree
- usePersistentPiP — persists to IndexedDB via SW
- Service worker — saves state, survives full reloads
Event Registration System
Registration Flow
1. Visitor views event on /events/[id] 2. Clicks "Register" → registration form modal 3. Submits name, email, phone (optional), attendance time slot 4. POST /api/events/:id/register 5. Backend checks: ├── Event status is active ├── Capacity not exceeded └── No duplicate registration for same email 6. Registration record created 7. Confirmation displayed to user
Seat Management
Each event has a capacity field. Backend tracks totalRegistrations, memberRegistrations, and visitorRegistrations separately. When capacity is reached, registration closes automatically.
Portal Event Management
The /portal/events page provides:
- Event CRUD operations
- Full registrant list with details
- Print-ready attendee list
- Registration analytics
Donation Campaign System
Campaign Lifecycle
Campaign Types
Payment Methods
- M-Pesa STK Push
- M-Pesa Paybill
- M-Pesa Till
- Bank Transfer
M-Pesa STK Push Flow
- 01.User enters phone number and amount
- 02.Frontend sends Idempotency-Key (UUID) + POST /api/payments/mpesa/initiate
- 03.Backend loads M-Pesa config from Settings (consumerKey, shortcode, passkey)
- 04.MpesaService.initiateSTKPush() requests OAuth token, generates timestamp and password
- 05.Returns CheckoutRequestID, creates pending payment record
- 06.User receives M-Pesa PIN prompt on phone
- 07.User enters PIN
- 08.Safaricom POSTs callback to /api/mpesa/callback
- 09.MpesaVerificationService validates callback structure
- 10.Re-queries Safaricom to verify transaction independently
- 11.On success (ResultCode === 0): updates payment status + campaign.currentAmount
- 12.On failure: marks payment failed
Feedback and Testimony System
Sermon Feedback
Sermon title/date, 5-star rating, resonated section, application steps
Rating displayService Experience
First-time visitor flag, per-area ratings, improvements
Multi-area ratings gridTestimony
Type, title, story, testimony date, willing to share
Publishable to publicSuggestion
Type, title, priority, description, benefit
Priority badgesPrayer Request
Urgency, category, request, share on prayer list
Urgent animation flagFeedback Lifecycle
Admin Response
When an admin responds to non-anonymous feedback, the system saves the response text, sends an email via emailService to the submitter, updates status to 'responded', and reports email delivery success.
Volunteer Management System
Application Flow
1. Visitor views /volunteer page 2. Selects ministry team (Ushering, Worship, Technical, Children's Ministry, etc.) 3. Fills application form: name, email, phone, experience, motivation, skills 4. POST /api/volunteers/apply 5. Backend checks for existing application from same email for same ministry 6. Application created with status: pending 7. Admin views in /portal/volunteers 8. Admin approves or denies with optional notes 9. On approval: status → approved, volunteer gains access to resources
Portal Management Features
- List all applications with ministry, applicant, status
- Approve/deny actions with optional notes
- Filter by ministry and status
- View volunteer hours (manual entry by admin)
- Volunteer statistics dashboard
- Export volunteer lists
Analytics and Admin Capabilities
The /portal/analytics page (requires view:analytics) provides a tabbed dashboard with six comprehensive views.
Overview
Total users, sermons, donations, events; user distribution; content performance
Users
Total, active, banned, new; breakdown by role, gender, auth provider
Content
Sermon leaderboards by views/likes; top events; gallery top photos; blog stats
Engagement
Feedback stats by category; volunteer stats; livestream analytics
Financial
Campaign progress; pledge fulfillment; payment method breakdown; M-Pesa stats
System
Audit actions, success rate, failed logins, banned users, recent activity
PWA and Service Worker
PWA Manifest
Home Screen Shortcuts
/livestream/sermons/events/donateService Worker Features
- Cache Strategy: Network-first with cache fallback for GET requests
- Cache Versioning: Date.now() timestamp, old caches purged on activate
- Wake Lock: Prevents screen sleep during PiP video playback
- Push Notifications: Push notification support for PiP reminders
- Auto-Update: Polls for SW updates every 60s, seamless reload on new version
SEO Strategy
Metadata System
All SSR pages export a metadata object with title, description, keywords, Open Graph, and Twitter Card data.
title: '%s | Busia House of Transformation Church'Dynamic Sitemap
src/app/sitemap.js generates XML sitemap combining static pages and all approved blog URLs. Blog URLs are revalidated every hour using ISR (revalidate: 3600).
JSON-LD Structured Data
The homepage injects Church schema with address, opening hours, and telephone.
{
"@context": "https://schema.org",
"@type": "Church",
"name": "Busia House of Transformation",
"address": {
"@type": "PostalAddress",
"addressLocality": "Busia Town",
"addressRegion": "Busia County",
"addressCountry": "KE"
},
"openingHours": "Su 09:00-12:00",
"telephone": "+254726793503"
}Image Optimization
next/imagewith AVIF + WebP auto format selection- Remote patterns configured for Cloudinary, YouTube thumbnails
Cache-Control: public, max-age=31536000, immutableon static assets
Security Considerations
Authentication
- All tokens verified with Supabase on every request
- Role permissions populated from MongoDB, never client-injected
- Admin bypass based on database role.name, not token claim
- Refresh tokens are single-use; failure clears all credentials
Ban System
- Banned users deleted from Supabase Auth
- BannedUser records store email and IP address
- Both checked at signup and login
- Admins cannot ban themselves or other admins
Input Security
- isomorphic-dompurify sanitizes HTML before storage
- express-validator validates auth and payment endpoints
- Mongoose schema validation provides database-level enforcement
Payment Security
- M-Pesa callbacks validated for structure
- Re-queries Safaricom after callback for independent verification
- Idempotency keys prevent double-charging
- Credentials runtime-configurable via Settings
File Upload Security
- Cloudinary API secret never exposed to browser
- Gallery deletions routed through backend with server credentials
- File type validation on both frontend and backend
- 5MB file size limit enforced
Rate Limiting
- All API routes: 1000 req / 15 min
- Login: 10 attempts / 15 min
- Signup: 5 attempts / 15 min
- CORS strict origin whitelist in production
Performance Considerations
Frontend Optimizations
Backend Optimizations
Scalability Considerations
Current Architecture Limits
The in-memory SSE connection map does not scale horizontally. Multiple server instances require migration to Redis pub/sub for announcement broadcasts.
Horizontal Scaling Path
- SSE:Replace in-memory map with Redis pub/sub. Each instance subscribes to Redis channel.
- M-Pesa Token:Move to Redis with shared TTL key so all instances share one cached token.
- Database:MongoDB Atlas supports read replicas and sharding. Current schema suitable for shard keys.
- Frontend:Next.js on Netlify scales statically at CDN edge. SSR functions scale via serverless.
Storage Scaling
All media is stored in Cloudinary — no local storage dependencies in production. Gallery, sermon thumbnails, and user avatars all route through Cloudinary CDN, which handles scaling independently.
Deployment Overview
Frontend (Netlify)
# netlify.toml [build] command = "npm run build" [[plugins]] package = "@netlify/plugin-nextjs"
@netlify/plugin-nextjs handles SSR function routing, ISR, and image optimization automatically.
Backend (Node.js Host)
npm start → node server.jsnpm run dev → nodemon server.jsRequirements: NODE_ENV=production, trust proxy: 1, M-Pesa callback must be publicly reachable HTTPS endpoint
First-Time Setup Scripts
node scripts/seedRoles.jsCreates default roles (admin, member, etc.)node scripts/createAdmin.jsCreates initial admin userEnvironment Variables
Frontend (.env.local)
NEXT_PUBLIC_API_URL=https://your-api.onrender.com/api NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME=your-cloud-name NEXT_PUBLIC_CLOUDINARY_UPLOAD_PRESET=user_avatars NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
Backend (../.env)
# Server PORT=5000 NODE_ENV=production FRONTEND_URL=https://your-frontend.netlify.app # MongoDB MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/church_db # Supabase SUPABASE_URL=https://your-project.supabase.co SUPABASE_ANON_KEY=your-anon-key SUPABASE_SERVICE_KEY=your-service-role-key # server-side only # Cloudinary CLOUDINARY_CLOUD_NAME=your-cloud-name CLOUDINARY_API_KEY=your-api-key CLOUDINARY_API_SECRET=your-api-secret # server-side only # M-Pesa (fallback; override via Settings panel) MPESA_CONSUMER_KEY=your-consumer-key MPESA_CONSUMER_SECRET=your-consumer-secret MPESA_SHORTCODE=174379 MPESA_PASSKEY=your-passkey # Email (fallback; override via Settings panel) EMAIL_HOST=smtp.gmail.com EMAIL_PORT=587 EMAIL_USER=your@gmail.com EMAIL_PASS=your-app-password
Security Notice
- ⚠️
SUPABASE_SERVICE_KEYCritical secret, grants admin access to Supabase Auth — server only - ⚠️
CLOUDINARY_API_SECRETRequired for media deletion — server only - ⚠️
MPESA_CONSUMER_SECRETPayment auth — server only
Maintenance Considerations
Scheduled Jobs
utils/cleanupJobs.js runs on server startup:
- Expired idempotency keys (Supabase table, 24-hour TTL)
- Announcements past their expiresAt date
- Overdue campaign status checks
Settings Without Redeployment
The Settings singleton in MongoDB allows updating at runtime without code changes:
Service Worker Updates
The SW auto-updates every 60 seconds in production. When a new deployment occurs, the new SW is detected via updatefound event, and window.location.reload() is triggered after controllerchange. Users receive updates without manual intervention.
Future Improvement Opportunities
Real-Time
- Replace in-memory SSE map with Redis pub/sub for horizontal scaling
- WebSocket upgrade for bi-directional communication
Payment
- Stripe integration (Settings model ready)
- M-Pesa C2B (Paybill direct) implementation
- Automated payment reconciliation job
AI Features
- Auto-captions for all gallery photos with queue
- Sermon transcript search with full-text engine
- Automated sermon summaries published to blog
Content
- Email newsletter system with template builder
- Push notifications for sermons, events, announcements
- Multi-language support (Swahili/English)
Operations
- Centralized logging with structured logger
- Monitoring and alerting for uptime and errors
- Automated testing coverage for auth and payments
Production-Grade Platform
A comprehensive full-stack church management and engagement platform with 30+ routes, 100+ API endpoints, 19 MongoDB collections, 50+ permission strings, and 6 external service integrations.
Built by Bryant
