capacitor-deep-linking ยท diff
git:20260501.ed3e92e to git:20261011.86834d4
105 added, 380 removed. Audit A to A.
---
name: capacitor-deep-linking
- description: Complete guide to implementing deep links and universal links in Capacitor apps. Covers iOS Universal Links, Android App Links, custom URL schemes, and navigation handling. Use this skill when users need to open their app from links.
+ description: Implements and debugs deep links in Capacitor apps - custom URL schemes, iOS Universal Links (apple-app-site-association, Associated Domains entitlement), Android App Links (assetlinks.json, autoVerify), and routing via @capacitor/app `appUrlOpen` + `App.getLaunchUrl()`. Covers the Capacitor 8.5+ UIScene change where AppDelegate `application(_:open:options:)` and `continue userActivity` stop being called and custom handling must move to SceneDelegate, plus cold vs warm launch testing. Use when links open Safari/Chrome instead of the app, `appUrlOpen` never fires, the launch URL is lost on cold start, or OAuth redirects do not return to the app. Do not use for the full UIScene migration (capacitor-uiscene-migration), push notification taps (capacitor-push-notifications), or social login plugin setup (capacitor-plugins).
---
# Deep Linking in Capacitor
- Implement deep links, universal links, and app links in Capacitor apps.
-
- ## When to Use This Skill
+ Route custom-scheme links, iOS Universal Links, and Android App Links into the web app.
- - User wants deep links
- - User needs universal links
- - User asks about URL schemes
- - User wants to open app from links
- - User needs share links
+ ## When to Use
- ## Types of Deep Links
+ TRIGGER when:
+ - Adding `myapp://` schemes, Universal Links, or App Links to a Capacitor app
+ - Links open the browser instead of the app, or open the app but land on the home page
+ - `appUrlOpen` fires on warm open but the URL is missing on cold launch (or the reverse)
+ - Deep links broke after updating to Capacitor 8.5+ / adopting `SceneDelegate.swift`
+ - OAuth / magic-link / payment redirects must come back into the app
+ - `adb shell pm get-app-links` shows `none` or `1024` instead of `verified`
- | Type | Platform | Format | Requires Server |
- |------|----------|--------|-----------------|
- | Custom URL Scheme | Both | `myapp://path` | No |
- | Universal Links | iOS | `https://myapp.com/path` | Yes |
- | App Links | Android | `https://myapp.com/path` | Yes |
+ Do not use:
+ - Full AppDelegate -> SceneDelegate migration of an app: `capacitor-uiscene-migration`
+ - Notification tap routing: `capacitor-push-notifications`
+ - Native log capture while debugging: `ios-android-logs`
+ - Sign in with Apple / Google plugin config: `capacitor-plugins`
- ## Quick Start
+ ## Link Types
- ### Install Plugin
+ | Type | Platform | Format | Needs hosted file | Verified ownership |
+ |------|----------|--------|-------------------|--------------------|
+ | Custom scheme | both | `myapp://product/123` | no | no (any app can claim it) |
+ | Universal Links | iOS | `https://example.com/product/123` | `/.well-known/apple-app-site-association` | yes |
+ | App Links | Android 6+ | `https://example.com/product/123` | `/.well-known/assetlinks.json` | yes |
- ```bash
- npm install @capacitor/app
- npx cap sync
- ```
+ Prefer verified https links for anything security-sensitive (OAuth, magic links). Custom schemes can be hijacked by another app.
- ### Handle Deep Links
+ ## Workflow
- ```typescript
- import { App } from '@capacitor/app';
+ 1. **Inspect first.** Read `capacitor.config.*`, `ios/App/App/Info.plist`, `ios/App/App/*.entitlements`, `ios/App/App/AppDelegate.swift`, `ios/App/App/SceneDelegate.swift` (if present), `android/app/src/main/AndroidManifest.xml`, and the `@capacitor/app` version in `package.json`.
+ 2. **Decide the iOS lifecycle path.**
+ - `UIApplicationSceneManifest` present in Info.plist (Capacitor 8.5+ template or migrated app) -> URL events arrive in `SceneDelegate`. Any custom code in AppDelegate `application(_:open:options:)` or `application(_:continue:restorationHandler:)` is dead code. See [references/ios-scene-delegate.md](references/ios-scene-delegate.md).
+ - No scene manifest -> AppDelegate path still works on 8.5 core, but Xcode 27 / Capacitor 9 require the scene lifecycle. Hand the migration to `capacitor-uiscene-migration`.
+ 3. **Install** `@capacitor/app` (`npm install @capacitor/app && npx cap sync`).
+ 4. **Register the JS handler once, at app bootstrap** (before the router renders), using both `appUrlOpen` and `getLaunchUrl()`. See below.
+ 5. **Configure platforms**: custom scheme (Info.plist `CFBundleURLTypes`, Android `<intent-filter>`), then verified links per platform:
+ - iOS Universal Links: [references/ios-universal-links.md](references/ios-universal-links.md)
+ - Android App Links: [references/android-app-links.md](references/android-app-links.md)
+ 6. **Route** in the framework router: [references/routing-patterns.md](references/routing-patterns.md) (React, Vue, Angular, OAuth callbacks, deferred links).
+ 7. **Verify** with the cold/warm matrix below on a real device.
- // Listen for deep link opens
- App.addListener('appUrlOpen', (event) => {
- console.log('App opened with URL:', event.url);
+ Only load a reference when its topic is in play.
- // Parse and navigate
- const url = new URL(event.url);
- handleDeepLink(url);
- });
+ ## JS Handler (the part every app needs)
- function handleDeepLink(url: URL) {
- // Custom scheme: myapp://product/123
- // Universal link: https://myapp.com/product/123
+ ```typescript
+ import { App, type URLOpenListenerEvent } from '@capacitor/app';
- const path = url.pathname || url.host + url.pathname;
+ let lastHandled: string | undefined;
- // Route based on path
- if (path.startsWith('/product/')) {
- const productId = path.split('/')[2];
- navigateTo(`/product/${productId}`);
- } else if (path.startsWith('/user/')) {
- const userId = path.split('/')[2];
- navigateTo(`/profile/${userId}`);
- } else if (path === '/login') {
- navigateTo('/login');
- } else {
- navigateTo('/');
- }
+ function route(rawUrl: string) {
+ if (rawUrl === lastHandled) return; // cold start can deliver the same URL to both paths
+ lastHandled = rawUrl;
+ const url = new URL(rawUrl);
+ // myapp://product/123 -> host "product", pathname "/123"
+ // https://example.com/product/123 -> pathname "/product/123"
+ const path = url.protocol.startsWith('http')
+ ? url.pathname
+ : `/${url.host}${url.pathname}`;
+ router.navigate(path + url.search); // your router
}
- ```
- ## Custom URL Scheme
-
- ### iOS Configuration
-
- ```xml
- <!-- ios/App/App/Info.plist -->
- <key>CFBundleURLTypes</key>
- <array>
- <dict>
- <key>CFBundleURLName</key>
- <string>com.yourcompany.yourapp</string>
- <key>CFBundleURLSchemes</key>
- <array>
- <string>myapp</string>
- <string>myapp-dev</string>
- </array>
- </dict>
- </array>
- ```
-
- ### Android Configuration
-
- ```xml
- <!-- android/app/src/main/AndroidManifest.xml -->
- <activity android:name=".MainActivity">
- <!-- Deep link intent filter -->
- <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="myapp" />
- </intent-filter>
- </activity>
- ```
-
- ### Test Custom Scheme
-
- ```bash
- # iOS Simulator
- xcrun simctl openurl booted "myapp://product/123"
-
- # Android
- adb shell am start -a android.intent.action.VIEW -d "myapp://product/123"
- ```
-
- ## Universal Links (iOS)
-
- ### 1. Enable Associated Domains
-
- In Xcode:
- 1. Select App target
- 2. Signing & Capabilities
- 3. + Capability > Associated Domains
- 4. Add: `applinks:myapp.com`
-
- ### 2. Create apple-app-site-association
-
- Host at `https://myapp.com/.well-known/apple-app-site-association`:
-
- ```json
- {
- "applinks": {
- "apps": [],
- "details": [
- {
- "appID": "TEAMID.com.yourcompany.yourapp",
- "paths": [
- "/product/*",
- "/user/*",
- "/invite/*",
- "NOT /api/*"
- ]
- }
- ]
- }
+ export async function initDeepLinks() {
+ await App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => route(event.url));
+ const launch = await App.getLaunchUrl(); // resolves undefined or { url }
+ if (launch?.url) route(launch.url);
}
```
- **Requirements**:
- - Served over HTTPS
- - Content-Type: `application/json`
- - No redirects
- - File at root domain
+ Traps:
+ - Custom scheme URLs parse with the first segment as `host`, not `pathname`. Normalize both forms as above.
+ - Register the listener at bootstrap, not inside a lazily loaded page. A listener added after the event fired never sees it; `getLaunchUrl()` is the fallback for cold start.
+ - Wrap state updates from the listener in your framework's zone/run loop (Angular `NgZone.run`) or navigation silently does nothing.
+ - Dedupe: on cold start the URL can be reachable via both `getLaunchUrl()` and `appUrlOpen`.
+ - Validate and allow-list paths before navigating; a deep link is untrusted input.
- ### 3. Info.plist
+ ## Custom Scheme Config
+ iOS `ios/App/App/Info.plist`:
+
```xml
- <!-- ios/App/App/Info.plist -->
- <key>com.apple.developer.associated-domains</key>
+ <key>CFBundleURLTypes</key>
<array>
- <string>applinks:myapp.com</string>
- <string>applinks:www.myapp.com</string>
+ <dict>
+ <key>CFBundleURLName</key>
+ <string>com.example.app</string>
+ <key>CFBundleURLSchemes</key>
+ <array><string>myapp</string></array>
+ </dict>
</array>
```
- ### Verify Universal Links
-
- ```bash
- # Validate AASA file
- curl -I https://myapp.com/.well-known/apple-app-site-association
-
- # Check Apple CDN cache
- curl "https://app-site-association.cdn-apple.com/a/v1/myapp.com"
- ```
-
- ## App Links (Android)
-
- ### 1. Create assetlinks.json
-
- Host at `https://myapp.com/.well-known/assetlinks.json`:
-
- ```json
- [
- {
- "relation": ["delegate_permission/common.handle_all_urls"],
- "target": {
- "namespace": "android_app",
- "package_name": "com.yourcompany.yourapp",
- "sha256_cert_fingerprints": [
- "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99"
- ]
- }
- }
- ]
- ```
-
- ### Get SHA256 Fingerprint
-
- ```bash
- # Debug keystore
- keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
-
- # Release keystore
- keytool -list -v -keystore release.keystore -alias your-alias
-
- # From APK
- keytool -printcert -jarfile app-release.apk
- ```
-
- ### 2. AndroidManifest.xml
+ Android `AndroidManifest.xml`, inside the existing `MainActivity` (keep the template's `android:launchMode="singleTask"` so warm opens reuse the activity):
```xml
- <!-- android/app/src/main/AndroidManifest.xml -->
- <activity android:name=".MainActivity">
- <!-- App Links intent filter -->
- <intent-filter android:autoVerify="true">
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
-
- <data android:scheme="https" />
- <data android:host="myapp.com" />
- <data android:pathPrefix="/product" />
- <data android:pathPrefix="/user" />
- <data android:pathPrefix="/invite" />
- </intent-filter>
- </activity>
- ```
-
- ### Verify App Links
-
- ```bash
- # Validate assetlinks.json
- curl https://myapp.com/.well-known/assetlinks.json
-
- # Use Google's validator
- https://developers.google.com/digital-asset-links/tools/generator
-
- # Check link handling on device
- adb shell pm get-app-links com.yourcompany.yourapp
- ```
-
- ## Advanced Routing
-
- ### React Router Integration
-
- ```typescript
- import { App } from '@capacitor/app';
- import { useHistory } from 'react-router-dom';
- import { useEffect } from 'react';
-
- function DeepLinkHandler() {
- const history = useHistory();
-
- useEffect(() => {
- App.addListener('appUrlOpen', (event) => {
- const url = new URL(event.url);
- const path = getPathFromUrl(url);
-
- // Navigate using React Router
- history.push(path);
- });
-
- // Check if app was opened with URL
- App.getLaunchUrl().then((result) => {
- if (result?.url) {
- const url = new URL(result.url);
- const path = getPathFromUrl(url);
- history.push(path);
- }
- });
- }, []);
-
- return null;
- }
-
- function getPathFromUrl(url: URL): string {
- // Handle both custom scheme and https
- if (url.protocol === 'myapp:') {
- return '/' + url.host + url.pathname;
- }
- return url.pathname + url.search;
- }
- ```
-
- ### Vue Router Integration
-
- ```typescript
- import { App } from '@capacitor/app';
- import { useRouter } from 'vue-router';
- import { onMounted } from 'vue';
-
- export function useDeepLinks() {
- const router = useRouter();
-
- onMounted(async () => {
- App.addListener('appUrlOpen', (event) => {
- const path = parseDeepLink(event.url);
- router.push(path);
- });
-
- const launchUrl = await App.getLaunchUrl();
- if (launchUrl?.url) {
- const path = parseDeepLink(launchUrl.url);
- router.push(path);
- }
- });
- }
- ```
-
- ### Deferred Deep Links
-
- Handle links when app wasn't installed:
-
- ```typescript
- import { App } from '@capacitor/app';
- import { Preferences } from '@capacitor/preferences';
-
- // On first launch, check for deferred link
- async function checkDeferredDeepLink() {
- const { value: isFirstLaunch } = await Preferences.get({ key: 'firstLaunch' });
-
- if (isFirstLaunch !== 'false') {
- await Preferences.set({ key: 'firstLaunch', value: 'false' });
-
- // Check with your attribution service
- const deferredLink = await fetchDeferredLink();
- if (deferredLink) {
- handleDeepLink(new URL(deferredLink));
- }
- }
- }
- ```
-
- ## Query Parameters
-
- ```typescript
- App.addListener('appUrlOpen', (event) => {
- const url = new URL(event.url);
-
- // Get query parameters
- const source = url.searchParams.get('source');
- const campaign = url.searchParams.get('campaign');
- const referrer = url.searchParams.get('ref');
-
- // Track attribution
- analytics.logEvent('deep_link_open', {
- path: url.pathname,
- source,
- campaign,
- referrer,
- });
-
- // Navigate with state
- navigateTo(url.pathname, {
- state: { source, campaign, referrer },
- });
- });
+ <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="myapp" />
+ </intent-filter>
```
- ## OAuth Callback Handling
-
- ```typescript
- // Handle OAuth redirect
- App.addListener('appUrlOpen', async (event) => {
- const url = new URL(event.url);
-
- if (url.pathname === '/oauth/callback') {
- const code = url.searchParams.get('code');
- const state = url.searchParams.get('state');
- const error = url.searchParams.get('error');
-
- if (error) {
- handleOAuthError(error);
- return;
- }
-
- if (code && validateState(state)) {
- await exchangeCodeForToken(code);
- navigateTo('/home');
- }
- }
- });
- ```
+ ## Verification
- ## Testing
+ Run every row on a physical device (Universal Links do not work reliably from the Simulator address bar; tap from Notes/Messages instead).
- ### Test Matrix
+ | Scenario | iOS | Android |
+ |----------|-----|---------|
+ | Custom scheme, warm | `xcrun simctl openurl booted "myapp://product/123"` | `adb shell am start -W -a android.intent.action.VIEW -d "myapp://product/123" com.example.app` |
+ | Custom scheme, cold | kill app, then same command | `adb shell am force-stop com.example.app`, then same command |
+ | Verified link, warm | tap `https://example.com/product/123` in Notes | `adb shell am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://example.com/product/123"` |
+ | Verified link, cold | swipe app away, tap link | force-stop, then same command |
+ | Ownership check | `curl -sI https://example.com/.well-known/apple-app-site-association` (200, no redirect) | `adb shell pm get-app-links com.example.app` shows `verified` |
- | Scenario | Command |
- |----------|---------|
- | Custom scheme | `myapp://path` |
- | Universal link cold start | Tap link with app closed |
- | Universal link warm start | Tap link with app in background |
- | Universal link in Safari | Type URL in Safari |
- | App link cold start | Tap link with app closed |
- | App link in Chrome | Tap link in Chrome |
+ Pass criteria: each case lands on the right route, `appUrlOpen` logs once, and on cold start `getLaunchUrl()` returns the URL. After a Capacitor 8.5 scene migration, re-run the full matrix: cold launch takes a different native path (`scene(_:willConnectTo:options:)`) than warm open (`scene(_:openURLContexts:)` / `scene(_:continue:)`).
- ### Debug Tools
+ Grep for dead handlers after migration:
```bash
- # iOS: Check associated domains entitlement
- codesign -d --entitlements - App.app | grep associated-domains
-
- # iOS: Reset Universal Links cache
- xcrun simctl erase all
-
- # Android: Check verified links
- adb shell dumpsys package d | grep -A5 "Package: com.yourcompany.yourapp"
+ grep -n "open url: URL\|continue userActivity" ios/App/App/AppDelegate.swift
+ grep -n "SceneDelegateProxy" ios/App/App/SceneDelegate.swift
```
- ## Common Issues
+ ## Error Handling
- | Issue | Solution |
- |-------|----------|
- | Universal Links not working | Check AASA file, SSL, entitlements |
- | App Links not verified | Check assetlinks.json, fingerprint |
- | Links open in browser | Check intent-filter, autoVerify |
- | Cold start not handled | Use `App.getLaunchUrl()` |
- | Simulator issues | Reset simulator, rebuild app |
+ | Symptom / message | Cause | Fix |
+ |-------------------|-------|-----|
+ | Link opens in Safari, app installed | AASA not fetched, wrong `appID`, entitlement missing, or user long-pressed and chose "Open in Safari" | Check AASA via Apple CDN, `TEAMID.bundleId`, `applinks:` entitlement; long-press link and choose "Open in App" to reset |
+ | Custom AppDelegate URL code stopped running after 8.5 update | Scene manifest exists; iOS calls SceneDelegate instead | Move logic to `SceneDelegate` (reference: ios-scene-delegate) |
+ | Warm opens work, cold launch lands on home | Listener registered late, or custom SceneDelegate code ignores `connectionOptions` | Call `getLaunchUrl()` at bootstrap; keep `SceneDelegateProxy.shared.scene(_:willConnectTo:options:)` |
+ | `Safari cannot open the page because the address is invalid` | Custom scheme not registered in installed build | Add `CFBundleURLTypes`, rebuild (not just `cap sync`) |
+ | `Error: Activity not started, unable to resolve Intent` | No intent-filter matches scheme/host | Fix `<data>` entries; reinstall app |
+ | `pm get-app-links` shows `1024` or `none` | assetlinks.json unreachable, wrong package, or wrong SHA-256 (often the Play App Signing key) | Fix file, then `adb shell pm verify-app-links --re-verify com.example.app` |
+ | Android shows app chooser for https link | Domain not verified (`autoVerify` missing or failed) | Add `android:autoVerify="true"`, re-verify |
+ | OAuth redirect returns to browser tab, not app | Redirect URI does not match registered scheme / verified domain | Register exact redirect URI; prefer verified https link |
## Resources
- - Capacitor App Plugin: https://capacitorjs.com/docs/apis/app
- - Universal Links Guide: https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app
- - Android App Links: https://developer.android.com/training/app-links
- - Digital Asset Links Validator: https://developers.google.com/digital-asset-links/tools/generator
+ - Capacitor deep links guide: https://capacitorjs.com/docs/guides/deep-links
+ - App plugin API: https://capacitorjs.com/docs/apis/app
+ - Updating to 8.5 (UIScene): https://capacitorjs.com/docs/updating/8-5
+ - Apple Universal Links: https://developer.apple.com/documentation/xcode/supporting-associated-domains
+ - Android App Links: https://developer.android.com/training/app-links/verify-android-applinks