> ## 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 Angular with Capacitor Application

> This guide demonstrates how to integrate Auth0 with an Ionic Angular & Capacitor application using the Auth0 Angular 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 Angular app
> ```
>
> Your AI assistant will automatically create your Auth0 application, fetch credentials, install the Auth0 Angular 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 Angular application with Capacitor. You'll build a mobile-ready app with login, logout, and user profile features using the Auth0 Angular SDK and Capacitor's native browser plugins.

**1. Create a new project**

Create a new Ionic Angular project with Capacitor

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

Open the project

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

> [!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
> ```

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

Install the Auth0 Angular SDK along with Capacitor's Browser and App plugins:

```shellscript theme={null}
npm install @auth0/auth0-angular @capacitor/browser @capacitor/app
```

* [`@capacitor/browser`](https://capacitorjs.com/docs/apis/browser) - opens the Auth0 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 from Auth0 after authentication

> [!NOTE]
>
> Capacitor's Browser plugin on iOS uses `SFSafariViewController`, which on iOS 11+ does not share cookies with Safari. 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:

> [tab] Quick Setup (recommended)
>
> Create a Native Auth0 App and copy the pre-filled environment file with the right configuration values.
>
> After creating your app, update the **Allowed Callback URLs** and **Allowed Logout URLs** in the [Auth0 Dashboard](https://manage.auth0.com/dashboard/) **Settings** tab. Replace `YOUR_PACKAGE_ID` with the `appId` from your `capacitor.config.ts` (default: `io.ionic.starter`):
>
> **Allowed Callback URLs** and **Allowed Logout URLs:**
>
> ```text theme={null}
> YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback
> ```

> [tab] CLI
>
> Run the following command in your project's root directory to create a Native Auth0 app and generate an environment file. Update `PACKAGE_ID` if your `capacitor.config.ts` uses a different `appId`:
>
> ```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 environment file
> auth0 qs setup --app --type native --framework ionic-angular --name "My Ionic Angular 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 environment file
> auth0 qs setup --app --type native --framework ionic-angular --name "My Ionic Angular 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 `src/environments/environment.ts` with your Auth0 domain and client ID

> [tab] Dashboard
>
> Before you start, create an environment file in your project
>
> ```typescript src/environments/environment.ts lines theme={null}
> export const environment = {
>   production: false,
>   auth0: {
>     domain: 'YOUR_AUTH0_APP_DOMAIN',
>     clientId: 'YOUR_AUTH0_APP_CLIENT_ID'
>   }
> };
> ```
>
> 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/)
>
> 2. Click on **Applications** > **Applications** > **Create Application**
>
> 3. Enter a name for your app (e.g., `Ionic Angular App`), select **Native** as the application type, and click **Create**
>
> 4. Switch to the **Settings** tab and note your **Domain** and **Client ID** values
>
> 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` in `src/environments/environment.ts` with your values
>
> > [!NOTE]
> >
> > Throughout this quickstart, `YOUR_PACKAGE_ID` refers to the `appId` field in your `capacitor.config.ts`. The default value is `io.ionic.starter`. See [Capacitor's Config schema](https://capacitorjs.com/docs/config#schema) for more info.
>
> Configure the following URLs on the **Settings** tab (replace `YOUR_PACKAGE_ID` with your actual package ID):
>
> **Allowed Callback URLs:**
>
> ```text theme={null}
> YOUR_PACKAGE_ID://{yourDomain}/capacitor/YOUR_PACKAGE_ID/callback
> ```
>
> **Allowed Logout URLs:**
>
> ```text theme={null}
> YOUR_PACKAGE_ID://{yourDomain}/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.
> >
> > **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will receive an error when logging out.
> >
> > **Allowed Origins** are required for silent authentication. The `capacitor://localhost` origin is for iOS and `http://localhost` is for Android.

**4. Configure the Auth0 module**

With your environment file in place from the previous step, configure the Auth0 module in your app:

```typescript src/main.ts {4-6,10,17-25} lines theme={null}
import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter } from '@angular/router';
import { IonicRouteStrategy, provideIonicAngular } from '@ionic/angular/standalone';
import { provideAuth0 } from '@auth0/auth0-angular';
import { environment } from './environments/environment';
import config from '../capacitor.config';
import { routes } from './app/app.routes';
import { AppComponent } from './app/app.component';

const redirect_uri = `${config.appId}://${environment.auth0.domain}/capacitor/${config.appId}/callback`;

bootstrapApplication(AppComponent, {
  providers: [
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
    provideIonicAngular(),
    provideRouter(routes),
    provideAuth0({
      domain: environment.auth0.domain,
      clientId: environment.auth0.clientId,
      useRefreshTokens: true,
      useRefreshTokensFallback: false,
      authorizationParams: {
        redirect_uri,
      },
    }),
  ],
});
```

The `provideAuth0` configuration includes:

* `useRefreshTokens: true` — **required** for mobile. Capacitor apps cannot use iframe-based silent authentication, so refresh tokens are used to renew sessions.
* `useRefreshTokensFallback: false` — **required** for mobile. Prevents the SDK from falling back to iframe-based silent auth, which is unavailable in native apps.
* `authorizationParams.redirect_uri` — uses your app's custom URL scheme to redirect back after authentication.

> [!WARNING]
>
> To persist authentication after closing and reopening the application, you may want to set `cacheLocation` to `localstorage`, but please be aware of [the risks of storing tokens in localstorage](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options). Also, localstorage should be treated as **transient** in Capacitor apps. Please read the [guidance on storage in the Capacitor docs](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb).

**5. Create Login, Logout and Profile components**

Create the component files

```shellscript Mac/Linux theme={null}
touch src/app/login-button.component.ts && touch src/app/logout-button.component.ts && touch src/app/profile.component.ts
```

```powershell Windows theme={null}
New-Item -ItemType File -Path src/app/login-button.component.ts
New-Item -ItemType File -Path src/app/logout-button.component.ts
New-Item -ItemType File -Path src/app/profile.component.ts
```

Add the following code to each component:

Now update the App Component to handle Auth0 callbacks, and the home page to use your components:

> [tab] App Component
>
> Replace the contents of `src/app/app.component.ts`:
>
> ```typescript src/app/app.component.ts expandable lines theme={null}
> import { Component, OnInit, NgZone, inject } from '@angular/core';
> import { AuthService } from '@auth0/auth0-angular';
> import { mergeMap } from 'rxjs/operators';
> import { Browser } from '@capacitor/browser';
> import { App } from '@capacitor/app';
> import { IonApp, IonRouterOutlet } from '@ionic/angular/standalone';
> import { environment } from '../environments/environment';
> import config from '../../capacitor.config';
>
> const callbackUri = `${config.appId}://${environment.auth0.domain}/capacitor/${config.appId}/callback`;
>
> @Component({
>   selector: 'app-root',
>   standalone: true,
>   imports: [IonApp, IonRouterOutlet],
>   template: '<ion-app><ion-router-outlet></ion-router-outlet></ion-app>',
> })
> export class AppComponent implements OnInit {
>   private auth = inject(AuthService);
>   private ngZone = inject(NgZone);
>
>   ngOnInit(): void {
>     App.addListener('appUrlOpen', ({ url }) => {
>       this.ngZone.run(() => {
>         if (url?.startsWith(callbackUri)) {
>           if (
>             url.includes('state=') &&
>             (url.includes('error=') || url.includes('code='))
>           ) {
>             this.auth
>               .handleRedirectCallback(url)
>               .pipe(mergeMap(() => Browser.close()))
>               .subscribe();
>           } else {
>             Browser.close();
>           }
>         }
>       });
>     });
>   }
> }
> ```

> [tab] Home Page
>
> Replace the contents of `src/app/tab1/tab1.page.ts`:
>
> ```typescript src/app/tab1/tab1.page.ts expandable lines theme={null}
> import { Component, inject } from '@angular/core';
> import { CommonModule } from '@angular/common';
> import { AuthService } from '@auth0/auth0-angular';
> import {
>   IonHeader, IonToolbar, IonTitle, IonContent,
>   IonCard, IonCardHeader, IonCardTitle, IonCardContent,
> } from '@ionic/angular/standalone';
> import { LoginButtonComponent } from '../login-button.component';
> import { LogoutButtonComponent } from '../logout-button.component';
> import { ProfileComponent } from '../profile.component';
>
> @Component({
>   selector: 'app-tab1',
>   standalone: true,
>   imports: [
>     CommonModule,
>     IonHeader, IonToolbar, IonTitle, IonContent,
>     IonCard, IonCardHeader, IonCardTitle, IonCardContent,
>     LoginButtonComponent, LogoutButtonComponent, ProfileComponent,
>   ],
>   template: `
>     <ion-header>
>       <ion-toolbar>
>         <ion-title>Home</ion-title>
>       </ion-toolbar>
>     </ion-header>
>
>     <ion-content class="ion-padding">
>       @if (auth.isAuthenticated$ | async) {
>         <ion-card>
>           <ion-card-header>
>             <ion-card-title>Welcome!</ion-card-title>
>           </ion-card-header>
>           <ion-card-content>
>             <app-profile />
>             <div class="ion-margin-top">
>               <app-logout-button />
>             </div>
>           </ion-card-content>
>         </ion-card>
>       } @else {
>         <ion-card>
>           <ion-card-header>
>             <ion-card-title>Get Started</ion-card-title>
>           </ion-card-header>
>           <ion-card-content>
>             <p>Sign in to your account to get started.</p>
>             <div class="ion-margin-top">
>               <app-login-button />
>             </div>
>           </ion-card-content>
>         </ion-card>
>       }
>     </ion-content>
>   `,
> })
> export class Tab1Page {
>   protected auth = inject(AuthService);
> }
> ```

> [!NOTE]
>
> The `appUrlOpen` event callback in the App Component is wrapped in `this.ngZone.run()`. This is **required** because Capacitor plugin callbacks execute outside Angular's zone, and without it Angular won't detect the auth state changes after login. See [Using Angular with Capacitor](https://capacitorjs.com/docs/guides/angular) for details.

**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 won't work because browsers cannot handle custom URL schemes. For browser testing, temporarily change `redirect_uri` to `http://localhost:8100` in `src/main.ts` 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. Make sure your custom URL scheme is registered (see Advanced Usage below).

> [!TIP]
>
> **Checkpoint**
>
> You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:8100/)

***

## Advanced Usage

> [accordion] Using Traditional NgModule Approach
>
> If you created your project with `--type=angular` (instead of `--type=angular-standalone`) or prefer using NgModules, configure the SDK with `AuthModule.forRoot`:
>
> ```typescript src/app/app.module.ts expandable lines theme={null}
> import { NgModule } from '@angular/core';
> import { BrowserModule } from '@angular/platform-browser';
> import { RouteReuseStrategy } from '@angular/router';
> import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
> import { AuthModule } from '@auth0/auth0-angular';
> import { environment } from '../environments/environment';
> import config from '../../capacitor.config';
>
> import { AppRoutingModule } from './app-routing.module';
> import { AppComponent } from './app.component';
>
> const redirect_uri = `${config.appId}://${environment.auth0.domain}/capacitor/${config.appId}/callback`;
>
> @NgModule({
>   declarations: [AppComponent],
>   imports: [
>     BrowserModule,
>     IonicModule.forRoot(),
>     AppRoutingModule,
>     AuthModule.forRoot({
>       domain: environment.auth0.domain,
>       clientId: environment.auth0.clientId,
>       useRefreshTokens: true,
>       useRefreshTokensFallback: false,
>       authorizationParams: {
>         redirect_uri,
>       },
>     }),
>   ],
>   providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
>   bootstrap: [AppComponent],
> })
> export class AppModule {}
> ```
>
> > [!NOTE]
> >
> > When using NgModules, inject `AuthService` via the constructor (`constructor(public auth: AuthService)`) instead of `inject()`. Use `*ngIf="auth.user$ | async as user"` in templates instead of `@if` control flow syntax. Components should be declared in the module rather than marked as `standalone: true`.

> [accordion] Custom URL Scheme Setup
>
> To test authentication on a real device, register your custom URL scheme for each platform.
>
> ### iOS
>
> Register your custom URL scheme in `ios/App/App/Info.plist`:
>
> ```xml lines theme={null}
> <key>CFBundleURLTypes</key>
> <array>
>   <dict>
>     <key>CFBundleURLSchemes</key>
>     <array>
>       <string>YOUR_PACKAGE_ID</string>
>     </array>
>   </dict>
> </array>
> ```
>
> Replace `YOUR_PACKAGE_ID` with your `appId` from `capacitor.config.ts`. To learn more, read [Defining a Custom URL Scheme](https://developer.apple.com/documentation/xcode/defining-a-custom-url-scheme-for-your-app).
>
> ### Android
>
> Add an intent filter to `android/app/src/main/AndroidManifest.xml` inside the `<activity>` tag:
>
> ```xml lines 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="YOUR_PACKAGE_ID" />
> </intent-filter>
> ```
>
> Replace `YOUR_PACKAGE_ID` with your `appId` from `capacitor.config.ts`. To learn more, read [Create Deep Links to App Content](https://developer.android.com/training/app-links/deep-linking).
>
> ### Build and run on device
>
> ```shellscript theme={null}
> ionic build && npx cap sync && npx cap open ios
> ```
>
> Or for Android:
>
> ```shellscript theme={null}
> ionic build && npx cap sync && npx cap open android
> ```

> [accordion] Protecting Routes with AuthGuard
>
> Use the functional guard to protect routes that require authentication:
>
> ```typescript src/app/app.routes.ts lines theme={null}
> import { Routes } from '@angular/router';
> import { authGuardFn } from '@auth0/auth0-angular';
>
> export const routes: Routes = [
>   {
>     path: 'tabs',
>     loadComponent: () => import('./tabs/tabs.page').then((m) => m.TabsPage),
>     children: [
>       {
>         path: 'tab1',
>         loadComponent: () => import('./tab1/tab1.page').then((m) => m.Tab1Page),
>       },
>       {
>         path: 'tab2',
>         loadComponent: () => import('./tab2/tab2.page').then((m) => m.Tab2Page),
>         canActivate: [authGuardFn],
>       },
>       {
>         path: 'tab3',
>         loadComponent: () => import('./tab3/tab3.page').then((m) => m.Tab3Page),
>         canActivate: [authGuardFn],
>       },
>       {
>         path: '',
>         redirectTo: '/tabs/tab1',
>         pathMatch: 'full',
>       },
>     ],
>   },
>   {
>     path: '',
>     redirectTo: '/tabs/tab1',
>     pathMatch: 'full',
>   },
> ];
> ```
>
> When unauthenticated users navigate to a protected route, `authGuardFn` automatically redirects them to the Auth0 login page.

> [accordion] Calling Protected APIs
>
> Configure the HTTP interceptor to automatically attach access tokens to API calls:
>
> ```typescript src/main.ts expandable lines theme={null}
> import { bootstrapApplication } from '@angular/platform-browser';
> import { RouteReuseStrategy, provideRouter } from '@angular/router';
> import { IonicRouteStrategy, provideIonicAngular } from '@ionic/angular/standalone';
> import { provideHttpClient, withInterceptors } from '@angular/common/http';
> import { provideAuth0, authHttpInterceptorFn } from '@auth0/auth0-angular';
> import { environment } from './environments/environment';
> import config from '../capacitor.config';
> import { routes } from './app/app.routes';
> import { AppComponent } from './app/app.component';
>
> const redirect_uri = `${config.appId}://${environment.auth0.domain}/capacitor/${config.appId}/callback`;
>
> bootstrapApplication(AppComponent, {
>   providers: [
>     { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
>     provideIonicAngular(),
>     provideRouter(routes),
>     provideAuth0({
>       domain: environment.auth0.domain,
>       clientId: environment.auth0.clientId,
>       useRefreshTokens: true,
>       useRefreshTokensFallback: false,
>       authorizationParams: {
>         redirect_uri,
>         audience: 'YOUR_API_IDENTIFIER',
>       },
>       httpInterceptor: {
>         allowedList: [
>           'http://localhost:3001/api/*',
>         ],
>       },
>     }),
>     provideHttpClient(
>       withInterceptors([authHttpInterceptorFn])
>     ),
>   ],
> });
> ```
>
> Then make API calls using Angular's `HttpClient` — the interceptor automatically attaches the Bearer token:
>
> ```typescript src/app/api.service.ts lines theme={null}
> import { Injectable, inject } from '@angular/core';
> import { HttpClient } from '@angular/common/http';
>
> @Injectable({ providedIn: 'root' })
> export class ApiService {
>   private http = inject(HttpClient);
>
>   getData() {
>     return this.http.get('http://localhost:3001/api/data');
>   }
> }
> ```
>
> > [!TIP]
> >
> > The `httpInterceptor.allowedList` determines which API endpoints receive access tokens. Include the `audience` parameter to request an access token for your API. Replace `YOUR_API_IDENTIFIER` with the identifier from [Auth0 Dashboard > APIs](https://manage.auth0.com/dashboard/).

> [accordion] Common Issues & Solutions
>
> ### Callback URL mismatch error
>
> **Solution:** Verify the callback URL in your Auth0 Dashboard matches exactly with the URL constructed in your app. Ensure `YOUR_PACKAGE_ID` matches the `appId` field in your `capacitor.config.ts`.
>
> ### Screen does not update after login
>
> **Solution:** Ensure the `appUrlOpen` event callback is wrapped in `this.ngZone.run()`. Without this, Angular won't detect the state changes from `handleRedirectCallback`. See [Using Angular with Capacitor](https://capacitorjs.com/docs/guides/angular).
>
> ### "PKCE not allowed" error
>
> **Fix:**
>
> 1. Go to Auth0 Dashboard > Applications > Your Application
> 2. Change the **Application Type** to **Native**
> 3. Set **Token Endpoint Authentication Method** to `None`
> 4. Save changes and try again
>
> ### SSO not working on iOS
>
> Capacitor's Browser plugin uses `SFSafariViewController`, which does not share cookies with Safari on iOS 11+. If you need SSO, use a compatible plugin that uses [ASWebAuthenticationSession](https://developer.apple.com/documentation/authenticationservices/aswebauthenticationsession).
>
> ### Login works but user stays unauthenticated after app restart
>
> Enable `cacheLocation: 'localstorage'` in the `provideAuth0` configuration to persist tokens across app restarts. Be aware of the [security implications](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options) and [Capacitor storage limitations](https://capacitorjs.com/docs/guides/storage#why-cant-i-just-use-localstorage-or-indexeddb).
>
> ### Observable never executes
>
> All `AuthService` methods return cold Observables. You must call `.subscribe()` for them to execute. If `loginWithRedirect()` or `logout()` appears to do nothing, check that `.subscribe()` is chained at the end.

## Next Steps

Check out the following resources to learn more:

* [Sample Application](https://github.com/auth0-samples/auth0-ionic-samples/tree/main/angular) — A complete Ionic Angular sample app with Auth0 integration
* [Auth0 Angular SDK Documentation](https://github.com/auth0/auth0-angular) — Full SDK reference and examples
* [Auth0 Dashboard](https://manage.auth0.com/dashboard/) — Configure and manage your Auth0 tenant and applications
* [Auth0 Marketplace](https://marketplace.auth0.com/) — Discover integrations you can enable to extend Auth0's functionality
