Magic Link Authentication Flow

This diagram illustrates the complete magic link (autologin) authentication flow in the Hatch Next application. It clearly separates client-side and server-side operations and shows all API endpoints that are called during the process.

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 external fill:#e8f5e9,stroke:#2e7d32,color:#2e7d32

    %% Initial request
    A["User Clicks Magic Link<br/>(URL with autologin parameter)"] --> B["Browser Navigates to URL<br/>example.com/some-page?autologin=TOKEN"]

    %% Server-side middleware processing
    subgraph "SERVER SIDE: Next.js Middleware"
        C["Middleware Intercepts Request<br/>(middleware.ts)"] --> D{"URL Contains<br/>autologin parameter?"}
        D -->|Yes| E["Extract Token from URL<br/>(handleAutoLoginRequest)"]
        E --> F["Store Original Path as returnTo<br/>(for post-login redirect)"]
        F --> G["Server-Side Redirect<br/>to /magic/[token]"]
    end

    %% Client-side magic link handling
    subgraph "CLIENT SIDE: Magic Token Page"
        H["Load Magic Token Page<br/>(app/(base)/magic/[token]/page.tsx)"] --> I["Render Auto Sign-In Component<br/>(auto-sign-in.tsx)"]
        I --> J["Extract Token from URL Path<br/>(useParams hook)"]
        J --> K["Get returnTo from Query Params<br/>(useSearchParams hook)"]
        K --> L["Call next-auth signIn<br/>(with mToken parameter)"]
    end

    %% Server-side authentication
    subgraph "SERVER SIDE: NextAuth API"
        M["NextAuth API Endpoint<br/>(pages/api/auth/[...nextauth].ts)"] --> N["Check for mToken in Credentials"]
        N --> O["Call Magic Link Authentication API<br/>(requestLoginWithMagic)"]
        O --> P["POST Request to External API<br/>(HATCH_SERVICE_URL/public/autoLogin/v1/login)"]
        P --> Q{"Is Token Valid?"}
        Q -->|Yes| R["Generate JWT Token"]
        Q -->|No| S["Return Authentication Error"]
        R --> T["Create User Session"]
        T --> U["Generate Multipass Token<br/>(for Shopify integration)"]
    end

    %% Post-authentication
    subgraph "CLIENT SIDE: Post-Authentication"
        V["Receive Authentication Result"] --> W{"Authentication Successful?"}
        W -->|Yes| X["Redirect to Original Path<br/>(from returnTo parameter)"]
        W -->|No| Y["Display Error Message"]
        X --> Z["User Authenticated"]
    end

    %% Flow connections between subgraphs
    B --> C
    G --> H
    L --> M
    T --> V

    %% Apply styles
    class A,B,H,I,J,K,L,V,W,X,Y,Z client
    class C,D,E,F,G,M,N,O,R,S,T,U server
    class P,Q external

Magic Link Authentication Flow Explanation

Initial Request

  1. User Clicks Magic Link: The process begins when a user clicks a magic link sent to their email
  2. Browser Navigates to URL: The browser loads a URL containing the autologin parameter with a token

Server-Side Middleware Processing

  1. Middleware Intercepts Request: The Next.js middleware (middleware.ts) intercepts all incoming requests
  2. Check for Autologin Parameter: The middleware checks if the URL contains an autologin parameter
  3. Extract Token: If found, handleAutoLoginRequest extracts the token from the URL
  4. Store Original Path: The middleware stores the original URL path as a returnTo parameter
  5. Server-Side Redirect: The middleware performs a server-side redirect to /magic/[token]

Client-Side Magic Token Page

  1. Load Magic Token Page: The browser loads the magic token page at /magic/[token]
  2. Render Auto Sign-In Component: The page renders the AutoSignIn component
  3. Extract Token from URL Path: The component extracts the token from the URL path using the useParams hook
  4. Get returnTo Parameter: The component retrieves the returnTo parameter from the URL query
  5. Call next-auth signIn: The component calls signIn('credentials', { mToken: token, ... })

Server-Side NextAuth API

  1. NextAuth API Endpoint: The request is handled by the NextAuth API endpoint
  2. Check for mToken: The authorize function checks for the presence of mToken
  3. Call Magic Link Authentication API: If found, it calls requestLoginWithMagic
  4. External API Request: This makes a POST request to HATCH_SERVICE_URL/public/autoLogin/v1/login
  5. Token Validation: The external API validates the token (checks existence, expiration, one-time use)
  6. Generate JWT: If valid, a JWT token is generated
  7. Create Session: A user session is created
  8. Generate Multipass Token: A Shopify Multipass token is generated for integration

Client-Side Post-Authentication

  1. Receive Authentication Result: The client receives the authentication result
  2. Check Authentication Status: The client checks if authentication was successful
  3. Redirect to Original Path: If successful, the user is redirected to the original path (from returnTo)
  4. Display Error: If unsuccessful, an error message is displayed
  5. User Authenticated: The user is now authenticated and can access protected resources