Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 71 ยท Navigation

Deep Linking and Authentication Flows

Open screens from URLs with schemes and universal links, configure linking, protect routes behind login, hold the splash screen and redirect after sign-in.

A deep link is a URL that opens a specific screen inside your app: myapp://orders/1042 or https://shop.example.com/orders/1042. Deep links power push notification taps, links in emails and messages, QR codes, and "continue in the app" buttons on your website. Without them, every outside entry point lands on your home screen.

Deep links bring a second problem: authentication. If the link opens a private screen and the user is signed out, the app must send them to login and, after signing in, take them to the page they asked for. This lesson covers URL schemes, universal links, the linking configuration, protected routes, the splash screen and redirect after login. It builds on Stack Navigation with React Navigation and File-Based Routing with Expo Router.

What runs on this site. Real deep links need an installed app and an operating system, so the real code and configuration are read-only. The runnable examples are stand-ins: a URL-to-screen resolver that follows the same path-pattern idea as the linking config, and a small state machine for sign-in and redirect. They run in the browser with plain JavaScript.

Custom URL schemes look like myapp://profile/7. You pick the scheme name, and the operating system hands any URL starting with it to your app. They are easy to set up, but nothing stops another app from claiming the same scheme, and a browser cannot open them if the app is missing. In an Expo project you declare the scheme in app.json:

JSON
{
  "expo": {
    "scheme": "myapp",
    "ios": { "associatedDomains": ["applinks:shop.example.com"] },
    "android": {
      "intentFilters": [
        {
          "action": "VIEW",
          "autoVerify": true,
          "data": [{ "scheme": "https", "host": "shop.example.com", "pathPrefix": "/orders" }],
          "category": ["BROWSABLE", "DEFAULT"]
        }
      ]
    }
  }
}

Universal links (iOS) and App Links (Android) are normal https:// URLs that open your app when it is installed and the website otherwise. They are safer because you prove you own the domain: iOS reads an apple-app-site-association file and Android reads assetlinks.json, both served from https://your-domain/.well-known/. These files list your app's identifiers, so only your app can claim the domain. The associatedDomains and intentFilters above tell the operating system which domains to check.

Custom schemes are fine for development, testing and links your own app creates. Use universal links for anything people share or that arrives from the web.

Two ways in

Custom scheme myapp://orders/42. Simple, not verified.
Universal link A real https URL, verified by your domain.

Prefer verified links for anything users share.

1 / 2

The linking configuration

With React Navigation you tell the container how URLs map to screens:

JSX
const linking = {
  prefixes: ['myapp://', 'https://shop.example.com'],
  config: {
    screens: {
      Home: '',
      Orders: {
        screens: {
          OrderList: 'orders',
          OrderDetail: 'orders/:id',
        },
      },
      Settings: 'settings',
      NotFound: '*',
    },
  },
};

<NavigationContainer linking={linking} fallback={<Text>Loading...</Text>}>
  {/* navigators */}
</NavigationContainer>

prefixes are the URL beginnings to strip. config.screens mirrors your navigator tree: each screen gets a path pattern, where :id becomes a route param (as a string; add parse: { id: Number } to convert it). Nested navigators nest under screens, and * is a catch-all for unknown URLs. Opening myapp://orders/1042 then navigates to Orders and inside it to OrderDetail with { id: '1042' }. The fallback is shown while the initial URL is being resolved.

In Expo Router you write no config: the file path is the URL (app/orders/[id].tsx is /orders/1042), and the scheme in app.json is all you need. That is why file-based routing makes deep links nearly free.

You can test links without a phone farm: with a simulator or emulator running your development build, npx uri-scheme open myapp://orders/1042 --ios (or --android) opens the link, and xcrun simctl openurl booted URL or adb shell am start -a android.intent.action.VIEW -d URL do the same.

A URL-to-screen resolver

The next TryIt implements the idea of the config: a list of patterns, a prefix stripper and a param extractor.

Resolve a URL to a screen (stand-in)

Notice that :id arrives as the string "1042" and that query parameters merge into the same params object. Unknown paths fall to NotFound, which is the job of '*' in a real config.

Protected routes

Most apps have a public area (login, sign up) and a private area (everything else). The classic mistake is to put both in the same stack and navigate('Login') when a user is signed out: the Back button then returns to a private screen. React Navigation's approach is conditional screens. You render only the screens that make sense for the current auth state:

JSX
function RootNavigator() {
  const { status, user } = useAuth();   // 'loading' | 'signedOut' | 'signedIn'

  if (status === 'loading') return null;

  return (
    <Stack.Navigator>
      {user ? (
        <>
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Orders" component={OrdersScreen} />
        </>
      ) : (
        <>
          <Stack.Screen name="SignIn" component={SignInScreen} />
          <Stack.Screen name="SignUp" component={SignUpScreen} />
        </>
      )}
    </Stack.Navigator>
  );
}

When user changes, the navigator swaps the whole set of screens and resets to the first one of the new set, with an animation. There is no navigate('Home') after login, and no way back to the sign-in screen with the Back button, because that screen no longer exists. The same logic protects deep links: a link to Orders while signed out has no matching screen, so it falls to the first available screen, SignIn.

In Expo Router, recent versions provide Stack.Protected, which works the same way:

TSX
// app/_layout.tsx
export default function RootLayout() {
  const { user } = useAuth();
  return (
    <Stack>
      <Stack.Protected guard={!!user}>
        <Stack.Screen name="(app)" />
      </Stack.Protected>
      <Stack.Protected guard={!user}>
        <Stack.Screen name="sign-in" />
      </Stack.Protected>
    </Stack>
  );
}

With older versions, the equivalent is a layout that renders <Redirect href="/sign-in" /> when there is no user. Never rely on hiding screens as your only security. The server must still check every request, because anything on the device can be inspected. See Mobile App Security.

Splash screen: wait until you know

The first thing your app must discover is whether the stored token is still valid. That check is asynchronous (read secure storage, maybe call the server). If you render before it finishes, a signed-in user sees the login screen flash for a moment. The fix is to keep the splash screen visible until the auth state is known:

JSX
import * as SplashScreen from 'expo-splash-screen';
import { useEffect } from 'react';

SplashScreen.preventAutoHideAsync();   // call once, at module level

export default function App() {
  const { status } = useAuth();

  useEffect(() => {
    if (status !== 'loading') {
      SplashScreen.hideAsync();
    }
  }, [status]);

  if (status === 'loading') return null;
  return <RootNavigator />;
}

Keep this loading phase short: restore the token, optionally load fonts, then hide. Do not wait for large network requests on the splash screen, or the app feels frozen.

Redirect after login

Suppose a signed-out user taps a link to myapp://orders/1042. After sign-in they should land on that order, not on Home. The pattern has three steps: remember the destination, sign in, then go there.

JSX
const pendingUrl = useRef(null);

// 1. When a protected link arrives while signed out
function onLink(url) {
  if (!isSignedIn) pendingUrl.current = url;
}

// 2. After a successful login
async function onSignedIn() {
  setUser(await login());
  // 3. Go to the saved destination (or Home)
  const target = pendingUrl.current ?? 'myapp://';
  pendingUrl.current = null;
  Linking.openURL(target);
}

With conditional screens, React Navigation can also handle step 3 for you in some setups, because the initial URL is matched against the screens that exist once the user is signed in. With Expo Router you can store the path in a param, for example /sign-in?next=%2Forders%2F1042, and call router.replace(next) after login. Validate next: accept only local paths that start with a single slash, never full URLs, or attackers can craft a link that sends users to another site after login (an open redirect).

The stand-in below puts the whole flow in one state machine.

Sign in, then continue to the link (stand-in)

Try this order: "Storage has no token", then "Open link /orders/1042", then "Sign in". The app shows the sign-in screen, remembers the order link, and lands on it after sign-in. The //evil.example link is rejected by safeNext and goes to /home instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of universal links over custom URL schemes?

    Universal and App Links prove domain ownership through files in /.well-known/, so other apps cannot hijack them, and a normal browser can still open the page.
  2. 2. In a linking config, what does the pattern 'orders/:id' do?

    A segment starting with a colon is a param. The value arrives as a string, and you can convert it with parse.
  3. 3. Why use conditional screens (or Stack.Protected) for login instead of navigate('Login')?

    Rendering only the screens valid for the current auth state removes the private ones from the tree, so Back and deep links cannot reach them while signed out.
  4. 4. Why validate a 'next' path before redirecting after login?

    Accepting only local paths that start with one slash prevents an open redirect to an external or look-alike URL.
  5. 5. What is the splash screen kept visible for during startup?

    preventAutoHideAsync holds the splash until you call hideAsync after the auth state is known.

Summary

  • A deep link opens a specific screen. Custom schemes (myapp://) are simple; universal links and App Links are verified https URLs that fall back to your website.
  • In React Navigation, linking with prefixes and config.screens maps URL patterns to screens; :id segments become string params. Expo Router derives URLs from file paths.
  • Show screens conditionally (or use Stack.Protected) so signed-out users cannot reach private screens by Back or by link, and never treat client-side hiding as real security.
  • Hold the splash screen until the stored session is checked, then hide it.
  • For redirect after login, save the destination, sign in, then go there, and accept only local paths.
  • On this site the real configuration is read-only and the TryIts are plain-JavaScript stand-ins.

Next, manage data that changes over time in State in React Native Apps.