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
autologin
parameter with a tokenmiddleware.ts
) intercepts all incoming requestsautologin
parameterhandleAutoLoginRequest
extracts the token from the URLreturnTo
parameter/magic/[token]
/magic/[token]
AutoSignIn
componentuseParams
hookreturnTo
parameter from the URL querysignIn('credentials', { mToken: token, ... })
authorize
function checks for the presence of mToken
requestLoginWithMagic
HATCH_SERVICE_URL/public/autoLogin/v1/login
returnTo
)