{"success":true,"name":"handle-token-expiry-in-api-clients-refresh-once-queue-retry","description":"API calls start failing with 401 after the user has been logged in a while","category":"ai-brimind","path":"ai-brimind/handle-token-expiry-in-api-clients-refresh-once-queue-retry/SKILL.md","file":"SKILL.md","content":"---\nname: handle-token-expiry-in-api-clients-refresh-once-queue-retry\ndescription: \"API calls start failing with 401 after the user has been logged in a while\"\n---\n\n# Handle Token Expiry in API Clients: Refresh Once, Queue, Retry\n\n## When to use\nYour client talks to an API using expiring tokens, and expiry currently means random 401 failures or a hand-rolled refresh scattered per call.\n\n## Example request\nToken expires mid-session → user gets kicked to login while their work is lost; a refresh-token flow renews access silently. — Five parallel requests hit 401 together and each triggers a refresh → refresh storm invalidates itself; one shared refresh with queued requests is the pattern. — Refresh logic copy-pasted around → some paths refresh, others just fail; the API client layer's interceptor is the single owner. — Refresh token itself expired or revoked → the app loops refreshing forever; that case is the real logout, and it must be terminal.\n\n## Instructions\nAct as an auth-flow engineer who treats token expiry as a scheduled event, not an error. In the client: 1) Centralize the handling in the API client layer's interceptor — one place catches 401, refreshes, and retries the original request; no per-call refresh logic anywhere. 2) Serialize the refresh: when multiple requests fail together, exactly one refresh runs while the others queue and replay after it — parallel refreshes race and log users out. 3) Distinguish the two failures clearly: access token expired (refresh and retry, invisible to the user) versus refresh token invalid/revoked (terminal — clean logout with state preserved where possible); looping on the second is the infinite-spinner bug. 4) Use the auth provider's or framework's existing mechanism first (SDK token management, built-in interceptors) — hand-rolled token dance is high-risk code that usually already exists. 5) Retry only once per request after refresh — a second 401 after a fresh token means a different problem (permissions, clock skew), not another refresh. Only trust the flow once you've tested with a short-lived token and parallel requests, and explain how the design makes expiry invisible to users rather than an intermittent bug report.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #926\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}