API client and auth screens

You build the API client and login and signup screens, sending authenticated requests and storing the returned token pair. Concurrent 401 responses must share one refresh.

Ticket

Build the API client in app/lib/api.ts and the supporting token and authentication modules. Every screen must send requests through this client. It adds the bearer token, converts HTTP failures into typed errors, and handles silent refresh when an access token expires.

Build the login and signup screens on top of that client. The app needs a persistent session so customers can reopen it without logging in again. The restaurant and order screens depend on the same authenticated client, while the protected route keeps signed-out customers out of the tabs.

Acceptance criteria

  • SecureTokenStore stores the access token and refresh token together as one JSON pair in expo-secure-store, using the key auth.tokens. Its first get() reads from SecureStore and later reads use the cache. A successful set() updates the cache and notifies every subscribed listener. A failed write must not update the cache. set(null) deletes the key. subscribe(listener) returns an unsubscribe function, and an unsubscribed listener receives no later notifications.
  • ApiClient.request<T>() prefixes the configured base URL and defaults to GET. It sends Content-Type: application/json, serialises a supplied body as JSON, and adds Authorization: Bearer <access> when a token pair exists and auth is not false. It merges extra headers last, so callers can override default headers. Requests with auth: false do not add the stored bearer token.
  • A successful response is parsed as JSON. A 204 response resolves to undefined. A non-2xx response throws ApiError with its HTTP status and parsed JSON body, or null when the body cannot be parsed. For a 429, retryAfterSec comes from the Retry-After header as a number, defaulting to 1. A network failure remains the TypeError thrown by fetch.
  • When a request receives 401 and a token pair is stored, the client sends POST /v1/auth/refresh with { "refresh_token": "<refresh>" }. It stores the returned access_token and refresh_token as the new pair, then retries the original request once. A second 401 is returned as an ApiError; the request must not retry again.
  • Concurrent 401 responses share one single-flight refresh promise. They must not submit the same rotating refresh token in separate refresh requests. The shared promise is reset in a finally path so a later refresh can start.
  • A refresh rejected by the API clears the stored pair with set(null). A refresh that fails because of a network error keeps the stored pair and propagates the original TypeError.
  • lib/client.ts constructs the app's only ApiClient from API_URL and tokenStore. The client depends on the TokenStore interface rather than directly depending on SecureStore.
  • login sends { email, password } to POST /v1/auth/login, and signup sends the same fields to POST /v1/auth/signup. Both use auth: false, map the response's access_token and refresh_token to { access, refresh }, and store the pair. Neither function performs navigation.
  • The login and signup forms trim and lower-case the email before submitting it. Signup rejects passwords shorter than 8 characters or longer than 72 bytes in UTF-8 before making an API request. The validation messages are Use at least 8 characters. and Use at most 72 bytes; long passphrases with emoji count extra.
  • authErrorMessage maps a 401 to Wrong email or password., a 409 to That email already has an account. Log in instead., and a 429 to Too many attempts. Try again in N s., using retryAfterSec or 1 when it is absent. For a 400 with a string error field, it displays that field. A non-ApiError displays Cannot reach the server. Check your Wi-Fi and that the API is running.
  • The shared AuthForm disables its inputs and submit button while a request is in flight. Login uses autoComplete="current-password" and signup uses autoComplete="new-password". The form remains usable with the keyboard open by using a KeyboardAvoidingView.
  • AuthProvider subscribes to the token store, reads its initial value, and unsubscribes during effect cleanup. isSignedIn reflects whether a token pair is stored. Login, signup, logout and a rejected refresh update the store, allowing Stack.Protected to move between the auth screens and tabs without navigation calls in those operations.
  • When isSignedIn becomes false, the root layout clears the TanStack Query cache. Signing out returns to Log in, and the back gesture cannot reopen the signed-in tabs. Logging in as another user must not show data cached for the previous user.
  • On a phone, signing up with a new email opens the tabs, and killing and reopening the app keeps the customer signed in. A wrong password displays Wrong email or password. and leaves the customer on the login form. With the API stopped, login displays the cannot-reach message instead.
  • With the API access token lifetime set to 10 seconds, the app continues working after 15 seconds of waiting because the next request refreshes silently. In Redis, a new refresh:* key replaces the old one. If you delete the current refresh:* key and wait past the access token's lifetime, the next request signs the customer out.
  • After npm ci in app-tests, make test W=4B2 passes all 29 tests: 7 in api.test.ts, 7 in tokens.test.ts, 9 in auth.test.ts and 6 in api-refresh.test.ts. npx tsc --noEmit passes in app/, and grep -rn "fetch(" app/app app/components finds no matches.

Constraints

  • Signup passwords have a minimum length of 8 characters and a maximum length of 72 UTF-8 bytes.
  • A request retries at most once after a 401.
  • Concurrent 401 responses use one shared refresh promise.

Design direction

Keep token persistence behind the TokenStore interface. Put the SecureStore implementation and its in-memory cache in tokens.ts. This lets the API client work with an in-memory store in tests without changing its request logic.

Keep HTTP behaviour in api.ts, and construct the single app client in client.ts. Put login, signup, logout, password validation and error mapping in authApi.ts. The form should own input state and submission feedback, while the screens provide the relevant submit operation and autocomplete setting. Let AuthProvider observe the token store rather than making individual authentication operations manage navigation.

Think carefully about the difference between an API rejection and a network failure. A rejected refresh means the stored session is no longer valid. A network failure does not establish that, so clearing the tokens would sign out customers unnecessarily.

Treat refresh coordination as part of the API client. Refresh tokens rotate on use, so concurrent refresh requests using one stored token can invalidate the session. The shared promise prevents that race. Any layout that meets the contract passes.

How to check your work

Run these commands in order:

bash
cd app-tests && npm ci
cd backend && make test W=4B2
cd app && npx tsc --noEmit
cd app && npx expo start

Read the first failing assertion before changing code. It identifies the behaviour that differs from the contract, so fix that behaviour before investigating later failures.

Finished Exercise 4.7?

API client and authentication

3 items

  • 4.5Secure token storagenot completed
  • 4.6Single-flight API refreshnot completed
  • 4.7API client and auth screensnot completed

Paged data lists

Up next · Module 3 · 4 items · about 3 h 30 min

Start module 3

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. make test W=4B2 passes all 29 tests.
  2. Signup opens the tabs, and the session survives an app restart.
  3. Wrong credentials show the expected message.
  4. Sign-out clears the session and the previous account's cached data.
  5. Requests continue working after access token expiry through silent refresh.
  6. An invalid refresh token signs the customer out on the next request.

Commands

terminal
cd app-tests && npm ci
terminal
cd backend && make test W=4B2
terminal
cd app && npx tsc --noEmit
terminal
cd app && npx expo start

Tests

  • W4 B2 ApiClient (7 tests) in app-tests/lib/api.test.ts
  • W4 B2 SecureTokenStore (7 tests) in app-tests/lib/tokens.test.ts
  • W4 B2 login and signup (9 tests) in app-tests/lib/auth.test.ts
  • W4 B2 ApiClient refresh failure (6 tests) in app-tests/lib/api-refresh.test.ts