003 Comprehensive Plan for Mobile Frontend

Plan for Mobile Frontend Development

Executive Summary

This document outlines a comprehensive, phased development plan for building a modern, mobile-first Next.js frontend application that integrates with the existing C# backend (Erpcrystal_chs). The new application will use Firebase for authentication, Next.js 14+ with App Router, Tailwind CSS, and shadcn/ui for the UI layer. The architecture is designed to minimize changes to the existing C# application while providing a robust, production-ready mobile experience.

The plan is structured in three phases: Proof of Concept (POC) to establish feasibility, Version 0 (v0) as a minimal viable product with core functionality, and Phase 3 for progressive feature building. Throughout all phases, the existing C# Blazor application will continue running without disruption, with changes isolated to a minimal JWT processing service.


1. Current Architecture Analysis

1.1 Existing System Overview

The Erpcrystal_chs application is a mature, production-ready system built on a three-project .NET 9.0 architecture:

ErpCrystal_CHS.Web (Blazor Server) serves as the current frontend, utilizing MudBlazor v6.9.0 for UI components and Azure AD B2C for authentication. This application handles multi-tenant database routing through a URL parameter pattern where each API call includes the database name as a route parameter. The web project maintains approximately 100+ service methods that coordinate data operations between the frontend and backend.

ErpCrystal_CHS.Api (ASP.NET Core Web API) provides the backend functionality through 60+ controllers covering member management, invoicing, vouchers, financial reports, GST reports, bank reconciliation, vendor management, investment tracking, and various utilities. The API currently uses a custom ApiKeyAuth attribute for security, with the API key passed in request headers. Database access is handled through Dapper 2.0.123, a lightweight micro-ORM that executes raw SQL queries efficiently.

ErpCrystal_CHS.Models contains the data transfer objects and entity models used across both the web and API projects. This shared library ensures type consistency throughout the application.

1.2 Current Database Architecture

The system employs a multi-tenant database architecture with three database layers. The System Database (ERPCrystalChs) contains client database mappings and configuration, storing the relationship between client identifiers and their corresponding SQL Server instances. The Common Database (ERPCrystalCommon) holds shared reference data used across all tenants. Each Client Database operates as an isolated per-customer database containing that specific client’s business data.

The DapperContext class handles the database resolution logic by first querying the System Database to obtain the SQL Server name for a given database name, then reading server configuration from appsettings.json, and finally constructing and returning a connection string for the target client database.

1.3 Current Authentication Flow

The current authentication mechanism operates through Azure AD B2C for user identity, combined with API key validation for backend security. When a user authenticates, Azure AD B2C issues tokens that identify the user. After authentication, users select their target database from a UI dropdown, and this selection is passed to API calls as a URL parameter. The API validates the request using the API key header and processes the database name from the URL to route queries to the appropriate client database.

1.4 Key Technical Characteristics

The existing system demonstrates several important characteristics that influence the migration strategy. The application is production-stable with extensive business logic accumulated over years of development. The API follows RESTful conventions with database names embedded in URL paths. The codebase uses a service-repository pattern that provides clear separation of concerns. Database connections are dynamically resolved at runtime based on the provided database name.


2. Proposed Target Architecture

2.1 High-Level Architecture

The new mobile frontend will operate alongside the existing Blazor application, sharing the same API backend but introducing Firebase as the authentication provider. The architecture consists of four primary layers. The Presentation Layer uses Next.js 14+ with App Router, providing server-side rendering, static generation, and API routes. The UI Layer implements Tailwind CSS for styling and shadcn/ui for accessible, composable components, optimized for mobile-first design. The Authentication Layer leverages Firebase Authentication to manage user identity, with custom claims containing the database name that are passed to the C# backend via JWT tokens. The API Layer continues using the existing C# ASP.NET Core Web API with minimal modifications to add JWT processing.

2.2 Technology Stack

Frontend Technologies:

  • Next.js 14+: Provides the React framework with App Router, enabling server components, streaming, and optimized performance
  • TypeScript: Ensures type safety across the codebase
  • Tailwind CSS: Utility-first CSS framework for responsive, mobile-first designs
  • shadcn/ui: Component library built on Radix UI primitives, fully customizable and themeable
  • TanStack Query (React Query): Handles server state management, caching, and data synchronization
  • Zustand: Lightweight state management for client-side application state
  • Firebase SDK: Handles authentication and token management
  • React Hook Form + Zod: Form handling with schema validation

Backend Modifications:

  • JWT Processing Middleware: Minimal middleware to extract database name from Firebase JWT claims
  • HttpContext Integration: Makes database name available to repositories without modifying controller signatures
  • Tenant Resolution Architecture (Authoritative): Tenant resolution is a backend responsibility and must never depend on client-supplied values. The system uses Firebase JWT custom claims as a tenant signal, but the final tenant-to-database resolution is validated against the System Database on every request. A per-request TenantContext object is created during middleware execution and is the sole source of truth for database connection resolution. Clients (including Next.js) must never explicitly pass database or tenant information via headers, query strings, or request bodies.

2.3 Authentication Flow

The new authentication flow introduces Firebase while maintaining compatibility with the existing system. Users authenticate through the Next.js application using Firebase Authentication (email/password or other providers). Upon successful authentication, Firebase issues a JWT token containing custom claims, including the database name. The Next.js application includes this JWT in the Authorization header of all API requests. The C# API middleware validates the JWT, extracts the database name claim, and makes it available for database resolution. The DapperContext uses this extracted database name to establish the correct client database connection, completing the request transparently.

This approach eliminates the need to pass the database name as a URL parameter while maintaining the existing repository and controller logic with minimal modifications. The database name is derived from Firebase JWT custom claims and validated against the System Database by the backend before any database connection is created. JWT claims are treated as a trusted signal but not as the sole authority for tenant resolution.

2.4 Multi-Tenant Data Flow

The multi-tenant architecture remains unchanged at the database level. The System Database continues maintaining client-to-server mappings. Each Client Database continues storing isolated business data. The DapperContext continues resolving database connections using the same logic, but the database name now originates from JWT claims instead of URL parameters. At no point is a null, missing, or invalid tenant allowed to reach repository or data-access code. Requests lacking a resolvable tenant context must fail fast with an HTTP 401 response.

2.5 PWA Configuration

The Next.js application will be configured as a Progressive Web Application to enable home screen installation on mobile devices. This includes a web app manifest defining the application name, icons, theme colors, and display mode. Service workers provide offline caching for static assets and potentially API responses (though offline functionality is not a requirement, the caching infrastructure improves performance). The application will be configured for standalone display mode to provide an app-like experience without browser chrome.


3. Phased Implementation Plan

3.1 Phase 1: Proof of Concept (POC) - Feasibility Establishment

Duration: 2-3 weeks

Objective: Validate the technical feasibility of integrating Next.js with the existing C# API using Firebase JWT authentication, and confirm that database name extraction from JWT claims works correctly.

Scope:

The POC will focus on a single, representative API endpoint to demonstrate the entire flow. The team will implement the JWT processing middleware in the C# API, create a minimal Next.js application with Firebase authentication, build one API route in Next.js that calls the C# backend with JWT auth, and verify the complete authentication and data flow.

Deliverables:

  1. C# API Changes:

    • JwtDbNameExtractorMiddleware.cs: Middleware component that reads the Authorization header, validates the JWT (using Firebase public keys), extracts the database name claim, and stores it in HttpContext.Items
    • Modified DapperContext: Updated to optionally read database name from HttpContext when available, falling back to URL parameter for backward compatibility
    • appsettings.json update: Firebase project configuration (project ID, validation settings)
  2. Next.js Application Setup:

    • Next.js 14+ project initialized with TypeScript
    • Firebase SDK configured for authentication
    • Basic layout implementing mobile-first responsive design with Tailwind CSS
    • Login page with Firebase email/password authentication
    • Dashboard page demonstrating authenticated state
  3. Integration Verification:

    • One working API call from Next.js to C# API using JWT authentication
    • Database name correctly extracted from JWT claims
    • Data successfully returned from the C# API
    • Error handling for invalid or missing tokens

Success Criteria:

  • Firebase authentication successfully issues JWT tokens with database name claims
  • C# API middleware correctly extracts database name from JWT
  • Data flows end-to-end from C# database through API to Next.js UI
  • No modifications to existing API controller logic required
  • The existing Blazor application continues functioning without any changes

Risks and Mitigation:

The primary risk involves JWT validation complexity. Firebase JWTs use specific formats and may require key rotation handling. Mitigation involves using the Firebase Admin SDK or manually validating against Firebase public keys. Another risk is middleware execution order, as the JWT middleware must execute before endpoint routing. Mitigation requires careful placement in the middleware pipeline.

Testing Strategy:

Manual testing of the complete authentication and data flow. Verification that existing Blazor application API calls continue working (backward compatibility).


3.2 Phase 2: Version 0 (MVP) - Core Foundation

Duration: 4-6 weeks

Objective: Establish the production-ready foundation of the mobile application with essential infrastructure, authentication, and core architectural patterns implemented.

Scope:

Build out the complete application infrastructure including routing, state management, API client layer, and authentication flow. Implement the JWT middleware across all C# API endpoints with backward compatibility. Create a polished mobile UI shell with navigation optimized for touch interactions. Implement the first business module (to be determined based on POC learnings and business priorities).

Deliverables:

  1. C# API Enhancements:

    • Production-ready JWT middleware with proper error handling and logging
    • Updated DapperContext with dual-mode database name resolution (JWT or URL parameter)
    • All API controllers continue working without modification
    • Comprehensive JWT validation including expiration, signature, and claim structure validation
  2. Next.js Application Foundation:

    • Next.js App Router structure with well-organized folder hierarchy
    • Authentication context and hooks (useAuth, useSession)
    • Protected route wrapper component for authenticated pages
    • TanStack Query configuration with API client setup
    • Zustand store for application state (user preferences, UI state)
    • API service layer abstracting backend calls
  3. UI Component Library:

    • Tailwind CSS configuration with design tokens
    • shadcn/ui components installed and configured (Button, Card, Input, Form, Dialog, etc.)
    • Custom mobile-optimized components (bottom navigation, swipe gestures, touch-friendly controls)
    • Responsive layout system working across mobile, tablet, and desktop
    • Dark/light theme support
  4. PWA Configuration:

    • manifest.json configuration for home screen installation
    • Service worker for asset caching
    • Icons and splash screen configurations
    • iOS meta tags for web app capability
  5. First Business Module:

    • Implementation of one complete business feature (e.g., member list, dashboard summary)
    • Full CRUD operations against C# API
    • Form validation using React Hook Form and Zod
    • Loading states, error handling, and empty states
    • Pull-to-refresh for data updates

Technical Implementation Details:

The API client layer will use a typed axios instance with interceptors for JWT injection and error handling. All API calls will go through this client with automatic token refresh logic. The state management will use TanStack Query for server state (caching, background updates, optimistic updates) and Zustand for client state (user preferences, UI state, modals). The authentication context will provide Firebase auth state, token management, and user claims extraction.

The folder structure will follow the Next.js App Router conventions with app/ containing routes, components/ holding reusable UI components, lib/ storing utilities and API clients, hooks/ containing custom React hooks, and types/ defining TypeScript interfaces.

Success Criteria:

  • All API calls from Next.js use JWT authentication with database name in claims
  • Existing Blazor application API calls continue working without modification
  • Application installs as PWA on mobile devices
  • First business module is functional with full CRUD operations
  • Application is responsive and provides good UX on mobile devices
  • CI/CD pipeline is established for automated builds

Testing Strategy:

Unit tests for utility functions and hooks using Vitest. Integration tests for API service layer. Component tests using React Testing Library. End-to-end testing with Playwright for critical user flows.


3.3 Phase 3: Progressive Feature Building

Duration: Ongoing (estimated 3-6 months for significant feature set)

Objective: Incrementally build out additional business modules and features based on prioritized requirements, following the architectural patterns established in Phase 2.

Scope:

Implement additional business modules based on business priorities and user feedback. Enhance the application with advanced features like advanced search, filtering, reporting, and notifications. Optimize performance for real-world usage. Expand test coverage and improve code quality metrics.

Feature Categories (prioritized based on business value):

Category A - High Priority (Months 1-2):

  • Member management module (list, detail, create, edit, delete)
  • Dashboard with key metrics and quick actions
  • Authentication with additional providers (if needed)
  • Basic reporting (summary views)

Category B - Medium Priority (Months 2-4):

  • Invoice management and viewing
  • Transaction history
  • Advanced search and filtering
  • Document viewing (PDFs, images)
  • Notification system

Category C - Lower Priority (Months 4-6):

  • Comprehensive reporting with charts
  • Export functionality (PDF, Excel)
  • Multi-language support
  • Advanced workflows (approvals, routing)
  • Analytics integration

Implementation Approach:

Each feature will follow a consistent implementation pattern. The team will create API service methods for backend communication, build React components using shadcn/ui and custom components, implement forms with validation using React Hook Form and Zod, add TanStack Query hooks for data fetching and mutations, and create pages/routes in the Next.js App Router.

Code Quality Standards:

  • Maintain test coverage above 80% for new code
  • Follow established component patterns and conventions
  • Document API integrations and complex logic
  • Participate in code reviews for all changes
  • Monitor performance using web vitals and custom metrics

Backlog Management:

Features will be prioritized in a product backlog, refined before each sprint, and implemented in two-week sprints with regular reviews. The team will gather user feedback after each release to inform subsequent priorities.


4. C# Backend Modification Strategy

4.1 Principles

All C# modifications must adhere to the principle of minimal change to maintain stability. The existing API should continue functioning exactly as before for the Blazor application while enabling the new Next.js application to work with JWT authentication.

4.2 Tenant Context Resolution (No-Crash Contract)

All tenant resolution logic is centralized in middleware and executed exactly once per request.

The backend enforces the following rules:

  1. Every data-access request must have a resolved TenantContext
  2. TenantContext is created during middleware execution
  3. Controllers and services are forbidden from resolving tenants
  4. Repositories may not execute without TenantContext
  5. Missing or invalid tenant resolution must return HTTP 401 (never 500)

The TenantContext contains:

  • TenantCode
  • DatabaseName
  • Resolution status

This contract guarantees that database connection logic never crashes due to authentication or token changes.

4.3 No Changes Required

The following will not require any changes: All 60+ API controllers will continue using their existing signatures and logic. All 100+ service methods in the Blazor project will continue passing database names as before. The API key authentication mechanism remains in place as an additional security layer.

DapperContext is modified only to consume the resolved TenantContext. It must not infer, derive, or guess tenant information from request data. If TenantContext is missing or invalid, DapperContext must fail fast.

4.4 Backward Compatibility

The dual-mode database name resolution ensures that existing API calls from the Blazor application continue working. When a request comes in without a valid JWT (or with the traditional API key approach), the system falls back to extracting the database name from the URL parameter. This means the Blazor application requires no modifications.


5. Firebase Integration Details

5.1 Firebase Project Configuration

The existing Firebase project will be used, with the user object containing the database name. This configuration requires setting up Firebase Authentication with the desired sign-in methods (email/password, etc.). Custom claims will be configured to include the database name for each user.

Firebase is the system of record for user identity only. Tenant-to-database mapping authority remains with the backend System Database. Firebase metadata and custom claims are derived from this mapping and used for optimization and identity portability.

5.2 Custom Claims Structure

Each Firebase user will have custom claims structured as follows: the database name will be stored in a claim key (e.g., “dbname”) containing the tenant identifier. Additional claims may be added for role-based access control if needed in the future.

Custom claims are treated as a cached representation of tenant mapping. Claims are validated against backend mappings on each request. Stale or mismatched claims are refreshed asynchronously without blocking request processing.

5.3 JWT Token Flow

The authentication flow will proceed as follows: the user logs in through the Next.js application using Firebase SDK, Firebase returns a JWT token containing custom claims including the database name, the Next.js application includes this token in the Authorization header of API requests (Bearer token format), the C# API middleware validates the token using Firebase public keys, extracts the database name claim, and stores it in HttpContext.Items for use by DapperContext.

5.4 Token Refresh

The Next.js application will handle token refresh automatically using Firebase’s onAuthStateChanged listener and getIdTokenResult for obtaining current tokens. The API client interceptor will ensure fresh tokens are included with each request.

5.5 Claim Staleness & Self-Healing

The backend must tolerate stale or missing Firebase claims.

If a mismatch is detected between JWT claims and backend tenant mapping:

  • The backend proceeds using the authoritative mapping
  • Firebase claims are refreshed asynchronously
  • The request is not failed unless tenant resolution is impossible

6. PWA Implementation Details

6.1 Web App Manifest

The manifest.json file will define the application identity and installation behavior. The name will be set to “CHS Mobile” or similar, with a short name for home screen display. The start_url will point to the application’s root. The display mode will be “standalone” for app-like appearance. Icons will be provided at multiple sizes (192x192, 512x512) for different device requirements. Theme colors will match the application’s color scheme. Background color will be defined for splash screen appearance.

6.2 Service Worker

The service worker will implement caching strategies for optimal performance. Static assets (JavaScript, CSS, images) will be cached with a cache-first strategy for instant loading. API responses may be cached with a network-first strategy for data freshness. The service worker will be registered during the application’s startup process.

6.3 iOS Support

iOS requires specific meta tags in the Next.js head component for web app capability. These include apple-mobile-web-app-capable, apple-mobile-web-app-status-bar-style, and apple-mobile-web-app-title. Icons will be linked as apple-touch-icon for home screen addition.

6.4 Mobile Optimization

The application will be designed mobile-first with specific considerations. Touch targets will be sized at least 44x44 pixels for comfortable tapping. Swipe gestures will be implemented for common actions like navigation and list operations. Form inputs will use appropriate input types (email, tel, number) for mobile keyboards. Viewport configuration will prevent horizontal scrolling and zooming issues.


7. State Management Strategy

7.1 Server State with TanStack Query

TanStack Query will manage all server-side state including data from the C# API. This includes data fetching with automatic caching and background refetching, mutation operations with optimistic updates, query invalidation for cache coherence, and loading and error state management. The configuration will use sensible defaults with custom settings for specific queries.

7.2 Client State with Zustand

Zustand will manage client-side application state that doesn’t come from the server. This includes user preferences (theme, language, display options), UI state (modals, sidebars, notifications), authentication state (though Firebase SDK handles most of this), and form draft state for persistence across navigations.

7.3 Separation of Concerns

The state management architecture maintains clear boundaries. TanStack Query handles data synchronization with the backend, caching, and server state. Zustand handles ephemeral client state and user preferences. React Context handles component tree global state like auth providers. Local component state handles UI-specific temporary state.


8. Development Workflow

8.1 Repository Structure

The repository will maintain a clean structure separating concerns. The Chsmobileversion folder will contain the Next.js application. The Erpcrystal_chs folder will remain unchanged (production application). Documentation will be maintained in markdown files within the repository.

8.2 Environment Configuration

Environment variables will be managed through .env files and Next.js environment variables. Development environment will point to development/staging API endpoints. Production environment will point to production API endpoints. Firebase configuration will be provided through environment variables.

8.3 CI/CD Pipeline

The CI/CD pipeline will include the following stages: linting and type checking, unit testing, build verification, and deployment to Firebase Hosting. The pipeline will run on every pull request and push to main branch.

8.4 Code Review Process

All changes will go through pull request review. Changes to C# code require special attention to maintain stability. Documentation will be updated alongside code changes.

8.5 Tenant Resolution Failure Handling

Tenant resolution failures are treated as authentication failures.

Failure modes:

  • Missing JWT → 401 Unauthorized
  • Invalid JWT → 401 Unauthorized
  • Unmapped Firebase UID → 401 Unauthorized
  • Invalid tenant mapping → 401 Unauthorized

Under no circumstances should tenant resolution failures result in application crashes or HTTP 500 errors.


9. Risk Assessment and Mitigation

9.1 Technical Risks

Risk: JWT validation complexity and security concerns.

Mitigation: Use Firebase Admin SDK or well-tested JWT validation libraries. Implement proper error handling for invalid tokens. Log authentication failures for debugging.

Risk: Database connection issues from JWT-based resolution.

Mitigation: Implement comprehensive logging in DapperContext. Create thorough testing for database resolution paths. Maintain backward compatibility as fallback.

Risk: Performance degradation from JWT validation on every request.

Mitigation: Implement token caching in the middleware. Use efficient JWT validation algorithms. Consider distributed caching if needed.

9.2 Operational Risks

Risk: Changes to C# API affecting production Blazor application.

Mitigation: Deploy C# changes to staging environment first. Run regression tests against Blazor application. Implement feature flags for JWT middleware. Roll back capability within minutes.

Risk: Firebase authentication downtime.

Mitigation: Implement proper error handling and user messaging. Consider alternative authentication fallback if needed. Monitor Firebase service status.

9.3 Scope Risks

Risk: Feature creep during Phase 3.

Mitigation: Maintain strict prioritization. Use sprint planning to define scope. Communicate scope boundaries clearly to stakeholders.


10. Timeline Summary

Phase Duration Key Deliverables
Phase 1: POC 2-3 weeks JWT middleware, basic Next.js app, one API integration
Phase 2: v0 4-6 weeks Production app foundation, first business module, PWA
Phase 3 3-6 months Progressive feature building based on prioritization

11. Success Metrics

11.1 Technical Metrics

  • API response times within acceptable thresholds (under 500ms for typical queries)
  • Lighthouse performance score above 90
  • Test coverage above 80% for new code
  • Zero critical security vulnerabilities

11.2 User Metrics

  • Task completion rate for core workflows
  • User satisfaction scores from feedback
  • App store rating (if applicable)
  • PWA installation rate

11.3 Operational Metrics

  • Uptime of Next.js application
  • API error rate
  • Deployment frequency and lead time
  • Time to resolve production issues

12. Next Steps

Upon approval of this plan, the team should proceed with the following immediate actions:

  1. Set up the development environment with Next.js project initialization
  2. Access Firebase project configuration for the new application
  3. Create a staging environment for C# API testing
  4. Begin Phase 1 POC implementation with JWT middleware development
  5. Establish CI/CD pipeline for automated builds

13. Architecture Decision Record

ADR-001: Tenant Resolution via Firebase JWT with Backend Validation

Status: Accepted

Decision: The system resolves tenant context using Firebase JWT custom claims validated against the System Database. A per-request TenantContext is created and enforced by middleware. Clients do not supply tenant or database identifiers.

Consequences:

  • Supports modern authentication
  • Preserves legacy Blazor compatibility
  • Prevents cross-tenant data access
  • Guarantees no-crash behavior during authentication transitions

This plan provides a comprehensive roadmap for building the mobile frontend while maintaining the stability of the existing production application. The phased approach allows for learning and adjustment while delivering value incrementally.