Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit 9460d2d · 15 days ago

Expo, part 2: project on expo-router — navigation, login, and secure token storage

🌐 Machine-translated from Russian. Show original

In this part:

Creating a project#

npx create-expo-app@latest my-app
cd my-app
npx expo start

The default template already includes TypeScript and expo-router. Set SDK modules with the command npx expo install, not npm install — it will select the version compatible with your SDK:

npx expo install expo-secure-store expo-constants expo-notifications expo-image

Before building and after updates, run a project validation:

npx expo-doctor@latest

Structure of the Kommit Chat"#

src/
  app/                  ← экраны (каждый файл — маршрут)
    _layout.tsx         ← корневой навигатор, сессия, поток событий
    sign-in.tsx         ← вход
    index.tsx           ← список диалогов
    chat/[id].tsx       ← переписка (динамический параметр id)
    new.tsx             ← новый диалог
    report.tsx          ← жалоба (модальное окно)
    settings.tsx
    delete-account.tsx
  components/           ← общие элементы интерфейса
  lib/
    api.ts              ← клиент API и хранение токена
    session.tsx         ← контекст сессии
    stream.ts, sse.ts   ← реальное время
    push.ts             ← уведомления
app.json                ← конфигурация Expo и плагинов
eas.json                ← профили сборки

Business logic without React (SSE parsing, date formatting) lies in lib/ and is covered by simple tests on the built-in node --test — without an emulator.

app.json: main points#

{
  "expo": {
    "name": Kommit Чат",
    "slug": "ITgovChatApp",
    "scheme": "itgovchat",
    "ios": { "bundleIdentifier": "kz.itgov.chat" },
    "android": {
      "package": "kz.itgov.chat",
      "blockedPermissions": ["android.permission.RECORD_AUDIO"]
    },
    "plugins": ["expo-router", "expo-secure-store", "expo-notifications"],
    "experiments": { "typedRoutes": true },
    "extra": { "apiUrl": "https://itgov.kz" }
  }
}
  • package / bundleIdentifier is the app identifier in stores. After publishing, it cannot be changed — choose immediately (usually the reverse domain: kz.company.app).
  • scheme — deep link scheme (itgovchat://chat/123).
  • blockedPermissions — remove permissions that libraries add "just in case." Excessive resolution (microphone, storage) — unnecessary questions on moderation and in the data security questionnaire.
  • typedRoutes — TypeScript checks paths: a typo in /chta/[id] will not be compiled.
  • extra.apiUrl — backend address; read as expo-constants.

In the root _layout.tsx , declare the stack and divide the screens into "before entry" and "after entry" after Stack.Protected:

import { Stack } from 'expo-router';
import { SessionProvider, useSession } from '@/lib/session';

function RootStack() {
  const { ready, me } = useSession();
  if (!ready) return <Loading />;          // пока читаем токен — заставка
  const signedIn = !!me;
  return (
    <Stack>
      <Stack.Protected guard={!signedIn}>
        <Stack.Screen name="sign-in" options={{ headerShown: false }} />
      </Stack.Protected>
      <Stack.Protected guard={signedIn}>
        <Stack.Screen name="index" options={{ title: 'Сообщения' }} />
        <Stack.Screen name="chat/[id]" options={{ title: '' }} />
        <Stack.Screen name="report" options={{ title: 'Жалоба', presentation: 'modal' }} />
        <Stack.Screen name="settings" options={{ title: 'Настройки' }} />
        <Stack.Screen name="delete-account" options={{ title: 'Удаление аккаунта' }} />
      </Stack.Protected>
    </Stack>
  );
}

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

How it works: if the guard is false, the screen is unavailable, and the router sends the user to the available one. Logged out of account — the history of "closed" screens is cleared; you cannot go back with the button. With SDK 58, Stack.Protected has prop redirectToto explicitly indicate where to go.

Navigating to the screen with the parameter:

import { router } from 'expo-router';
router.push({ pathname: '/chat/[id]', params: { id } });

The site operates on a cookie session, but a token is more convenient for the mobile app. On the server, we created separate routes /api/m/*:

  • POST /api/m/auth/login — login and password → device token (lasts 90 days and is renewed upon use);
  • POST /api/m/auth/logout — token withdrawal;
  • All other queries are headed Authorization: Bearer <токен>.

The advantage of this approach is that the user sees a list of devices on the site, the administrator can revoke the token, and deleting an account or blocking immediately "kicks out" the app.

Where to store the token#

StorageSuitable for the token?
AsyncStorage❌ a regular unencrypted file
expo-secure-store✅ Keychain on iOS, Keystore encryption on Android
in-memory variableonly as cache on top of SecureStore
import * as SecureStore from 'expo-secure-store';

const TOKEN_KEY = 'itgov.token';
let token: string | null = null;           // кэш в памяти, чтобы не читать хранилище на каждый запрос

export async function loadToken() {
  token = await SecureStore.getItemAsync(TOKEN_KEY).catch(() => null);
  return token;
}

export async function saveToken(t: string | null) {
  token = t;
  if (t) await SecureStore.setItemAsync(TOKEN_KEY, t);
  else await SecureStore.deleteItemAsync(TOKEN_KEY).catch(() => undefined);
}

⚠️ SecureStore does not work in the browser version (web), and push does not work in Expo Go. Therefore, the development of Kommit Chat" is based on a development build on a real phone.

We never store the password in the app — only the token. We do not write the token in logs or bug reports.

Session context#

Session — React context: at startup, read the token, load the profile, and when exiting, clean everything.

export function SessionProvider({ children }: { children: ReactNode }) {
  const [ready, setReady] = useState(false);
  const [me, setMe] = useState<Me | null>(null);

  const loadMe = useCallback(async () => {
    const r = await api<{ user: Me }>('/api/m/me');
    setMe(r.user);
  }, []);

  useEffect(() => {
    // сервер ответил 401 (токен отозван) — возвращаемся к экрану входа
    setUnauthorizedHandler(() => {
      saveToken(null).catch(() => undefined);
      setMe(null);
    });
    (async () => {
      if (await loadToken()) await loadMe().catch(() => undefined);
      setReady(true);
    })();
  }, [loadMe]);

  const signIn = useCallback(async (email: string, password: string) => {
    const r = await login(email.trim(), password);
    await saveToken(r.token);
    await loadMe();
  }, [loadMe]);

  const signOut = useCallback(async () => {
    await api('/api/m/auth/logout', { method: 'POST' }).catch(() => undefined);
    await saveToken(null);
    setMe(null);
  }, []);

  const value = useMemo(() => ({ ready, me, signIn, signOut }), [ready, me, signIn, signOut]);
  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
}

Note: logout first revokes the token on the server, then deletes it on the phone. If the server is unavailable, we still log out locally.

Account deletion screen — immediately#

If you can create or sign in to an account in the app, Google Play and the App Store require the ability to delete the account (more details in part 6: Expo, part 6: publishing to Google Play and the App Store — accounts, testing, account deletion, and data questionnaires). We created the screen immediately, not before publishing:

  • a warning about exactly what is being deleted (we share the account with the site);
  • confirmation with a password and the word "DELETE";
  • DELETE /api/m/account → local output;
  • a link to the web page describing the deletion — you also specify it in Google Play.

Project checklist#

  • package and bundleIdentifier are finally selected
  • Modules are installed every npx expo install, expo-doctor without errors
  • Extra permissions are blocked
  • Screens are divided into protected and open
  • Token — only in SecureStore, password not stored
  • 401 from the server returns to the login screen
  • There is an account deletion screen

Next — how the app talks to the backend: Expo, part 3: communication with the backend — API client, real-time via SSE, errors, and offline.

Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.