Caracal Starter
Guides

Authentication

How the starter handles sign up, sign in and sessions.

Caracal ships a complete sign-up and sign-in flow that runs entirely on the device. Accounts and the session are stored in MMKV, and the global auth state lives in a Zustand store.

This is a local demo. Accounts never leave the device, and there is no password reset or server-side validation. A real app should replace src/lib/auth/accounts.ts with calls to its own auth API and keep the rest of the flow (store, route guards, screens) as it is.

Local accounts

src/lib/auth/accounts.ts keeps a list of accounts under the MMKV key accounts:

  • createAccount({ fullName, email, password }) normalises the email (trimmed, lower case), rejects a duplicate email with AUTH_ERRORS.emailTaken, and stores the account with a random salt and a SHA-256 hash of salt + password (via expo-crypto). The plain password is never stored.
  • verifyCredentials({ email, password }) hashes the password with the stored salt and returns the account, or throws AUTH_ERRORS.invalidCredentials.
  • getAccountById(id) looks up an account for the session.

Authentication store

The store lives in src/lib/auth/store.ts and is re-exported from @/lib/auth:

  • status: idle before hydration, then signOut or signIn.
  • userId: the signed-in account id, persisted as the MMKV session key.
  • signIn(userId), signOut(): update the store and the session.
  • hydrate(): reads the session synchronously and signs in only if the account still exists.

Call hydrateAuth() once at module scope in src/app/_layout.tsx. Because MMKV reads are synchronous, the first render already has the right status, so no loading screen or redirect flash is needed.

Signing in and creating accounts

Forms call two async helpers from @/lib/auth:

import { AUTH_ERRORS, loginWithEmail, signUpWithEmail } from '@/lib/auth';

await loginWithEmail({ email, password }); // throws AUTH_ERRORS.invalidCredentials
await signUpWithEmail({ fullName, email, password }); // throws AUTH_ERRORS.emailTaken

Both sign the user in on success. The screens do not navigate afterwards: the Stack.Protected route guards in the root layout switch to the (home) tabs as soon as status becomes signIn (see the Navigation guide).

Reading the current user

useCurrentUser() returns the signed-in profile, or null:

import { useCurrentUser } from '@/lib/auth';

const user = useCurrentUser();
// { id, fullName, email, username: 'emily', initials: 'EJ' }

Signing out

Use useSignOut() inside components. It signs out and clears the React Query cache. Outside React, call signOut() directly, for example from an API interceptor:

import { signOut } from '@/lib/auth';

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      signOut();
    }
    return Promise.reject(error);
  }
);

Additional Resources

On this page