पाठ 12 / 25

Authentication Flows

Different screens for signed-in and signed-out users.

Guarded routes

Signed-out users should see welcome and sign-in screens, signed-in users the app, and the back button should not lead from the app back to the login screen. The common pattern is to keep auth state in a context or store, show a splash screen while restoring the saved session, and then render different route groups depending on whether a user is signed in. In React Navigation you conditionally render screens inside the navigator. Expo Router supports redirects (<Redirect href="/sign-in" />) in layouts, and recent versions add protected routes (Stack.Protected with a guard prop); check the docs for your version. Keep the token in secure storage, not plain storage.

Redirecting signed-out users

A layout that guards a route group (Expo Router; sketch).

// app/(app)/_layout.tsx  - everything in (app) requires a session
import { Redirect, Stack } from "expo-router";
import { Text } from "react-native";
import { useSession } from "../../src/auth";   // your own context

export default function AppLayout() {
  const { session, isLoading } = useSession();

  if (isLoading) return <Text>Loading...</Text>;       // or keep the splash screen visible
  if (!session) return <Redirect href="/sign-in" />;  // signed out -> sign-in screen

  return <Stack />;
}

Use replace after signing in

After a successful sign-in, replace the route instead of pushing, so the back gesture does not return to the login form.

A building with a reception desk

Visitors without a badge only reach the lobby. Once badged, they go straight through, and leaving the office does not send them back through the turnstile.

त्वरित जाँच: What is a good way to keep signed-out users out of app screens?

  • Hide the screens with opacity 0
  • Render different route groups or redirect based on auth state
  • Ask users not to press back
  • Store the password in a global variable
Answer

Render different route groups or redirect based on auth state — Navigation follows the auth state.