> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Add Login to Your Ionic React with Capacitor Application

> This guide demonstrates how to integrate Auth0 with an Ionic React & Capacitor application using the Auth0 React SDK.

> [accordion] Use AI to integrate Auth0
>
> If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 authentication automatically in minutes using [agent skills](https://agentskills.io/home).
>
> First, install the Auth0 agent skills:
>
> ```bash theme={null}
> npx skills add auth0/agent-skills --skill auth0
> ```
>
> Then, ask your AI assistant:
>
> ```text theme={null}
> Add Auth0 authentication to my Ionic React app
> ```
>
> Your AI assistant will automatically create your Auth0 application, fetch credentials, install the Auth0 React SDK and Capacitor plugins, configure deep linking, and implement login/logout flows with native browser integration. Learn more about [Auth0 agent skills](https://auth0.com/docs/quickstart/agent-skills.md).

## Get Started

This quickstart demonstrates how to add Auth0 authentication to an Ionic React application with Capacitor. You'll build a mobile-ready app with login, logout, and user profile features using the Auth0 React SDK and Capacitor's native browser integration.

**1. Create a new project**

Create a new Ionic React app with Capacitor

```shellscript theme={null}
npx ionic start auth0-ionic-react tabs --type=react --capacitor
```

Open the project

```shellscript theme={null}
cd auth0-ionic-react
```

> [!WARNING]
>
> Make sure you're using the `@ionic/cli` package (not the deprecated `ionic` package). If you see errors about `--npm-client` during project creation, update your CLI:
>
> ```shellscript theme={null}
> npm uninstall -g ionic
> npm i -g @ionic/cli
> ```

> [!NOTE]
>
> If you already have an Ionic React app, make sure Capacitor is enabled. You can add it with `ionic integrations enable capacitor` and then `npx cap init`.

**2. Install the Auth0 React SDK and Capacitor plugins**

The Ionic starter template may scaffold `react@19.0.0`, which is not compatible with the Auth0 React SDK. First, ensure you have a supported React version:

```shellscript theme={null}
npm install react@^19.0.1 react-dom@^19.0.1
```

Then install the Auth0 SDK and Capacitor plugins:

```shellscript theme={null}
npm install @auth0/auth0-react @capacitor/browser @capacitor/app && npx cap sync
```

* [`@auth0/auth0-react`](https://github.com/auth0/auth0-react): Provides React hooks and components for Auth0 authentication
* [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser): Opens the login page in the device's system browser ([SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) on iOS, [Chrome Custom Tabs](https://developer.chrome.com/docs/android/custom-tabs) on Android)
* [`@capacitor/app`](https://capacitorjs.com/docs/apis/app): Handles deep link callbacks when Auth0 redirects back to your app

> [!NOTE]
>
> Capacitor's Browser plugin on iOS uses `SFSafariViewController`, which on iOS 11+ does not share cookies with Safari on the device. This means [SSO](https://auth0.com/docs/sso) will not work on those devices. If you need SSO, use a compatible plugin that uses [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession).

**3. Setup your Auth0 App**

Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project.

You have three options to set up your Auth0 app: use the Quick Setup tool (recommended), run a CLI command, or configure manually via the Dashboard.

> [!NOTE]
>
> Throughout this quickstart, `YOUR_PACKAGE_ID` is your application's package ID. This is the `appId` field in your `capacitor.config.ts` file (e.g. `io.ionic.starter`). See [Capacitor's Config schema](https://capacitorjs.com/docs/config#schema) for more info.

> [tab] Quick Setup (recommended)
>
> Create an Auth0 App and copy the pre-filled `.env` file with the right configuration values.
>
> After creating the app, go to its **Settings** in the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) and update the **Allowed Callback URLs** and **Allowed Logout URLs** to replace `YOUR_PACKAGE_ID` with your actual package ID and `YOUR_AUTH0_DOMAIN` with your Auth0 domain:
>
> ```text theme={null}
> YOUR_PACKAGE_ID://YOUR_AUTH0_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
> ```
>
> Also ensure the **Application Type** is set to **Native** and the **Token Endpoint Authentication Method** is set to **None**.

> [tab] CLI
>
> Run the following command in your project's root directory to create an Auth0 app and generate a `.env` file:
>
> ```shellscript Mac theme={null}
> # Install Auth0 CLI (if not already installed)
> brew tap auth0/auth0-cli && brew install auth0
>
> # Set up Auth0 app and generate .env file
> auth0 qs setup --app --type native --framework ionic-react --build-tool vite --name "My Ionic React App"
> ```
>
> ```powershell Windows theme={null}
> # Install Auth0 CLI (if not already installed)
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Set up Auth0 app and generate .env file
> auth0 qs setup --app --type native --framework ionic-react --build-tool vite --name "My Ionic React App"
> ```
>
> > [!NOTE]
> >
> > This command will:
> >
> > 1. Check if you're authenticated (and prompt for login if needed)
> > 2. Create an Auth0 Native application
> > 3. Generate a `.env` file with `VITE_AUTH0_DOMAIN` and `VITE_AUTH0_CLIENT_ID`
>
> Create a `.env` file with the values from the CLI output:

> [tab] Dashboard
>
> Before you start, create a `.env` file in your project's root directory
>
> ```shellscript .env theme={null}
> VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN
> VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID
> ```
>
> 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/)
> 2. Click on **Applications** > **Applications** > **Create Application**
> 3. In the popup, enter a name for your app, select `Native` as the app type and click **Create**
> 4. Switch to the **Settings** tab on the Application Details page
> 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` in the `.env` file with the **Domain** and **Client ID** values from the dashboard
> 6. Set the **Token Endpoint Authentication Method** to `None`
>
> Finally, on the **Settings** tab of your Application Details page, configure the following URLs (replace `YOUR_PACKAGE_ID` with your `appId` from `capacitor.config.ts`):
>
> **Allowed Callback URLs:**
>
> ```text theme={null}
> YOUR_PACKAGE_ID://YOUR_AUTH0_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
> ```
>
> **Allowed Logout URLs:**
>
> ```text theme={null}
> YOUR_PACKAGE_ID://YOUR_AUTH0_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
> ```
>
> **Allowed Origins:**
>
> ```text theme={null}
> capacitor://localhost, http://localhost
> ```
>
> > [!NOTE]
> >
> > **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app.
> >
> > **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page.
> >
> > **Allowed Origins** (`capacitor://localhost` for iOS and `http://localhost` for Android) are required so your native app can communicate with the Auth0 API.

> [!TIP]
>
> Verify your `.env` file exists: `cat .env` (Mac/Linux) or `type .env` (Windows)

**4. Configure the Auth0Provider**

Open `src/main.tsx` and wrap the `App` component with the `Auth0Provider`. The mobile-specific settings `useRefreshTokens` and `useRefreshTokensFallback` are required for Ionic apps on iOS and Android.

```javascript src/main.tsx {5,6,12,13,14,15,16,17,18,19} lines theme={null}
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';

// Must match the appId in your capacitor.config.ts
const appId = 'io.ionic.starter';

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={import.meta.env.VITE_AUTH0_DOMAIN}
      clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
      useRefreshTokens={true}
      useRefreshTokensFallback={false}
      authorizationParams={{
        redirect_uri: `${appId}://${import.meta.env.VITE_AUTH0_DOMAIN}/capacitor/${appId}/callback`
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);
```

* `useRefreshTokens`: Required for Ionic on Android and iOS. Mobile browsers block third-party cookies, so the SDK uses refresh tokens instead of iframe-based silent authentication.
* `useRefreshTokensFallback`: Must be `false` to prevent the SDK from attempting iframe-based silent auth, which is not available on mobile.
* `authorizationParams.redirect_uri`: Uses your package ID as a custom URL scheme so the OS can route the Auth0 callback back to your app.

> [!WARNING]
>
> To persist authentication after closing and reopening the application, you may want to set `cacheLocation` to `localstorage`, but be aware of [the risks of storing tokens in localstorage](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options). On Capacitor, localstorage should be treated as **transient** — the OS may clear it unexpectedly. See [Capacitor's guidance on storage](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb).
>
> We recommend **against** using [Capacitor's Preferences plugin](https://capacitorjs.com/docs/apis/preferences) to store tokens, as it is backed by `UserDefaults` (iOS) and `SharedPreferences` (Android), which are not encrypted and could be synced to the cloud. The SDK supports [custom cache implementations](https://github.com/auth0/auth0-spa-js/blob/master/EXAMPLES.md#creating-a-custom-cache) if you need a more secure and persistent storage mechanism.

**5. Create Login, Logout, Profile, and Callback Handler**

Create files

```shellscript Mac/Linux theme={null}
touch src/LoginButton.tsx && touch src/LogoutButton.tsx && touch src/Profile.tsx
```

```powershell Windows theme={null}
New-Item -ItemType File -Path src/LoginButton.tsx
New-Item -ItemType File -Path src/LogoutButton.tsx
New-Item -ItemType File -Path src/Profile.tsx
```

And add the following code snippets

The `openUrl` callback in `LoginButton` and `LogoutButton` uses Capacitor's Browser plugin to open the Auth0 login and logout pages in the device's system browser component, rather than navigating away from the app entirely.

The `App` component listens for the `appUrlOpen` event, which fires when Auth0 redirects back to your app using the custom URL scheme. It calls `handleRedirectCallback` to exchange the authorization code for tokens, then closes the browser.

> [!NOTE]
>
> By default, the SDK's `loginWithRedirect` method uses `window.location.href` to navigate to the login page, which opens the device's default browser application. Setting `openUrl` to use `Browser.open` keeps the authentication flow within your app's context for a better user experience.

**6. Run your app**

Test in the browser first

```shellscript theme={null}
ionic serve
```

> [!WARNING]
>
> When running in the browser with `ionic serve`, the custom URL scheme redirect (`io.ionic.starter://...`) won't work because browsers cannot handle custom URL schemes. For browser testing, temporarily change `redirect_uri` to `http://localhost:8100` in `src/main.tsx` and add `http://localhost:8100` to your Auth0 app's **Allowed Callback URLs** and **Allowed Logout URLs** in the Dashboard. Remember to revert this change before building for native.

To run on a device or simulator, first add the native platforms:

```shellscript theme={null}
npx cap add ios
npx cap add android
```

Then build, sync, and run:

```shellscript iOS theme={null}
ionic build && npx cap sync && npx cap run ios
```

```shellscript Android theme={null}
ionic build && npx cap sync && npx cap run android
```

> [!NOTE]
>
> You must add native platforms with `npx cap add` before you can run on them. This only needs to be done once per platform. After that, `npx cap sync` copies your built web assets and updates native plugins.

> [!TIP]
>
> **Checkpoint**
>
> You should now have a fully functional Auth0 login running in your Ionic app. When running on a device, tapping "Log in" opens the Auth0 Universal Login Page in the system browser, and after authenticating, you're redirected back to your app with the user's profile displayed.

***

## Advanced Usage

> [accordion] Custom URL Scheme Configuration (iOS & Android)
>
> For Auth0 callbacks to work on devices, register your package ID as a custom URL scheme on each platform.
>
> **iOS** — add to `ios/App/App/Info.plist`:
>
> ```xml ios/App/App/Info.plist theme={null}
> <key>CFBundleURLTypes</key>
> <array>
>   <dict>
>     <key>CFBundleURLSchemes</key>
>     <array>
>       <string>io.ionic.starter</string>
>     </array>
>   </dict>
> </array>
> ```
>
> **Android** — add an intent filter inside the main `<activity>` in `android/app/src/main/AndroidManifest.xml`:
>
> ```xml android/app/src/main/AndroidManifest.xml theme={null}
> <intent-filter>
>   <action android:name="android.intent.action.VIEW" />
>   <category android:name="android.intent.category.DEFAULT" />
>   <category android:name="android.intent.category.BROWSABLE" />
>   <data android:scheme="io.ionic.starter" />
> </intent-filter>
> ```
>
> Replace `io.ionic.starter` with your actual `appId` from `capacitor.config.ts`.
>
> > [!NOTE]
> >
> > To learn more, read [Defining a Custom URL Scheme](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app) for iOS, or [Create Deep Links to App Content](https://developer.android.com/training/app-links/deep-linking) for Android.

> [accordion] Protecting Routes with Ionic Router
>
> Use Auth0's authentication state to protect specific routes in your Ionic application:
>
> ```jsx src/App.tsx theme={null}
> import { useAuth0, withAuthenticationRequired } from '@auth0/auth0-react';
> import { IonReactRouter } from '@ionic/react-router';
> import { IonRouterOutlet } from '@ionic/react';
> import { Route, Redirect } from 'react-router-dom';
> import HomePage from './pages/Home';
> import DashboardPage from './pages/Dashboard';
>
> const ProtectedRoute = ({ component, ...args }: any) => {
>   const Component = withAuthenticationRequired(component, {
>     onRedirecting: () => <div className="ion-padding">Loading...</div>,
>   });
>   return <Route {...args} render={() => <Component />} />;
> };
>
> const App: React.FC = () => {
>   // ... callback handler from previous step
>
>   return (
>     <IonApp>
>       <IonReactRouter>
>         <IonRouterOutlet>
>           <Route exact path="/home" component={HomePage} />
>           <ProtectedRoute exact path="/dashboard" component={DashboardPage} />
>           <Route exact path="/">
>             <Redirect to="/home" />
>           </Route>
>         </IonRouterOutlet>
>       </IonReactRouter>
>     </IonApp>
>   );
> };
> ```
>
> The `withAuthenticationRequired` HOC automatically redirects unauthenticated users to the Auth0 login page when they try to access a protected route.

> [accordion] Calling Protected APIs
>
> Configure your Auth0Provider to include an API audience and use the `getAccessTokenSilently` method to get access tokens for your backend:
>
> ```jsx src/main.tsx theme={null}
> <Auth0Provider
>   domain={import.meta.env.VITE_AUTH0_DOMAIN}
>   clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
>   useRefreshTokens={true}
>   useRefreshTokensFallback={false}
>   authorizationParams={{
>     redirect_uri: `${appId}://${import.meta.env.VITE_AUTH0_DOMAIN}/capacitor/${appId}/callback`,
>     audience: "YOUR_API_IDENTIFIER"
>   }}
> >
>   <App />
> </Auth0Provider>
> ```
>
> Then make authenticated API calls from your components:
>
> ```jsx src/ApiCall.tsx theme={null}
> import { useState } from 'react';
> import { useAuth0 } from '@auth0/auth0-react';
> import { IonButton, IonText } from '@ionic/react';
>
> const ApiCall: React.FC = () => {
>   const { getAccessTokenSilently } = useAuth0();
>   const [result, setResult] = useState<string | null>(null);
>
>   const callApi = async () => {
>     try {
>       const token = await getAccessTokenSilently();
>
>       const response = await fetch('https://your-api.example.com/protected', {
>         headers: {
>           Authorization: `Bearer ${token}`
>         }
>       });
>
>       const data = await response.json();
>       setResult(JSON.stringify(data, null, 2));
>     } catch (error) {
>       console.error('API call failed:', error);
>     }
>   };
>
>   return (
>     <div className="ion-padding">
>       <IonButton onClick={callApi}>Call Protected API</IonButton>
>       {result && (
>         <IonText>
>           <pre>{result}</pre>
>         </IonText>
>       )}
>     </div>
>   );
> };
>
> export default ApiCall;
> ```
