Skip to Content

Expo Router

Save the session in the device's secure storage, hold the splash screen while it restores, and keep deep links across sign-in.

People who open your Expo app expect to find themselves still signed in, to land on the screen a link points to, and not to see the sign-in screen flash past while the app starts. In this guide, you build an Expo Router app for iOS and Android that does that. It saves the session in the device's secure storage, holds the splash screen while the session restores, and keeps a deep link across sign-in.

The app is a shorter version of the expo-router example app. It signs in against DummyJSON's auth API, so it runs as written. The example adds a few extras, such as one-minute tokens so you can watch a refresh, and its links use the scheme sessionkit where this page uses myapp. Its src/auth.ts takes the place of Getting started's backend.ts and auth.ts.

This page covers what differs on Expo. Using the client, Refresh and Errors explain how the client works.

Before you begin

  • Expo SDK 53 to 58, with the Expo Router and React Native versions that come with your SDK. Compatibility lists the versions.
  • An app for iOS and Android. Expo web isn't supported. On the web, use a web router setup with webStorage().
  • Expo Go, which includes expo-secure-store and expo-file-system, or a development build with both installed.

Installation

Install the package, its Expo peers, the splash screen module and a schema library. npx expo install picks the versions that match your SDK:

npx expo install @monarcode/session-kit expo-secure-store \
  expo-file-system expo-splash-screen zod

An Expo Router app already has expo-router and react-native. expo-splash-screen is what holds the splash screen. Without it, holding does nothing, and the app shows while the session is still restoring.

Then add the expo-secure-store config plugin to app.json. It keeps the session out of Android's Auto Backup, and adds the Face ID permission on iOS:

{
  "expo": {
    "scheme": "myapp",
    "plugins": ["expo-router", "expo-secure-store"]
  }
}

scheme is what custom-scheme deep links such as myapp://profile use. Expo Go opens its own exp:// links instead, and doesn't apply config plugins, so both take effect in a development or release build. Reinstalls and Android backups says more about the backup rules.

1. Create the client

secureStorage() replaces webStorage(). The rest of the client is the same as on the web:

src/auth.ts
import {  } from "@monarcode/session-kit";
import {  } from "@monarcode/session-kit/expo";
import {  } from "@monarcode/session-kit/http";
import {  } from "zod";

const  = "https://dummyjson.com";

export const  = .({
  : .(),
  : .(),
  : .(),
  : .(),
});

const  = .({
  : .(),
  : .(),
});
const  = .(.);

export const  = ({
  : "my-app",
  : ,
  : (),
  // Logs what Session kit does to Metro, in development only.
  : ,
  : async ({ ,  }) => {
    const  = await (`${}/auth/refresh`, {
      : "POST",
      ,
      : { "Content-Type": "application/json" },
      : .({  }),
    });
    // DummyJSON answers 401 or 403 when the refresh token is no good.
    if (. === 401 || . === 403) return null;
    if (!.) throw new (`Refresh failed (${.})`);
    return .(await .());
  },
});

export const  = (, { : `${}/` });

export async function (: string, : string) {
  const  = await (`${}/auth/login`, {
    : "POST",
    : { "Content-Type": "application/json" },
    : .({ ,  }),
  });
  if (!.) throw new (`Sign-in failed (${.})`);
  const { , , ... } = .(
    await .(),
  );
  await .({ , ,  });
}

Turn on debug logs says what debug adds on Expo.

2. Add the unavailable screen

Sometimes there's a saved session that can't be used: a refresh failed, often because the device is offline, or the keychain couldn't be read. Access is then unavailable, and the gate you add in the next step shows this screen in place of the app. It receives the error and a retry function:

src/unavailable.tsx
import { , ,  } from "react-native";

import type {  } from "@monarcode/session-kit/expo";

import {  } from "./auth";

export function ({ ,  }: ) {
  return (
    < ={{ : 1, : "center", : 24, : 12 }}>
      < ="header">Can't reach your account</>
      <>{?. ?? "Check your connection and try again."}</>
      < ="Try again" ={} />
      {/* Works offline: it clears the session on this device. */}
      <
        ="Sign out"
        ={() => void .().(() => {})}
      />
    </>
  );
}

Without an unavailable screen, the gate hides the splash screen and throws the error to the root layout's ErrorBoundary instead. That boundary's retry only renders again, so have it call auth.retry() too, as SessionGateProps explains.

3. Gate the root layout

SessionGate goes inside AuthProvider, around the root navigator. Guard the screens with Stack.Protected: signed-in users see the (app) group, and everyone else sees login. Register the client's type here too, so the hooks from @monarcode/session-kit/react carry your user:

app/_layout.tsx
import {  } from "@monarcode/session-kit";
import {  } from "@monarcode/session-kit/expo";
import { ,  } from "@monarcode/session-kit/react";
import { ,  } from "expo-router";

import {  } from "../src/auth";
import {  } from "../src/unavailable";

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    : typeof ;
  }
}

// Keeps the splash screen up until SessionGate hides it.
void .();

export default function () {
  return (
    < ={}>
      < ={() => < {...} />}>
        < />
      </>
    </>
  );
}

function () {
  // Not signed in while locked, though a locked session keeps its user.
  const  = ();
  return (
    < ={{ : false }}>
      <. ={}>
        <. ="(app)" />
      </.>
      <. ={!}>
        <. ="login" />
      </.>
    </>
  );
}

RootStack is its own component so that useAuth runs inside AuthProvider. SessionGate mounts the navigator only after the session is restored, so the guards never see initializing.

If the first screen needs more than the session, such as fonts, pass ready as well. The splash screen then stays up until both are done. Count a failed load as done, or the splash screen never hides: with Expo Font's useFonts, pass ready={fontsLoaded || fontError !== null}. SessionGateProps describes ready.

Stack.Protected sends a link to a guarded screen to the first screen the user may see. So a signed-out user who opens myapp://profile lands on the sign-in screen, and the link is lost. deepLinkHandler keeps the link, and SessionGate opens it after the sign-in. Expo Router calls redirectSystemPath with every URL that opens the app, before routing:

app/+native-intent.tsx
import {  } from "@monarcode/session-kit/expo";

import {  } from "../src/auth";

export const  = ();

It returns the path unchanged, so the link still goes to Expo Router, which shows it right away when the user is signed in. If your redirectSystemPath does more, such as rewriting old links, call rememberDeepLink(auth, path) in it instead. How deep links are kept has the rules.

5. Add the sign-in screen

The sign-in screen calls signInWithPassword from src/auth.ts:

app/login.tsx
import {  } from "react";
import { , , ,  } from "react-native";

import {  } from "../src/auth";

export default function () {
  // DummyJSON's documented test user.
  const [, ] = ("emilys");
  const [, ] = ("emilyspass");
  const [, ] = ("");

  async function () {
    ("");
    try {
      await (, );
      // No navigation: Stack.Protected leaves this screen, and
      // SessionGate opens the deep link the user was headed to.
    } catch () {
      ( instanceof  ? . : "Could not sign in");
    }
  }

  return (
    < ={{ : 1, : "center", : 24, : 12 }}>
      <
        ="Username"
        ={}
        ={}
        ="none"
      />
      <
        ="Password"
        ={}
        ={}
        
      />
      { ? < ="alert">{}</> : null}
      < ="Sign in" ={() => void ()} />
    </>
  );
}

The guards already decide where a signed-in user belongs, so the screen doesn't navigate after signIn. After the user signs in, Stack.Protected removes the sign-in screen. A router.replace of your own would race the deep link that SessionGate opens.

6. Add the signed-in screens

Screens inside the guarded group read the user with useAuth. They call the API with authFetch, which adds the access token and refreshes after a 401. To use axios or another HTTP client instead, see Other HTTP clients. The group's layout is a plain stack:

app/(app)/_layout.tsx
import {  } from "expo-router";

export default function () {
  return < />;
}

Its first screen shows the user's name, links to the profile, and signs out:

app/(app)/index.tsx
import { , ,  } from "react-native";

import { ,  } from "@monarcode/session-kit/react";
import {  } from "expo-router";

export default function () {
  const  = (() => .?.);
  const  = ();
  return (
    < ={{ : 1, : "center", : 24, : 12 }}>
      < ="header">Welcome, {}</>
      < ="/profile">Profile</>
      {/* No navigation: Stack.Protected then shows the sign-in screen. */}
      <
        ="Sign out"
        ={() => void .().(() => {})}
      />
    </>
  );
}

The profile screen fetches the user from the API. It's also where a deep link such as myapp://profile goes:

app/(app)/profile.tsx
import { ,  } from "react";
import { ,  } from "react-native";

import {  } from "zod";

import { ,  } from "../../src/auth";

const  = .({
  : .(),
  : .(),
});

export default function () {
  const [, ] = <.<typeof >>();
  const [, ] = ("");

  (function () {
    const  = new ();
    ("auth/me", { : . })
      .(async () => {
        if (!.)
          throw new (`Profile failed (${.})`);
        (.(await .()));
      })
      .((: unknown) => {
        if (..) return;
        ( instanceof  ? . : "Could not load");
      });
    return function () {
      .();
    };
  }, []);

  if () return < ="alert">{}</>;
  if (!) return <>Loading…</>;
  return (
    < ={{ : 24, : 8 }}>
      < ="header">
        {.} {.}
      </>
      <>{.}</>
      <>{.}</>
    </>
  );
}

7. Check the app

Run the app, and check each part of the session:

  1. Sign in. The home screen shows your name. Open the profile to see your email.
  2. Close the app and open it again. The splash screen stays up until the session is restored, then the home screen shows.
  3. Sign out. The sign-in screen shows.
  4. While signed out, open myapp://profile. On the iOS Simulator, run xcrun simctl openurl booted myapp://profile. In Expo Go, open exp://HOST:8081/--/profile instead, and replace HOST with the address Expo CLI prints for Metro. Sign in. The profile screen opens.

That's the whole app. The rest of this page explains what secureStorage(), SessionGate and the deep link handler do on the device.

Secure storage

secureStorage() saves the session with expo-secure-store: in the iOS keychain, and in storage encrypted with an Android Keystore key on Android. A session too large for one SecureStore value is split across several keys, up to 128 KB, as its reference explains. Its options are in SecureStorageOptions.

Reinstalls and Android backups

iOS keeps keychain items after the app is deleted. So by default, secureStorage() removes a session that an earlier install left, and a reinstalled app starts signed out. To restore that session instead, pass secureStorage({ clearOnReinstall: false }).

On Android, Auto Backup can restore the app's data onto another device. The session can't be decrypted there, so the app starts signed out, and the unreadable session is removed. The expo-secure-store config plugin from Installation keeps the session out of backups, with two conditions:

  • It applies in a development or release build. Expo Go doesn't apply config plugins.
  • If your app already has its own backup rules, the plugin leaves them as they are and prints a warning. Exclude SecureStore's data in your rules yourself, as Expo's SecureStore docs explain.

Keychain access on iOS

By default, iOS lets the app read the keychain only while the device is unlocked. What happens when the keychain is locked depends on what's reading it:

  • When the app starts, a keychain that can't be read leaves the session unavailable, not signed out. SessionGate tries again when the app returns to the foreground.
  • When a refresh runs, it can't save the new tokens to a locked keychain, and that signs the user out.

An app that refreshes in a background task while the device is locked needs secureStorage({ keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK }), with SecureStore imported from expo-secure-store.

What SessionGate does

SessionGate adds what Stack.Protected lacks:

  • It holds the splash screen while the session is restored, and until ready.
  • It shows unavailable when access can't be used.
  • It checks the session again when the app returns to the foreground, since timers don't run while iOS suspends the app.
  • It opens the deep link kept for after the sign-in.

While the session is locked, it renders the navigator, so your guards can show an unlock screen. When one account replaces another without a sign-out between them, it remounts the navigator, so no screen keeps the previous account's state.

deepLinkHandler keeps one link at a time, and SessionGate opens it after the next sign-in or unlock. Some links aren't kept, or are dropped before then:

  • A link to the root or the sign-in screen is ignored, as is one that could leave the app.
  • A link that arrives while the user is signed in is dropped, since Expo Router opens it as usual.
  • A link to a screen anyone may see is dropped when that screen shows. If the app launched with such a link, it's dropped at the sign-in instead, unopened.

If your sign-in screen isn't /login, pass deepLinkHandler(auth, { loginPath: "/sign-in" }).

Where Stack.Protected takes a redirectTo, as in Expo SDK 58, it only chooses the screen a turned-away link goes to, such as /login. It doesn't keep the link, so deepLinkHandler is still what opens it after the sign-in.

There's no ?redirectTo= parameter on Expo. The link waits in memory, not in the URL, and an app restart forgets it.

Turn on debug logs

The client in step 1 sets debug: __DEV__, so in development the app logs what Session kit does to Metro. SessionGate and the deep link handler report through the same option. They log why the splash screen is held (restoring, or waiting for ready), when it hides, and what happened to a remembered link. secureStorage() adds what only it can see, such as removing a session an earlier install left. Debugging covers what the logs leave out, and how to send them somewhere other than the console.

Locking

A returning user can be asked to unlock before the app opens: a "Welcome back" screen with Face ID, Touch ID or a fingerprint, and the password as a fallback. Unlock with biometrics adds that to this guide's app, step by step. Locking explains how a locked session behaves.

Not supported

  • Expo web. secureStorage() and SessionGate are for iOS and Android.
  • requireAuthentication. secureStorage() doesn't use SecureStore's biometric prompt. A session that refreshes on its own can't ask for a face or fingerprint on every read and write. Keep a key behind the prompt instead, and seal the session with it, as Unlock with biometrics shows.
  • Network status. Session kit doesn't watch connectivity. When your app learns the device is back online, for example from @react-native-community/netinfo, call auth.retry(), or the retry that unavailable receives.

Next steps

On this page