All Challenges
3 PointsIntermediateMERN Stack
00:00
MERN Stack: Axios/Fetch Interceptor with Silent JWT Token Refresh Queue
Implement an HTTP interceptor that catches 401s, pauses concurrent requests in a FIFO promise queue, refreshes the token, and replays failed requests.
### Problem Overview
In production MERN stack web apps, access tokens expire every 10-15 minutes. When multiple components render simultaneously on a page, all 3 make concurrent HTTP requests with the expired token, resulting in simultaneous 401 Unauthorized errors. You must build an HTTP Interceptor with an Asynchronous Request Queue that intercepts 401s, initiates a single refresh call, queues all concurrent requests, and replays them automatically with the new token.
### Functional Requirements
1. **`fetch(url: string, headers?: Record<string, string>): Promise<{ status: number; data: any }>`**:
- Attaches `Authorization: Bearer <token>` header to requests.
- If the request returns `401`, intercepts the response.
2. **Atomic Token Refresh Locking**:
- Only ONE refresh token request must be in flight at any given moment.
- Other requests encountering 401s while a refresh is in progress must be enqueued into an asynchronous pending resolver queue.
3. **Queue Replay on Refresh Success**:
- Once refreshed, updates the token and replays all pending queued requests.
4. **Queue Rejection on Refresh Failure**:
- If token refresh fails, rejects all queued requests and calls `onSessionExpired`.
AI Review Rubric Dimensions (1–10 Points):
- Single-flight lock
- Asynchronous promise queueing
- Error cascade suppression
- Infinite retry prevention
solution.tsTYPESCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
27 lines•741 characters•
AI Review Ready