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: admins MongoDB collection (Super Admins, Venue Owners, Venue Staff).
  • Customers: users MongoDB 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:

  1. POST /auth/unified/login
  2. POST /auth/unified/google

How it works:

  1. The backend securely queries the privileged Admin collection first. If it finds an Admin or Venue Owner, it authenticates them and issues their privileged role token.
  2. If the user isn't found in the Admin collection, the backend effortlessly falls back to checking the standard User (Customer) collection.
  3. 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 fetch calls 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

  1. Create a Mongoose schema in src/server/models/[entity].model.ts defining the structure.
  2. Create business logic and CRUD operations in src/server/controllers/[entity].controller.ts.

Step 2: Backend API Route

  1. Expose the controller in a new Express router src/server/routes/[entity].routes.ts.
  2. Secure the routes using protect middleware from auth.middleware.ts for authentication and role verification.
  3. Mount the new router in the main server entry point.

Step 3: Frontend Integration

  1. Web App: Create or update the corresponding file in src/lib/api/[entities].ts to call the new API endpoint.
  2. Mobile App: Create or update a custom hook in src/hooks/ using @tanstack/react-query to consume the API.

5. Important Gotchas & Rules

  • Pagination: Implement strictly on all APIs dealing with arrays. Use page and limit query 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 specific venueId).
  • 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.