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
SecureTokenStorestores the access token and refresh token together as one JSON pair in expo-secure-store, using the keyauth.tokens. Its firstget()reads from SecureStore and later reads use the cache. A successfulset()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 toGET. It sendsContent-Type: application/json, serialises a suppliedbodyas JSON, and addsAuthorization: Bearer <access>when a token pair exists andauthis notfalse. It merges extra headers last, so callers can override default headers. Requests withauth: falsedo not add the stored bearer token.- A successful response is parsed as JSON. A
204response resolves toundefined. A non-2xx response throwsApiErrorwith its HTTP status and parsed JSON body, ornullwhen the body cannot be parsed. For a429,retryAfterSeccomes from theRetry-Afterheader as a number, defaulting to1. A network failure remains theTypeErrorthrown byfetch. - When a request receives
401and a token pair is stored, the client sendsPOST /v1/auth/refreshwith{ "refresh_token": "<refresh>" }. It stores the returnedaccess_tokenandrefresh_tokenas the new pair, then retries the original request once. A second401is returned as anApiError; the request must not retry again. - Concurrent
401responses 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 afinallypath 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 originalTypeError. lib/client.tsconstructs the app's onlyApiClientfromAPI_URLandtokenStore. The client depends on the TokenStore interface rather than directly depending on SecureStore.loginsends{ email, password }toPOST /v1/auth/login, andsignupsends the same fields toPOST /v1/auth/signup. Both useauth: false, map the response'saccess_tokenandrefresh_tokento{ 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.andUse at most 72 bytes; long passphrases with emoji count extra. authErrorMessagemaps a401toWrong email or password., a409toThat email already has an account. Log in instead., and a429toToo many attempts. Try again in N s., usingretryAfterSecor1when it is absent. For a400with a stringerrorfield, it displays that field. A non-ApiErrordisplaysCannot reach the server. Check your Wi-Fi and that the API is running.- The shared
AuthFormdisables its inputs and submit button while a request is in flight. Login usesautoComplete="current-password"and signup usesautoComplete="new-password". The form remains usable with the keyboard open by using a KeyboardAvoidingView. AuthProvidersubscribes to the token store, reads its initial value, and unsubscribes during effect cleanup.isSignedInreflects whether a token pair is stored. Login, signup, logout and a rejected refresh update the store, allowingStack.Protectedto move between the auth screens and tabs without navigation calls in those operations.- When
isSignedInbecomes 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
10seconds, the app continues working after15seconds of waiting because the next request refreshes silently. In Redis, a newrefresh:*key replaces the old one. If you delete the currentrefresh:*key and wait past the access token's lifetime, the next request signs the customer out. - After
npm ciinapp-tests,make test W=4B2passes all 29 tests: 7 inapi.test.ts, 7 intokens.test.ts, 9 inauth.test.tsand 6 inapi-refresh.test.ts.npx tsc --noEmitpasses inapp/, andgrep -rn "fetch(" app/app app/componentsfinds 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
401responses 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:
cd app-tests && npm ci
cd backend && make test W=4B2
cd app && npx tsc --noEmit
cd app && npx expo startRead the first failing assertion before changing code. It identifies the behaviour that differs from the contract, so fix that behaviour before investigating later failures.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
API client and authentication
3 items
- 4.5Secure token storagenot completed
- 4.6Single-flight API refreshnot completed
- 4.7API client and auth screensnot completed
Up next · Module 3 · 4 items · about 3 h 30 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
make test W=4B2passes all 29 tests.- Signup opens the tabs, and the session survives an app restart.
- Wrong credentials show the expected message.
- Sign-out clears the session and the previous account's cached data.
- Requests continue working after access token expiry through silent refresh.
- An invalid refresh token signs the customer out on the next request.
Commands
cd app-tests && npm cicd backend && make test W=4B2cd app && npx tsc --noEmitcd app && npx expo startTests
W4 B2 ApiClient (7 tests)inapp-tests/lib/api.test.tsW4 B2 SecureTokenStore (7 tests)inapp-tests/lib/tokens.test.tsW4 B2 login and signup (9 tests)inapp-tests/lib/auth.test.tsW4 B2 ApiClient refresh failure (6 tests)inapp-tests/lib/api-refresh.test.ts