DEV Community

Cathy Lai
Cathy Lai

Posted on

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

The directory structure

(Refer to Introduction for details)

OAuth Prototype App Directory structure

Reference

For more details on Expo Router Protected routes: Expo Router

Top comments (1)

Collapse
 
bhavin-allinonetools profile image
Bhavin Sheth

Nice and clear explanation.

I like how you used Expo Router’s protected routes with Clerk — the guard logic is easy to follow, especially for people new to auth flows.

Looking forward to the next part of the series.