Single-flight API refresh

You can make authenticated requests through one API client and share a refresh across concurrent 401 responses.

Learning outcomes

  • Explain why every screen should send API requests through one shared API client.
  • Distinguish HTTP failures from network failures and represent HTTP errors with ApiError.
  • Implement silent refresh with one retry when an authenticated request receives 401.
  • Coordinate concurrent refresh attempts with a shared promise because refresh tokens rotate on use.
  • Distinguish a rejected refresh from a network failure so the app only clears sessions when the API rejects them.
Prerequisite conceptsTokenStore

Three screens in the app can make requests at the same time: the restaurant list, the cart badge and the order poll. All three use the same access token, which expires after 15 minutes. When it expires, all three requests can receive 401 together. You need one request layer that handles authentication and coordinates refresh without making the customer log in again.

One API client

Every screen talks to the same Go API. The login screen sends credentials, the restaurant list fetches pages, the configurator requests quotes and checkout creates orders.

If every screen calls fetch() independently, each one must handle the base URL, JSON, bearer headers and HTTP errors. Each screen would also need its own refresh logic. That creates several places where authentication behaviour can differ.

The API client centralises these responsibilities in app/lib/api.ts. Screens call request() instead of calling fetch() directly.

The app creates one client in lib/client.ts. It receives the configured API URL and the token store introduced in the previous lesson.

ts
import { ApiClient } from "./api";
import { API_URL } from "./config";
import { tokenStore } from "./tokens";

export const api = new ApiClient(API_URL, tokenStore);

The client depends on the TokenStore interface rather than SecureStore itself. This means the same client can use an in-memory implementation during Jest tests.

A screen does not need to know where tokens are stored or how authentication headers are generated. It only needs to describe the request.

For example, a restaurant list can request a typed response:

ts
const page = await api.request<Page<Restaurant>>(
  "/v1/restaurants?limit=20"
);

An order request can supply its method, body and idempotency key:

ts
await api.request("/v1/orders", {
  method: "POST",
  body: order,
  headers: { "Idempotency-Key": key },
});

The same client handles both requests. Screens no longer need to construct the base URL or manually add the bearer token.

Fetch response behaviour

The native fetch API behaves differently from libraries such as Axios in one important way: HTTP error statuses do not reject its promise.

A response with status 400, 401, 429 or 500 still resolves successfully from the perspective of JavaScript. The server responded, so fetch gives you a Response object.

ts
const response = await fetch(url);

console.log(response.status);
console.log(response.ok);

For an unsuccessful HTTP response, response.ok is false. Your API client must inspect that property and decide what error to expose.

A network failure behaves differently. When the phone cannot reach the API, fetch rejects its promise, usually with a TypeError. There is no HTTP response and therefore no HTTP status to inspect.

Keep these cases separate:

SituationWhat the client receives
API returns 400A resolved response with status 400
API returns 401A resolved response with status 401
API returns 429A resolved response with status 429
API returns 204A successful response without a body
Network connection failsA rejected promise with a TypeError

This distinction matters on a phone. An incorrect password means the API rejected the credentials. A lost Wi-Fi connection means the app could not reach the API. Showing the same message for both hides useful information.

Response bodies

A response body is a stream that you can consume once. Calling response.json() reads that stream, so do not try to parse the same response twice.

Successful responses generally contain JSON. The client parses that JSON and returns it to the caller.

A 204 No Content response is an exception. It has no body, so calling response.json() would fail. Return undefined instead.

Error responses also need defensive parsing. The Go API normally returns an error body with fields such as error, message and field. However, an empty body or a non-JSON response should not hide the original HTTP status.

ts
let body: unknown = null;

try {
  body = await response.json();
} catch {
  body = null;
}

The client can now preserve the status even when the response body cannot be parsed.

Typed API errors

Every unsuccessful HTTP response becomes an ApiError. Its status identifies the HTTP failure, its body carries the parsed response, and its optional retryAfterSec field carries the wait time for rate limits.

ts
export class ApiError extends Error {
  constructor(
    public status: number,
    public body: unknown,
    public retryAfterSec?: number,
  ) {
    super(`API ${status}`);
  }
}

Keeping the status and body together lets screens make decisions without inspecting raw Response objects.

Consider the responses used by this API:

StatusMeaning to the app
400Invalid input. The body may contain a useful error message.
401Authentication failed or an access token is no longer accepted.
409The requested operation conflicts with existing state.
429The request was rate limited.
500The API encountered a server error.

The 429 response has an additional header: Retry-After. It tells the client how many seconds to wait before trying again.

Convert its value to a number and expose it through retryAfterSec. When the header is missing, use 1.

For example, a response containing:

HTTP/1.1 429 Too Many Requests
Retry-After: 3

gives the screen an ApiError with status equal to 429 and retryAfterSec equal to 3.

A network failure must not become an ApiError. The original TypeError needs to reach the screen so it can display a connection message instead of an HTTP error message.

Requests without authentication

Login and signup are special because the customer may not have a valid session yet.

The API client normally reads the current token pair and adds the access token to the request. Authentication requests must opt out of that behaviour with auth: false.

ts
const response = await api.request<TokenResponse>(
  "/v1/auth/login",
  {
    method: "POST",
    body: { email, password },
    auth: false,
  }
);

Without auth: false, a stale access token could accompany the login request. The server might respond with 401, which the client could mistake for an expired session and attempt to refresh.

That is not what the customer expects. A 401 from login means the credentials were rejected. It should not trigger silent refresh.

The auth option therefore controls two related behaviours: whether the client attaches the stored bearer token and whether it considers the response for refresh.

Extra headers are merged after the default headers. This allows a caller to supply headers such as Idempotency-Key or override a default header when needed.

Silent refresh

The Go API issues a 15-minute access token and a refresh token. When an authenticated request receives 401, the app can use the refresh token to obtain a new pair.

Silent refresh handles this without asking the customer to enter their password again.

The request follows this sequence:

  1. The API client reads the stored token pair.
  2. It sends the original request with the access token.
  3. The API responds with 401.
  4. The client sends POST /v1/auth/refresh with the refresh token.
  5. The API returns a new access token and refresh token.
  6. The client stores the new pair together.
  7. The original request is sent again with the new access token.

The refresh request has this JSON body:

json
{
  "refresh_token": "current-refresh-token"
}

The response contains access_token and refresh_token. Map those fields to the app's { access, refresh } token pair and store the pair through the token store.

The original request must be retried only once. This is important because not every 401 necessarily means that refreshing will fix the problem.

For example, the API might reject a request for a reason that remains true after a refresh. Repeating the refresh indefinitely would cause an endless request loop.

A retry flag captures this limit:

ts
if (response.status === 401 && tokens && !retried) {
  const fresh = await refresh(tokens.refresh);

  if (fresh) {
    return request(path, options, true);
  }
}

The first attempt can refresh. The second attempt has retried set to true, so another 401 becomes an ordinary ApiError.

This limit belongs to each original request. A successful refresh does not give that request permission to retry indefinitely.

Refresh token rotation

The Week 3 API rotates refresh tokens on every successful refresh. The old refresh token becomes invalid as soon as the API issues the replacement.

This creates a concurrency problem.

Imagine three authenticated requests starting at nearly the same time. All three read the same stored token pair before sending their requests. The access token has expired, so all three receive 401.

If every request independently sends the same refresh token, the first refresh succeeds and rotates the token. The remaining refresh requests use the old token, which is now invalid.

The backend can reject those requests with 401 invalid_refresh_token. The app may then clear the session even though the first request already obtained a valid new pair.

The problem is not the access token. It is multiple refresh operations competing to consume one rotating refresh token.

Single-flight refresh

The solution is single-flight coordination. Only one refresh operation runs at a time, and every request that needs that refresh shares the same promise.

A promise represents work that has started but has not finished yet. Storing that promise in the API client gives concurrent requests a common result to await.

The refresh state starts empty:

ts
private refreshing: Promise<Tokens | null> | null = null;

When the first request receives 401, the client creates a refresh promise and stores it in refreshing. Another request receiving 401 while that promise is pending reuses it.

The important distinction is between creating a refresh and awaiting one.

  1. The first failed request checks whether refreshing is empty.
  2. If it is empty, that request starts the refresh and stores its promise.
  3. Every concurrent request finds the existing promise.
  4. All waiting requests receive the same refresh result.
  5. The promise is cleared after the refresh operation settles.

The refresh operation must clear its shared state in a finally block. This ensures that a later access token expiry can start another refresh.

Three requests to the API each receive 401. The first starts one request to /v1/auth/refresh. The other two await the same promise. The API returns a new token pair, which is stored once. All three original requests then retry with the new access token.Three requests to the API each receive 401. The first starts one request to /v1/auth/refresh. The other two await the same promise. The API returns a new token pair, which is stored once. All three original requests then retry with the new access token.

Once the shared refresh succeeds, each original request retries independently. Each retry reads the updated token pair from the store, so all three requests use the new access token.

Refresh failure handling

A refresh can fail for two different reasons. The client must distinguish an API rejection from a network failure.

API rejection

The API might reject a refresh token because it is invalid, expired or already used. The Week 3 API uses 401 invalid_refresh_token for a used refresh token.

When the refresh endpoint rejects the request, the stored pair is no longer usable for this session. The client clears it:

ts
await store.set(null);
return null;

The token store publishes this change to its listeners. The AuthProvider from the previous lesson observes null and updates isSignedIn to false.

Stack.Protected then switches the customer back to the authentication routes. The API client does not need to call the router or know which screen is currently visible.

The original request does not get another retry when refresh fails. It surfaces its original 401 as an ApiError.

Network failure

A network failure does not establish that the refresh token is invalid.

The customer might be travelling through a tunnel or temporarily disconnected from Wi-Fi. The API has not necessarily received the refresh request or rejected the session.

In this case, the refresh operation must preserve the stored token pair and propagate the original TypeError.

The screen can show a connection error. Once the phone is connected again, another request can attempt refresh with the still-stored pair.

Rate limits and empty responses

The API client also handles two response cases that screens should not need to understand.

The Week 1 rate limiter responds with 429 rate_limited and a Retry-After header. The client exposes the delay as retryAfterSec, allowing the screen to tell the customer when to try again.

A 204 No Content response is successful but has no JSON body. Return undefined for this status rather than attempting to parse it.

These behaviours belong in the shared client because every screen should receive consistent results regardless of which endpoint it calls.

Testing the API client boundary

The API client depends on fetch and the TokenStore interface. This makes it possible to test its behaviour without starting the Go API or running a native app.

The Jest tests in app-tests/ replace fetch with a scripted fake. They also supply an in-memory token store. Each test controls the response and checks the requests the client sends.

The tests cover these behaviours:

  • A normal request includes the bearer header and parses JSON.
  • A request with a body sends JSON and preserves additional headers.
  • A 401 triggers one refresh and one retry, storing the returned pair.
  • Three concurrent 401 responses share one refresh call.
  • A second 401 after a successful refresh throws instead of retrying again.
  • A 429 exposes Retry-After through retryAfterSec.
  • Other HTTP failures expose their status and parsed body.
  • An API rejection during refresh clears the tokens.
  • A network failure during refresh preserves the tokens and propagates a TypeError.
  • A 204 resolves to undefined.

The tests also verify that the API client does not depend directly on SecureStore. The in-memory implementation must be able to provide the same token-store contract.

The API client and auth screens

The next exercise, API client and auth screens, brings these pieces together.

You will build the shared API client, connect it to the existing token store and use it from login and signup. The authentication provider will respond to token changes without navigation calls inside the API client.

The exercise tests focus on the behaviour of the client and token storage. The login and signup screens also need to work on a phone, including when the keyboard is open.

Keep the boundary clear: screens describe requests, the API client handles HTTP and refresh, and the token store owns persistence. The same client will serve the restaurant, menu, configurator, checkout and order screens.

Check your understanding

Question 1 of 4

A screen calls fetch() and receives a response with status 500. The promise resolves normally. What should the API client do?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (fetch, React Native 0.88).

Finished Lesson 4.6?