Comprehensive Next.js Authentication Flow

This diagram illustrates the complete authentication flow in the Hatch Next application, including middleware processing and magic link authentication. It clearly separates client-side and server-side operations.

flowchart TD
    %% Define styles for client and server
    classDef client fill:#d4f1f9,stroke:#05a,color:#05a
    classDef server fill:#ffeded,stroke:#d79b00,color:#004d0e
    classDef shared fill:#e1d5e7,stroke:#9673a6,color:#9673a6

    %% Initial request
    A[User Enters Site with URL] --> M1[Next.js Middleware Executes]

    %% Server-side middleware processes request
    subgraph "Server-Side Middleware"
        M1 --> B{URL Contains 'autologin'?}
        %% Branch based on URL parameters
        B -->|Yes| C1[Magic Link Flow]
        B -->|No| C2[Standard Auth Flow]
    end

    %% Magic Link Authentication Flow
    subgraph "Magic Link Authentication"
        subgraph "Server-Side URL Handling"
            C1 --> S1["Extract Token from URL<br/>(in handleAutoLoginRequest)"]
            S1 --> S1a["Store returnTo parameter<br/>(original URL path)"]
            S1a --> S2["Server-Side Redirect<br/>(to /magic/[token])"]
        end

        subgraph "Client-Side Magic Link"
            S2 --> D1[Extract Token from Path]
            D1 --> E1[Call Magic Link Auth API]
            J1[Redirect to Protected Route]
            K1[Display Error Message]
        end

        subgraph "Server-Side Magic Link"
            F1["API Endpoint Receives Token<br/>(Calls /api/auth/[...nextauth])"]
            G1["Validate Token<br/>(Calls HATCH_SERVICE_URL/public/autoLogin/v1/login)"]
            H1{Is Token Valid?}
            I1[Generate JWT and Session]
        end

        %% Magic Link Flow connections
        E1 --> F1
        F1 --> G1
        G1 --> H1
        H1 -->|Yes| I1
        H1 -->|No| K1
        I1 --> J1
    end

    %% Standard Authentication Flow
    subgraph "Standard Authentication Flow"
        subgraph "Server-Side Route Protection"
            C2 --> E2{Is Protected Route?}
            E2 -->|No| F2[Allow Access to Public Route]
            E2 -->|Yes| G2[handleAuthProtectedRoute]
            G2 --> H2{User Authenticated?}
            H2 -->|No| I2[Redirect to Login]
            H2 -->|Yes| J2[Allow Access to Protected Route]
        end

        subgraph "Client-Side Auth State"
            K2[useSession Hook]
            L2{Session Exists?}
            M2[Show Authenticated UI]
            N2[Show Unauthenticated UI]
            O2[Login Form]
            P2[Submit Credentials]
        end

        subgraph "Server-Side Auth API"
            Q2["Auth API Endpoint<br/>(Calls /api/auth/[...nextauth])"]
            R2[Validate Credentials]
            S2{"Valid Credentials?<br/>(Calls HATCH_SERVICE_URL/public/v1/login)"}
            T2[Generate JWT]
            U2[Return Error]
        end

        %% Standard Flow connections
        K2 --> L2
        L2 -->|Yes| M2
        L2 -->|No| N2
        N2 --> O2
        O2 --> P2
        P2 --> Q2
        Q2 --> R2
        R2 --> S2
        S2 -->|Yes| T2
        S2 -->|No| U2
        T2 --> V2[Store in Session]
        U2 --> W2[Display Error]
        I2 --> O2
    end

    %% Post-authentication flows
    J1 --> X[Authenticated User]
    J2 --> X
    M2 --> X

    %% Periodic checks
    subgraph "Periodic Status Checks"
        subgraph "Client-Side Checks"
            X --> Y1[useMemberStatusCheck]
            X --> Y3[useHatchSubscription]
        end

        subgraph "Server-Side Checks"
            Z1["/api/hatch/get-member<br/>(Calls HATCH_SERVICE_URL/service/app/member/v1/{id})"]
            Z3["/api/hatch/subscription<br/>(Calls HATCH_SERVICE_URL/service/app/hatchSubscription/v1/fetch)"]
        end

        %% Connections
        Y1 --> Z1
        Y3 --> Z3
        Z1 -->|Valid| AA1[Continue Session]
        Z1 -->|Invalid| AA2[Sign Out User]
        Z3 -->|Active| AB1[Access Premium Features]
        Z3 -->|Inactive| AB2[Restrict Access]
    end

    %% Protected API Requests
    subgraph "Protected API Requests"
        subgraph "Client-Side Request"
            AC[Make API Request with JWT]
        end

        subgraph "Server-Side API"
            AD["API Middleware<br/>(JWT Validation)"]
            AE{"Valid JWT Token?<br/>(Verified with NEXTAUTH_SECRET)"}
            AF[Process Request]
            AG[Return 401 Unauthorized]
            AH{Requires Subscription?}
            AI{Subscription Active?}
            AJ[Process Request]
            AK[Return Error]
        end

        %% Connections
        X --> AC
        AC --> AD
        AD --> AE
        AE -->|Yes| AF
        AE -->|No| AG
        AF --> AH
        AH -->|Yes| AI
        AH -->|No| AJ
        AI -->|Yes| AJ
        AI -->|No| AK
    end

    %% Apply styles
    class A client
    class M1,B,C1,C2,S1,S2,E2,F2,G2,H2,I2,J2,F1,G1,H1,I1,Q2,R2,S2,T2,U2,Z1,Z3,AD,AE,AF,AG,AH,AI,AJ,AK server
    class D1,E1,J1,K1,K2,L2,M2,N2,O2,P2,V2,W2,Y1,Y3,AA1,AA2,AB1,AB2,AC client

Authentication Flow Explanation

Initial Request Handling

  1. User Enters Site with URL: The process begins when a user navigates to the site
  2. Next.js Middleware Executes: Server-side middleware runs on every request
  3. URL Parameter Check: The middleware checks if the URL contains an 'autologin' parameter
    • If 'autologin' is present → Magic Link Authentication Flow
    • If not → Standard Authentication Flow

Magic Link Authentication (When 'autologin' is in URL)

Server-Side Middleware:

  1. The middleware detects the 'autologin' parameter in the URL
  2. The middleware extracts the token from the URL parameter
  3. The middleware extracts the token and stores the original URL path as 'returnTo'
  4. The middleware performs a server-side redirect to the magic token route (e.g., /magic/[token])

Client-Side:

  1. The client loads the magic token page at /magic/[token]
  2. The client extracts the authentication token from the URL path parameter
  3. The client retrieves the returnTo parameter from the URL query
  4. The client calls the Magic Link Authentication API with the token
  5. Upon successful authentication, the user is redirected to the protected route
  6. If authentication fails, an error message is displayed

Server-Side Auth API:

  1. The API endpoint receives the magic link token
  2. The server validates the token (checks existence, expiration, and one-time use)
  3. If valid, the server generates a JWT and creates a session
  4. If invalid, an error response is returned to the client

Standard Authentication Flow

Server-Side Middleware:

  1. Next.js middleware executes on every request
  2. Middleware checks if the requested route is protected
  3. For public routes, access is allowed immediately
  4. For protected routes, the handleAuthProtectedRoute function is called
  5. This function checks if the user is authenticated:
    • If authenticated → Allow access to the protected route
    • If not authenticated → Redirect to login page

Client-Side Authentication State:

  1. The useSession hook checks for an existing authentication session
  2. If a session exists, authenticated UI is shown
  3. If no session exists, unauthenticated UI with login form is shown
  4. User can submit credentials through the login form

Server-Side Authentication API:

  1. The authentication API endpoint receives credentials
  2. The server validates the credentials
  3. If valid, a JWT token is generated and returned
  4. If invalid, an error response is returned

Post-Authentication Flows

Periodic Status Checks:

  1. Client-Side:
    • useMemberStatusCheck periodically verifies account status
    • useHatchSubscription checks subscription status
  2. Server-Side:
    • /api/hatch/get-member verifies account status
    • /api/hatch/subscription checks subscription status
  3. Based on these checks:
    • Valid account → Continue session
    • Invalid account → Sign out user
    • Active subscription → Access to premium features
    • Inactive subscription → Restricted access

Protected API Requests:

  1. Client-Side:
    • API requests include JWT token in headers
  2. Server-Side:
    • API middleware checks for valid JWT token
    • If token is valid, request is processed
    • If token is invalid, 401 Unauthorized is returned
    • For subscription-required endpoints, subscription status is checked
    • If subscription is required but inactive, error is returned

Security Considerations

  1. JWT tokens should be securely stored and transmitted
  2. Magic link tokens should be:
    • One-time use only
    • Time-limited (typically expire after 10-15 minutes)
    • Securely stored with proper encryption
  3. After successful authentication, the magic link token should be immediately invalidated
  4. The 'autologin' parameter should be removed from the URL after processing
  5. Protected routes should consistently enforce authentication checks
  6. Periodic account and subscription status checks ensure continued authorization

Account & Subscription Status Checks

  1. Client-Side Operations
    • useMemberStatusCheck
    • useHatchSubscription
  2. Server-Side Operations
    • "/api/hatch/get-member"
    • "/api/hatch/subscription"

Protected Routes

  1. Frontend Protected Routes
    • Subscription Offer Paths
    • Upgrade Offer Paths
  2. API Protected Routes
    • Recharge API Routes
    • Hatch API Routes
    • Membership API Routes
    • Multipass API Routes

Authentication Methods

  1. Credentials Login
  2. Magic Link Login