Login with Google on an iPhone (Local Metro server + Dev Build) – Part 5/7: Expo Router Setup

Quick recap!

From step 1-4, we have

  • Install the necessary packages Step 1
  • Create a Clerk Project Step 2
  • Add the Clerk API key Step 3
  • Created and Configured the Google Cloud Console Step 4

Set up the routes

In this step we will use the Expo Router new “Protected” route (available after Expo Router SDK 53) to guard our protected page.

The root layout will now have ClerkProvider wrapped around it.

_layout.tsx

export default function RootLayout() {
  const publishableKey =
    process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ??
    EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY;
  if (!publishableKey) {
    throw new Error(
      "Missing EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY. Set it in your .env (see Clerk Expo quickstart) or in env.ts."
    );
  }

{* ClerkProvider with 
 *     - publishableKey
 *     - tokenCache
 *}
  return (
    <ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
      <RootLayoutNav />
    </ClerkProvider>
  );
}

Setting up the routes for the two pages “login”, “protected”

_layout.tsx

function RootLayoutNav() {
  const { isLoaded, isSignedIn } = useAuth();
  const isLoggedIn = isLoaded && isSignedIn;

  return (
    <Stack>
      {/* Only available when NOT logged in */}
      <Stack.Protected guard={!isLoggedIn}>
        <Stack.Screen name="(auth)/login" options={{ title: "Login" }} />
      </Stack.Protected>

      {/* Only available when logged in */}
      <Stack.Protected guard={isLoggedIn}>
        <Stack.Screen
          name="(protected)/protected"
          options={{ title: "Protected" }}
        />
      </Stack.Protected>

      {/* Public screens */}
      <Stack.Screen name="index" options={{ title: "Home" }} />
    </Stack>
  );
}

Don’t forget the imports

_layout.tsx

import { ClerkProvider, useAuth } from "@clerk/clerk-expo";
import { tokenCache } from "@clerk/clerk-expo/token-cache";
import { Stack } from "expo-router";
import { EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY } from "../env";

The directory structure

(Refer to Introduction for details)

OAuth Prototype App Directory structure

Reference

For more details on Expo Router Protected routes: Expo Router

Leave a Reply