📚 Supabase Security series — read it in full on warrendeleon.com, where new parts land first.
This post covers the auth client: a typed Axios wrapper around Supabase's REST API with sign-up, sign-in, logout, current-user retrieval, a request interceptor for token attachment, and a mapped error type. It's part 2 of the Supabase-without-the-SDK series; part 1 covered the why.
supabase-js already does this well for most projects. The reasons to write your own are narrow and were covered in part 1: tighter control over storage, validation at the API boundary, and a smaller dependency footprint when you only need REST. If supabase-js fits your shape, use it. The walkthrough below is for the cases where it doesn't.
The token-refresh response interceptor gets its own post. This one stops at the request interceptor and the auth methods.
In this post: project layout, base client, request interceptor, the four auth methods (sign-up, sign-in, logout, getCurrentUser), typed errors, tests, common pitfalls.
Source: src/httpClients/SupabaseAuthClient.ts.
Assumptions
The setup below was written against:
- React Native 0.74+ (bare workflow)
- TypeScript with the standard RN Babel config
- A Supabase project (or any compatible REST API at
/auth/v1) - Token storage wired up so tokens go into the platform Keychain, not AsyncStorage
- Zod for runtime response validation (the auth client validates every response before it touches Redux; covered in a later post in this series)
- Jest configured for unit tests (see Setting up MSW v2 in React Native if you don't have it yet)
Installation
yarn add axios react-native-config zod cd ios && pod install && cd .. react-native-config reads SUPABASE_URL and SUPABASE_ANON_KEY from a .env file at build time. It's a native module, so iOS needs a pod install.
.env at the repo root:
SUPABASE_URL=https://your-project.supabase.co SUPABASE_ANON_KEY=ey... The anon key is designed to be public. That's a different claim from "safe to ship unconditionally". It's the identifier Supabase uses for unauthenticated client access; the actual security boundary is whatever RLS policies and function permissions you put on the backend. If RLS is missing or written wrong on a single table, the anon key is enough to read it from any script. Treat the key as identification, and treat your RLS policies as the thing protecting your data. The final post in this series covers RLS specifically.
What you're building
A single class with an Axios instance and four public methods:
class SupabaseAuthClient { signUp(request: SupabaseSignUpRequest): Promise<SupabaseSignUpResponse>; signIn(request: SupabaseSignInRequest): Promise<SupabaseSignInResponse>; logout(): Promise<void>; getCurrentUser(): Promise<SupabaseUser | null>; } The Axios instance is constructed once with the project URL, the anon key as a default header, and a request interceptor that attaches the user's access token on every authenticated call. Each public method posts to a Supabase REST endpoint, validates the response with Zod, stores the resulting tokens in the platform Keychain, and returns typed data to the caller.
A typed AuthError class wraps every failure mode so the UI can switch on the error code without parsing strings.
Project layout
src/ httpClients/ SupabaseAuthClient.ts # this post SupabaseStorageClient.ts # later post in the series GithubApiClient.ts # the portfolio data API index.ts # barrel export __tests__/ SupabaseAuthClient.rntl.ts schemas/ supabase.auth.schema.ts # Zod schemas for requests + responses utils/ storage/ SecureStore.ts # Keychain wrapper, tier 1 EncryptedStore.ts # AES-256 wrapper, tier 2 Each file has one job. The auth client doesn't know about storage internals; it imports the SecureStore wrapper and calls set/get. The storage wrapper doesn't know about Supabase. The schemas don't know about either. Three small modules instead of one large one.
The base client
// src/httpClients/SupabaseAuthClient.ts import Config from 'react-native-config'; import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios'; import { EncryptedStore, EncryptedStoreKey, SecureStore, SecureStoreKey } from '@app/utils/storage'; class SupabaseAuthClientClass { private axiosInstance: AxiosInstance; constructor() { this.axiosInstance = axios.create({ baseURL: Config.SUPABASE_URL, timeout: 10_000, headers: { 'Content-Type': 'application/json', apikey: Config.SUPABASE_ANON_KEY, }, }); this.axiosInstance.interceptors.request.use(this.attachToken); } // ... methods follow } export const SupabaseAuthClient = new SupabaseAuthClientClass(); Three configuration choices worth flagging.
The 10-second timeout. Most calls finishing past 10s are network problems; the few that aren't (cold-start serverless functions, an under-provisioned instance) are rare enough that timing them out is the right default. The Axios default of no timeout lets requests hang forever, which means a flaky cell signal manifests as a frozen UI rather than an error message.
The apikey default header. Supabase requires it on every call. Setting it once on the instance means you never forget it on a new endpoint.
Content-Type: application/json as a default. Supabase's auth endpoints expect JSON bodies. The header is harmless on GET requests and required on POST/PATCH.
The request interceptor
Every authenticated call needs a Bearer token. Reading from the Keychain on every call has a real cost: it's a syscall, not a hashmap lookup, and on configurations with biometric access control it can trigger a user-presence check.
private attachToken = async ( config: InternalAxiosRequestConfig ): Promise<InternalAxiosRequestConfig> => { const accessToken = await SecureStore.get(SecureStoreKey.ACCESS_TOKEN); if (accessToken) { config.headers.Authorization = `Bearer ${accessToken}`; } return config; }; The interceptor runs on every request through the instance. If the user isn't signed in, accessToken is null and the call goes through with just the anon key. If they are signed in, the access token attaches as a Bearer header and Supabase resolves the request as that user.
💡 One production refinement. For higher-traffic apps, or for a Keychain configuration with biometric access control on the access token, layer an in-memory cache on top of this interceptor. Sign-in writes the token to both the Keychain and the cache; the interceptor reads from the cache; refresh and sign-out keep both in sync. The Keychain stays the source of truth across cold starts. The pattern shown above reads on every call, which is fine for the tiered-storage configuration this series uses, but it's not the only choice.
ℹ️ Why not pass the token explicitly to each call. That is the obvious alternative, and it fails quietly. Forgetting to attach it on a single endpoint is a bug that doesn't crash anything. The call goes through unauthenticated, the RLS policy filters everything, and the screen renders empty. Centralising token attachment in an interceptor makes "not authenticated when you should be" impossible by construction.
Sign-up
async signUp(request: SupabaseSignUpRequest): Promise<SupabaseSignUpResponse> { try { const { data } = await this.axiosInstance.post('/auth/v1/signup', request); // This client assumes email confirmation is on (the Supabase default), so // /auth/v1/signup returns the user object directly. const user = validateResponse(SupabaseUserSchema, data, 'Supabase Auth signUp'); if (user) { await EncryptedStore.set(EncryptedStoreKey.USER_EMAIL, user.email); await SecureStore.set(SecureStoreKey.USER_ID, user.id); } return { user, session: null }; } catch (error) { throw this.handleError(error); } } A few things worth calling out.
Email confirmation is the default Supabase behaviour, and this client assumes it stays on. With confirmation required, /auth/v1/signup returns just the user object, and that's the shape the Zod schema validates. If your project has confirmation disabled, the endpoint returns the session fields directly (access token, refresh token, user) rather than a bare user, and this method would need to store that session the way signIn does. Scoping the client to one configuration keeps the validation honest instead of pretending one schema covers both.
Email and ID are stored immediately. Email goes into the AES-256 EncryptedStore (it's PII, but you need it for the profile screen). The ID goes into the Keychain (it's used to identify the user in subsequent requests).
No tokens are stored on signup. A user who needs to confirm their email doesn't have a session yet. signIn is what produces a session.
Sign-in
async signIn(request: SupabaseSignInRequest): Promise<SupabaseSignInResponse> { try { const { data } = await this.axiosInstance.post( '/auth/v1/token?grant_type=password', request, ); const validatedData = validateResponse( SupabaseSignInResponseSchema, data, 'Supabase Auth signIn', ); await this.storeSession(validatedData); await EncryptedStore.set(EncryptedStoreKey.USER_EMAIL, validatedData.user.email); await SecureStore.set(SecureStoreKey.USER_ID, validatedData.user.id); return validatedData; } catch (error) { throw this.handleError(error); } } private async storeSession(session: SupabaseSignInResponse): Promise<void> { await SecureStore.set(SecureStoreKey.ACCESS_TOKEN, session.access_token); await SecureStore.set(SecureStoreKey.REFRESH_TOKEN, session.refresh_token); } The endpoint is /auth/v1/token?grant_type=password, the OAuth2 password grant flow that returns an access token, a refresh token, and the user object in one response.
storeSession is private and tiny on purpose. It's the only place tokens get written. If you ever need to add observability around token storage, change the storage tier, or add encryption-at-rest verification, you change one method and every call site stays the same.
Logout
async logout(): Promise<void> { try { await this.axiosInstance.post('/auth/v1/logout'); } catch (error) { // Server-side logout failure shouldn't block local logout. // Clearing the local session is more important than telling Supabase about it. } finally { await this.clearSession(); } } private async clearSession(): Promise<void> { await SecureStore.clear(); await EncryptedStore.clear(); } The finally block is load-bearing. The user-facing meaning of "log out" is "wipe my session from this device". If the server is unreachable, the call fails, but the local clear still has to happen. Otherwise tapping log-out leaves the user logged in until they get connectivity again, which is the worst possible UX for a security action.
The try still attempts the server-side logout because Supabase tracks active sessions and revoking the refresh token server-side prevents an attacker who stole the device's refresh token from continuing to use it.
Getting the current user
async getCurrentUser(): Promise<SupabaseUser | null> { const accessToken = await SecureStore.get(SecureStoreKey.ACCESS_TOKEN); if (!accessToken) { return null; } try { const { data } = await this.axiosInstance.get('/auth/v1/user'); return validateResponse(SupabaseUserSchema, data, 'Supabase Auth getCurrentUser'); } catch (error) { if (axios.isAxiosError(error) && error.response?.status === 401) { return null; } throw this.handleError(error); } } A 401 means the access token is expired or invalid. The token-refresh interceptor (covered in the next post) handles refresh transparently for most requests. getCurrentUser is the exception: when called at app startup before any other request has fired, a 401 means there's no valid session, and the right answer is to return null so the app knows to show the login screen instead of throwing.
The Keychain pre-check at the top matters more than it looks: once the next post's refresh interceptor is installed on this instance, a no-session 401 would trigger a refresh attempt that fails with a different status, and the error reaching this method would no longer be a 401, so a cold start would throw instead of showing login. Reading the token first means "no session" never touches the network at all.
Every other error gets converted to an AuthError and rethrown.
Typed errors
The SDK throws errors with a message string. The custom client throws an AuthError with both a user-facing message and a machine-readable code, so the UI can switch on the code while the user sees the message.
export class AuthError extends Error { public readonly code?: string; constructor(message: string, code?: string) { super(message); this.name = 'AuthError'; this.code = code; if (Error.captureStackTrace) { Error.captureStackTrace(this, AuthError); } } } The handleError method centralises the conversion from Supabase's various error formats into one normalised type:
private handleError(error: unknown): AuthError { if (axios.isAxiosError(error)) { const errorData = error.response?.data as SupabaseErrorResponse; // Supabase's preferred error_code field if (errorData?.error_code) { switch (errorData.error_code) { case 'email_not_confirmed': return new AuthError('Email not confirmed', 'email_not_confirmed'); case 'user_already_exists': return new AuthError('User already exists', 'user_already_exists'); case 'invalid_credentials': return new AuthError('Invalid email or password', 'invalid_credentials'); default: return new AuthError( errorData.msg || errorData.message || 'An error occurred', errorData.error_code, ); } } // OAuth error format if (errorData?.error_description) { return new AuthError(errorData.error_description); } // Status-code fallbacks for endpoints that don't return error_code switch (error.response?.status) { case 400: return new AuthError('Invalid email or password', 'invalid_credentials'); case 422: return new AuthError('Email already registered', 'user_already_exists'); case 429: return new AuthError('Too many attempts. Please try again later.', 'rate_limit_exceeded'); case 500: return new AuthError('Server error. Please try again later.', 'server_error'); default: return new AuthError('An unexpected error occurred'); } } return error instanceof Error ? new AuthError(error.message) : new AuthError('Unknown error'); } Three layers of fallback because Supabase's error response shape is inconsistent between endpoints:
- The newer
error_codeformat, preferred by/auth/v1/*endpoints. - The OAuth-style
error_descriptionformat returned by some token-grant flows. - A status-code fallback for cases where neither shape is present.
The default branch catches the rest with a generic message. That keeps AuthError total: every code path returns one, never throws or returns undefined.
A component using the client switches on the code:
try { await SupabaseAuthClient.signIn({ email, password }); navigation.navigate('Home'); } catch (error) { if (error instanceof AuthError) { if (error.code === 'email_not_confirmed') { navigation.navigate('VerifyEmail', { email }); return; } if (error.code === 'rate_limit_exceeded') { showToast({ message: error.message, severity: 'warning' }); return; } setFormError(error.message); } } The component never parses Supabase's error response. The auth client is the one place that translation happens.
Testing the client
MSW intercepts the network calls at the right layer for these tests: Axios fires real HTTP requests, MSW catches them before they leave the process, returns canned responses, and the rest of the client (validation, error mapping, storage calls) runs as it would in production. Storage modules are stubbed with jest.mock so the test can assert which keys would have been written, without standing up a real Keychain.
// src/httpClients/__tests__/SupabaseAuthClient.rntl.ts import { http, HttpResponse } from 'msw'; import { server } from '@app/test-utils/msw/server'; import { AuthError, SupabaseAuthClient } from '../SupabaseAuthClient'; jest.mock('react-native-config', () => ({ SUPABASE_URL: 'https://test.supabase.co', SUPABASE_ANON_KEY: 'test-anon-key', })); jest.mock('@app/config/e2e', () => ({ isE2EMockEnabled: jest.fn(() => false), })); jest.mock('@app/utils/storage/EncryptedStore', () => ({ EncryptedStore: { set: jest.fn(), get: jest.fn(), clear: jest.fn() }, EncryptedStoreKey: { USER_EMAIL: 'userEmail' }, })); jest.mock('@app/utils/storage/SecureStore', () => ({ SecureStore: { get: jest.fn(), set: jest.fn(), clear: jest.fn() }, SecureStoreKey: { ACCESS_TOKEN: 'accessToken', REFRESH_TOKEN: 'refreshToken', USER_ID: 'userId', }, })); const SUPABASE_URL = 'https://test.supabase.co'; const mockUser = { id: '550e8400-e29b-41d4-a716-446655440000', aud: 'authenticated', email: 'warren@example.com', email_confirmed_at: '2026-01-01T00:00:00Z', phone: null, confirmed_at: '2026-01-01T00:00:00Z', last_sign_in_at: '2026-01-01T00:00:00Z', created_at: '2026-01-01T00:00:00Z', }; describe('SupabaseAuthClient.signIn', () => { const { SecureStore, SecureStoreKey } = require('@app/utils/storage/SecureStore'); beforeEach(() => { jest.clearAllMocks(); server.resetHandlersSource:https://dev.to/warrendeleon/building-an-axios-based-supabase-auth-client-in-react-native-4k29Related posts
Node.js SMS OTP Login — Seller Rate Limiting, Retry, and Replay Evidence
