Mehfil — Architecture & Implementation Guide
This document serves as the primary knowledge base for the Mehfil application. It details the architecture, authentication flow, and backend-frontend integration. Any AI agent or developer working on this project should read this document to understand the established patterns before making changes.
1. High-Level Architecture
The application is built using a hybrid Next.js/Express architecture and uses MongoDB Atlas as the primary database. To ensure security and support multiple client applications (web and mobile), the architecture is strictly decoupled into a distinct backend REST API and frontend clients.
Directory Structure (web-mehfil)
src/
├── app/ # (Frontend) Next.js 14+ App Router
│ ├── api/ # (Backend proxy) Next.js route handlers that forward/mount Express
│ ├── admin/ # (Frontend) Admin portal UI pages
│ ├── venue/ # (Frontend) Venue Owner/Staff portal UI pages
│ └── user/ # (Frontend) Customer portal UI pages
│
├── server/ # (Backend) Core Express.js backend logic. Never imported into client components.
│ ├── config/ # Database initialization (Mongoose)
│ ├── controllers/ # Business logic (CRUD operations)
│ ├── middlewares/ # Authentication and RBAC (`protect`, role checks)
│ ├── models/ # TypeScript interfaces and MongoDB Mongoose schemas
│ └── routes/ # Express routers mapping to controllers
│
├── lib/ # (Frontend) Client-side utilities
│ ├── api-client.ts # Configured fetch wrapper for the web frontend
│ └── api/ # API integration layer for frontend hooks
│
└── components/ # (Frontend) Shared React components (UI, AuthContext)
2. Authentication System & Unified Login
Because the application serves distinct user types, it maintains separate database collections but exposes Unified Authentication Endpoints to simplify client integrations (especially for the Mobile App).
Database Collections
- Admin Users:
adminsMongoDB collection (Super Admins, Venue Owners, Venue Staff). - Customers:
usersMongoDB collection. - Login Mechanism: Email and Password (hashed with
bcrypt) or Google OAuth. - Session Management: Secure JWT Bearer tokens stored in client-side storage (e.g., localStorage or AsyncStorage).
Unified Authentication Endpoints
To avoid forcing client applications (like the Expo mobile app) to guess the user's role before logging in, the backend exposes unified endpoints:
POST /auth/unified/loginPOST /auth/unified/google
How it works:
- The backend securely queries the privileged
Admincollection first. If it finds an Admin or Venue Owner, it authenticates them and issues their privileged role token. - If the user isn't found in the
Admincollection, the backend effortlessly falls back to checking the standardUser(Customer) collection. - This allows all users, regardless of their role, to log in from a single, unified screen.
3. Client API Integration
The frontends (both Web and Mobile) never query the database directly. Instead, they communicate exclusively through the REST API.
Frontend Abstraction (src/lib/api/)
To organize frontend data fetching, files inside src/lib/api/*.ts (e.g., venues.ts, bookings.ts) act as an abstraction layer for the Next.js web application.
- They contain functions that utilize
apiFetch('/api/v1/...')to communicate with the backend. - Rule: If you need to fetch data in a React Component, use these helpers. Do not write raw
fetchcalls directly inside components.
Mobile App (Expo) Integration
The mobile app (mehfil) implements Role-Based Access Control (RBAC) via Expo Router with completely segregated trees (/admin, /venue-owner, /venue-staff, /user).
- Data fetching is handled by heavily modularized custom hooks (
src/hooks/useVenue.ts,src/hooks/useAdmin.ts, etc.) using TanStack Query (React Query) for aggressive caching and optimized performance.
4. How to Add New Features
When adding new data entities or features, follow this strict pipeline to maintain the decoupled architecture.
Step 1: Backend Model & Controller
- Create a Mongoose schema in
src/server/models/[entity].model.tsdefining the structure. - Create business logic and CRUD operations in
src/server/controllers/[entity].controller.ts.
Step 2: Backend API Route
- Expose the controller in a new Express router
src/server/routes/[entity].routes.ts. - Secure the routes using
protectmiddleware fromauth.middleware.tsfor authentication and role verification. - Mount the new router in the main server entry point.
Step 3: Frontend Integration
- Web App: Create or update the corresponding file in
src/lib/api/[entities].tsto call the new API endpoint. - Mobile App: Create or update a custom hook in
src/hooks/using@tanstack/react-queryto consume the API.
5. Important Gotchas & Rules
- Pagination: Implement strictly on all APIs dealing with arrays. Use
pageandlimitquery params. The frontend uses Infinite Loading patterns for performance. - Role Map: The system uses 4 distinct roles:
"admin","venue","venue_staff", and"customer". Make sure any frontend dropdowns or route protections account for"venue_staff"(which has read-only access limited to their specificvenueId). - Google OAuth: Do not create explicit Admin users via Google OAuth initially. Admins must be invited/created by a Super Admin via the dashboard. However, once created, Admins can log in via Google using the unified login endpoints if their Google email matches their Admin account email.