Cap-go avatar

capacitor-features

Capacitor feature skills for deep links, keyboard handling, offline-first data, push notifications, splash screens, and App Intents (Siri, Shortcuts, Spotlight).

version
1.1.0
GitHub stars
79

Install

/plugin install capacitor-features@capgo-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Cap-go/capgo-skills.

Contents

Discovered from source

Skills 6

App Intents for Capacitor Apps

Add native App Intents to the iOS project so system surfaces can run app actions, and connect them to the web layer. App Intents are Swift only. There is no JavaScript API for them, so every intent is native code in the App target or an extension, and the web layer is reached through a URL or a small local plugin.

When to Use

TRIGGER when:

  • The user wants Siri phrases, Shortcuts actions, App Shortcuts, Spotlight actions, Action button or Apple Intelligence integration for a Capacitor app
  • The user wants a widget button or a Control Center control to run an app action
  • An intent opens the app, but the web view does not navigate, or it navigates only on warm launch
  • A background intent crashes, times out, or tries to call JS
  • Migrating openAppWhenRun to supportedModes, or adopting iOS 26/27 App Intents APIs
  • A plugin author wants to ship App Intents with a plugin

Do not use:

  • JavaScript dispatch for Siri, Shortcuts, Spotlight, or Home Screen quick actions via @capgo/capacitor-app-intents: use capacitor-plugins (capgo-plugin-index.md, package @capgo/capacitor-app-intents). This skill is for native Swift App Intents (app target, extensions, or plugin native code), not that plugin API.
  • Universal Links / custom scheme / appUrlOpen setup: capacitor-deep-linking
  • AppDelegate to SceneDelegate migration: capacitor-uiscene-migration
  • Push notification actions: capacitor-push-notifications
  • Live Activities or SVG widgets driven from JS: capacitor-plugins (@capgo/capacitor-widget-kit)
  • Android app shortcuts and intents: not covered here

Facts that drive the design

  • App Intents need iOS 16. Capacitor 8 deploys to iOS 15, so every intent type, entity, query and AppShortcutsProvider needs @available(iOS 16.0, *), or the user raises the deployment target. Capacitor 9 deploys to iOS 16, so the base API needs no gating. Newer APIs still do (tables in references/ios-26-27-apis.md).
  • A background intent has no WebView. iOS can launch the app process headless for .background intents. AppDelegate.application(_:didFinishLaunchingWithOptions:) runs, but no scene connects and CAPBridgeViewController never loads. Background intents must do native work only (network, storage, HealthKit, etc.). They cannot call JS or plugins through the bridge.
  • perform() is not on the main actor, and it can run more than once. Hop explicitly (await MainActor.run or @MainActor func perform()) before you touch UIKit, the bridge or @MainActor state. Do irreversible work last. Details: references/intent-traps.md.
  • With UIScene (Capacitor 8.5+) URL delivery moved. Universal Links and custom-scheme opens reach SceneDelegate and are forwarded by SceneDelegateProxy, which posts the notifications @capacitor/app listens to. If the app still has custom URL code in AppDelegate, it no longer runs. Check capacitor-deep-linking first if appUrlOpen does not fire for a normal link. An intent cannot fix a broken link pipeline.
  • On cold launch the JS listener does not exist yet. Any route an intent hands to the web layer must survive until JS asks for it: use App.getLaunchUrl() for URLs, or a pending-route store plus notifyListeners(..., retainUntilConsumed: true) for the local-plugin path.
  • Identifiers are a public contract. Intent type names, AppEntity.id values, AppEnum raw values, URL formats and shipped phrases are stored in users' saved shortcuts. Add new ones; do not rename or remove shipped ones without telling the user.

References

Only load a reference when its topic is in play.

FileLoad when
references/project-setup.mdCreating files, target membership, extensions, App Groups, availability gating, build verification
references/web-bridge.mdConnecting an intent to the web layer: URL routing, the local AppIntentsBridge plugin, pending routes, shared data
references/intent-traps.mdWriting or reviewing any intent, entity, query, phrase, dependency, error or donation
references/ios-26-27-apis.mdsupportedModes, foreground continuation, long-running/cancellable/undoable intents, execution targets, snippets, Spotlight indexing, schemas, testing
references/widgets-and-controls.mdWidget configuration intents, interactive widget buttons, Control Center controls

Workflow

1. Inspect (read-only)

  1. Read package.json (@capacitor/ios version), ios/App/App/Info.plist (scene manifest present?), ios/App/App/AppDelegate.swift, ios/App/App/SceneDelegate.swift, the App target's deployment target, and any existing *.entitlements (Associated Domains, App Groups).
  2. Check whether the app already handles deep links in JS (App.addListener('appUrlOpen', ...), App.getLaunchUrl()) and which routes exist.
  3. Search for existing intents: grep -rn "AppIntent\|AppShortcutsProvider\|openAppWhenRun" ios/App.
  4. List extension targets (widgets) in ios/App/App.xcodeproj/project.pbxproj (PBXNativeTarget entries other than App).

2. Design with the user

For each action the user wants, decide and confirm:

QuestionOptions
Does it need the UI?No: background intent, native only. Yes: foreground intent that routes into the web app
How does it reach JS?Universal Link via OpenURLIntent (iOS 18+, needs Associated Domains), or a local plugin with a pending-route store (works with custom schemes and iOS 16+)
What data does it need?Fixed set: AppEnum. Dynamic, queryable: AppEntity + EntityQuery. Free text or number: plain @Parameter
Where must it run?App target only, or also a widget / control (then the intent file needs both target memberships)
Which surfaces?App Shortcut phrase (at most 10 App Shortcuts per app), Spotlight, widget, control

Keep one intent per atomic task. Report the plan (files to add, targets, entitlements, JS changes) before editing.

3. Implement

  1. Create the Swift files in ios/App/App/Intents/ with the App target membership (references/project-setup.md).
  2. Write the intents following references/intent-traps.md. Gate APIs by version.
  3. Add the web bridge (references/web-bridge.md): either reuse the deep-link router, or add the local plugin and register it in a CAPBridgeViewController subclass.
  4. Add an AppShortcutsProvider with shortTitle, systemImageName and \(.applicationName) in every phrase.
  5. Add entitlements only when needed (App Groups for shared data, Associated Domains for Universal Links), and on every target that uses them.
  6. JS side: handle the route on warm and cold start.

4. Verify

npx cap sync ios
xcodebuild -project ios/App/App.xcodeproj -scheme App \
  -destination 'generic/platform=iOS Simulator' build
# CocoaPods projects: -workspace ios/App/App.xcworkspace
  • The build log shows the App Intents metadata extraction step with no warnings about phrases. A phrase without \(.applicationName) produces a build warning and is dropped at runtime.
  • Product > App Shortcuts Preview in Xcode shows the phrases matching.
  • Run on a simulator or device: open the Shortcuts app, find the app's actions, run each one.
    • Background intent: completes without the app coming to the foreground. Check the native logs (ios-android-logs).
    • Foreground intent, app killed first (cold) and app running (warm): the web view lands on the right route both times.
  • Spotlight: search the shortcut title.
  • If tests exist, add AppIntentsTesting coverage for iOS 27 test runners (references/ios-26-27-apis.md).

Error Handling

SymptomCauseFix
'AppIntent' is only available in iOS 16.0 or newerCapacitor 8 project deploys to iOS 15Add @available(iOS 16.0, *) to every App Intents type, or raise the deployment target with the user's approval
Intent missing from Shortcuts after installFile not in the App target, or metadata extraction failedCheck target membership. Read the build log for the App Intents metadata step. Reinstall the app
Phrase never triggers Siri; build warning about the application namePhrase lacks \(.applicationName)Add the token to every phrase
Build error about more than 10 App ShortcutsPer-app capMerge actions or drop low-value ones
Crash "...was not initialized prior to access" from @DependencyDependency registered too late (in a view controller)Register in AppDelegate.application(_:didFinishLaunchingWithOptions:), which runs on headless launches too
Foreground intent opens the app but the web view stays on the home route on cold startThe route was posted before JS added its listenerUse the pending-route store + retainUntilConsumed, or App.getLaunchUrl()
appUrlOpen never fires for OpenURLIntentUniversal Links not configured, or custom AppDelegate URL code under UISceneFix with capacitor-deep-linking. OpenURLIntent needs a real https Universal Link
Swift 6 error: main actor-isolated property cannot satisfy nonisolated requirementThe intent type is marked @MainActorRemove @MainActor from the type. Put it on perform() or hop inside
Background intent killed after about 30 secondsiOS limit for background intentsShorten the work, or use LongRunningIntent on iOS 27
'openAppWhenRun' was deprecated in iOS 26.0iOS 26 SDKAdd a gated supportedModes (references/ios-26-27-apis.md). Keep openAppWhenRun while the deployment target is below 26

Related Skills

  • capacitor-deep-linking: Universal Links and appUrlOpen routing the intents rely on
  • capacitor-uiscene-migration: required before Xcode 27; moves URL handling to SceneDelegate
  • capacitor-plugins: @capgo/capacitor-widget-kit for Live Activities and JS-driven widgets
  • capacitor-testing: native unit tests and the device verification loop
  • ios-android-logs: logs from headless intent runs

Deep Linking in Capacitor

Route custom-scheme links, iOS Universal Links, and Android App Links into the web app.

When to Use

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

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

Link Types

TypePlatformFormatNeeds hosted fileVerified ownership
Custom schemebothmyapp://product/123nono (any app can claim it)
Universal LinksiOShttps://example.com/product/123/.well-known/apple-app-site-associationyes
App LinksAndroid 6+https://example.com/product/123/.well-known/assetlinks.jsonyes

Prefer verified https links for anything security-sensitive (OAuth, magic links). Custom schemes can be hijacked by another app.

Workflow

  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.
    • 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:
  6. Route in the framework router: references/routing-patterns.md (React, Vue, Angular, OAuth callbacks, deferred links).
  7. Verify with the cold/warm matrix below on a real device.

Only load a reference when its topic is in play.

JS Handler (the part every app needs)

import { App, type URLOpenListenerEvent } from '@capacitor/app';

let lastHandled: string | undefined;

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
}

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);
}

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.

Custom Scheme Config

iOS ios/App/App/Info.plist:

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLName</key>
    <string>com.example.app</string>
    <key>CFBundleURLSchemes</key>
    <array><string>myapp</string></array>
  </dict>
</array>

Android AndroidManifest.xml, inside the existing MainActivity (keep the template's android:launchMode="singleTask" so warm opens reuse the activity):

<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>

Verification

Run every row on a physical device (Universal Links do not work reliably from the Simulator address bar; tap from Notes/Messages instead).

ScenarioiOSAndroid
Custom scheme, warmxcrun 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, coldkill app, then same commandadb shell am force-stop com.example.app, then same command
Verified link, warmtap https://example.com/product/123 in Notesadb shell am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://example.com/product/123"
Verified link, coldswipe app away, tap linkforce-stop, then same command
Ownership checkcurl -sI https://example.com/.well-known/apple-app-site-association (200, no redirect)adb shell pm get-app-links com.example.app shows verified

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:)).

Grep for dead handlers after migration:

grep -n "open url: URL\|continue userActivity" ios/App/App/AppDelegate.swift
grep -n "SceneDelegateProxy" ios/App/App/SceneDelegate.swift

Error Handling

Symptom / messageCauseFix
Link opens in Safari, app installedAASA 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 updateScene manifest exists; iOS calls SceneDelegate insteadMove logic to SceneDelegate (reference: ios-scene-delegate)
Warm opens work, cold launch lands on homeListener registered late, or custom SceneDelegate code ignores connectionOptionsCall getLaunchUrl() at bootstrap; keep SceneDelegateProxy.shared.scene(_:willConnectTo:options:)
Safari cannot open the page because the address is invalidCustom scheme not registered in installed buildAdd CFBundleURLTypes, rebuild (not just cap sync)
Error: Activity not started, unable to resolve IntentNo intent-filter matches scheme/hostFix <data> entries; reinstall app
pm get-app-links shows 1024 or noneassetlinks.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 linkDomain not verified (autoVerify missing or failed)Add android:autoVerify="true", re-verify
OAuth redirect returns to browser tab, not appRedirect URI does not match registered scheme / verified domainRegister exact redirect URI; prefer verified https link

Resources

Keyboard Handling in Capacitor

When to Use

TRIGGER when:

  • Focused input is covered by the keyboard, or the page scrolls unexpectedly
  • Chat composer / fixed footer does not stick to the keyboard
  • White or black band above the keyboard (Android 15+ edge-to-edge, iOS backdrop)
  • 100vh / dvh layout collapses when the keyboard opens
  • iOS zooms into inputs, or the QuickType/accessory bar looks wrong
  • Keyboard events never fire or fire twice

Do not use:

  • Notch / home-indicator / status-bar padding: safe-area-handling
  • Ionic ion-input, ion-footer styling: ionic-design
  • Labels, focus order, screen readers: capacitor-accessibility

Platform model (the key decision)

iOSAndroid
Who resizesPlugin, per resize modeOS + WebView; resize config is ignored
EventskeyboardWillShow before animation, keyboardDidShow afterWill/Did fire almost together
JS controlsetResizeMode, getResizeMode, setScroll, setStyle, setAccessoryBarVisible (iPhone only)show() (Android only), hide()

iOS resize modes (KeyboardResize enum):

ModeEffectUse when
native (default)Whole WebView shrinks; vh units changePlain web apps; simplest
bodyOnly <body> height changes; vh unchangedLayouts that rely on stable vh
ionicOnly ion-app resizesIonic Framework apps only
noneNothing resizes; you position with keyboard heightCustom chat UIs, full control

Workflow

  1. Inspect: capacitor.config.* plugins.Keyboard, @capacitor/keyboard version (8.0.4+ includes iOS 26 and Android SystemBars fixes), whether Ionic is used, @capacitor/status-bar / SystemBars config, and the failing screen's CSS (position: fixed, 100vh).
  2. Reproduce on a device (simulators often use a hardware keyboard: iOS Simulator -> I/O -> Keyboard -> Toggle Software Keyboard).
  3. Pick the iOS resize mode from the table; set it in config, not at runtime, unless one screen needs a different mode.
  4. Fix Android separately (below).
  5. Verify.

Config

// capacitor.config.ts
import { KeyboardResize, KeyboardStyle } from '@capacitor/keyboard';

plugins: {
  Keyboard: {
    resize: KeyboardResize.Body,      // iOS only
    style: KeyboardStyle.Default,     // iOS only; JSON value is "DARK" | "LIGHT" | "DEFAULT"
    // resizeOnFullScreen: omit on Capacitor 8+ (SystemBars handles insets; see Android notes)
    autoBackdropColor: 'auto',        // iOS, 8.0.4+: 'off' (default) | 'auto' | 'dom'
  },
},

String values in JSON config are uppercase for style ("DARK"), lowercase for resize ("body").

Custom positioning (resize: none or chat UIs)

import { Capacitor } from '@capacitor/core';
import { Keyboard } from '@capacitor/keyboard';

if (Capacitor.isNativePlatform()) {
  Keyboard.addListener('keyboardWillShow', ({ keyboardHeight }) => {
    document.documentElement.style.setProperty('--kb', `${keyboardHeight}px`);
  });
  Keyboard.addListener('keyboardWillHide', () => {
    document.documentElement.style.setProperty('--kb', '0px');
  });
}
.composer {
  position: fixed;
  inset-inline: 0;
  bottom: max(var(--kb, 0px), env(safe-area-inset-bottom));
}

Use max(), not +: while the keyboard is up the home-indicator inset is already covered.

Android notes

  • Android 15+ (targetSdk 35) enforces edge-to-edge; Android 16 (targetSdk 36, Capacitor 8 default) removes the opt-out. The WebView now draws under system bars, so the keyboard inset must be handled. @capacitor/keyboard 7.0.2 fixed white space above the keyboard on Android 15+, and 8.0.3 fixed the interaction with the SystemBars core plugin. Update the plugin before writing workarounds.
  • resizeOnFullScreen: true was the Capacitor <= 7 workaround for fullscreen / overlaid status bar. On Capacitor 8+ the SystemBars core plugin handles IME insets and logs You should omit `Keyboard.resizeOnFullScreen` in your `capacitor.config.json`. Other values can lead to unexpected behavior. unless SystemBars.insetsHandling is disable. Remove it.
  • Do not add android:windowSoftInputMode="adjustPan" to fix overlap; it pans the whole window and breaks fixed headers. The template omits it (default resize behavior).
  • env(keyboard-inset-height) and interactive-widget viewport meta are Chromium features; test on the target Android System WebView version before relying on them, and never on iOS.

iOS notes

  • Inputs with computed font-size < 16px make iOS zoom on focus. Use font-size: 16px (or larger) on inputs; do not disable user zoom globally (maximum-scale=1) as it hurts accessibility.
  • setAccessoryBarVisible({ isVisible: false }) hides the prev/next/done bar on iPhone; it has no effect on iPad.
  • setScroll({ isDisabled: true }) stops the WebView scroll view from bouncing when the keyboard opens; pair with resize: none for custom layouts.
  • iOS 26 keyboard regressions and the iPad Magic Keyboard black QuickType bar were fixed in @capacitor/keyboard 8.0.4. If a black/white band appears behind the keyboard, set autoBackdropColor: 'auto' (uses backgroundColor from config, else the DOM body background) or 'dom'.

Verification

  1. npx cap sync and run on a physical iPhone and an Android 15+/16 device.
  2. For each form screen: focus first and last input; the focused field stays visible; footer sits on the keyboard; no gap above the keyboard; rotating with the keyboard open keeps layout.
  3. Dismiss via swipe/back button: keyboardWillHide fires and --kb returns to 0.
  4. iOS: confirm no zoom on focus; accessory bar state matches the design.
  5. Check versions: npm ls @capacitor/keyboard @capacitor/core.

Error Handling

Symptom / messageCauseFix
"Keyboard" plugin is not implemented on web or "Keyboard.setAccessoryBarVisible()" is not implemented on androidPlugin/method unavailable on that platformGuard with Capacitor.getPlatform() === 'ios'
show() does nothing on iOSshow() is Android onlyFocus an input from a user gesture instead
Footer floats in the middle after keyboard closes (Android)WebView height not reset when keyboard hides without animationUpdate to @capacitor/keyboard 8.0.4+
White band above keyboard on Android 15+Edge-to-edge insets + old pluginUpdate plugin (7.0.2+ / 8.0.3+); on Capacitor 8 remove resizeOnFullScreen
Logcat SystemBars: You should omit `Keyboard.resizeOnFullScreen` ...Legacy config fighting SystemBars inset handlingDelete resizeOnFullScreen from config
vh-based screen shrinks on iOSresize: native changes viewportSwitch to body or none
Ionic content jumps twiceresize: native/body plus Ionic's own handlingUse resize: 'ionic'
Listeners fire twice after navigationListener added per page mount, never removedKeep the returned handle and await handle.remove() on unmount
Black QuickType bar on iPad with hardware keyboardPre-8.0.4 plugin bugUpdate plugin

Resources

Offline-First Capacitor Apps

When to Use

TRIGGER when:

  • The app must read and write while offline and sync later
  • Choosing local storage (Preferences vs SQLite vs IndexedDB) for user data
  • Writes are duplicated, lost, or overwritten during sync
  • Cached data vanishes on iOS after low-storage events
  • A service worker was added and native plugins stopped working (Plugin not implemented)

Do not use:

  • Replacing @capacitor-community/sqlite / Ionic secure storage: sqlite-to-fast-sql
  • Getting new web code to devices (OTA): capgo-live-updates
  • Encryption key storage, SSL pinning: capacitor-security
  • Query speed / bridge overhead tuning: capacitor-performance

Decisions (make these before writing code)

QuestionDefault answer
Where does UI read from?Local DB only. Network writes into the DB; UI observes the DB.
Storage for recordsSQLite via @capgo/capacitor-fast-sql
Storage for small settings / tokens@capacitor/preferences (not for secrets; see capacitor-security)
localStorage / IndexedDBTransient only: iOS can evict WebView storage under pressure
App shell offlineAlready offline: Capacitor bundles web assets in the binary (or Capgo live-update bundle). No service worker needed.
Service worker in native buildsAvoid. Android SW blocks Capacitor plugin injection; iOS SW needs WKAppBoundDomains, which also blocks injection unless ios.limitsNavigationsToAppBoundDomains is set. Keep SW for the PWA build only.
IDsClient-generated UUIDs (crypto.randomUUID()), so offline creates need no server round trip
Conflict policyAsk the user/product owner: last-write-wins per record, per-field merge, or server-authoritative with user review
DeletesSoft delete (tombstone) until the server acknowledges

Workflow

  1. Inspect: current storage (localStorage, @capacitor/preferences, other SQLite plugins), API shape (does it support updated_since / version fields / idempotency keys?), auth refresh flow, existing service worker registration.
  2. Report the plan (schema, outbox, conflict policy) to the user before invasive changes. For large apps, list each entity as a TODO.
  3. Install: npm install @capgo/capacitor-fast-sql @capacitor/network && npx cap sync, then the platform setup in references/fast-sql-setup.md (required: iOS ATS local networking, Android localhost cleartext).
  4. Schema + outbox: references/sync-engine.md.
  5. Triggers for sync: app start, networkStatusChange -> connected, App resume, after each local write (debounced), optional background task.
  6. UI: show pending count / last synced time; never block a write on the network.
  7. Verify (below).

Only load a reference when its topic is in play.

Minimal shape

import { FastSQL } from '@capgo/capacitor-fast-sql';
import { Network } from '@capacitor/network';
import { App } from '@capacitor/app';

const db = await FastSQL.connect({ database: 'app' });
await db.execute(`CREATE TABLE IF NOT EXISTS outbox (
  id TEXT PRIMARY KEY, entity TEXT NOT NULL, op TEXT NOT NULL,
  payload TEXT NOT NULL, created_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0
)`);

export async function saveTodo(todo: Todo) {
  await db.transaction(async (tx) => {
    await tx.run('INSERT OR REPLACE INTO todos (id, text, done, updated_at, dirty) VALUES (?, ?, ?, ?, 1)',
      [todo.id, todo.text, todo.done ? 1 : 0, Date.now()]);
    await tx.run('INSERT INTO outbox (id, entity, op, payload, created_at) VALUES (?, ?, ?, ?, ?)',
      [crypto.randomUUID(), 'todo', 'upsert', JSON.stringify(todo), Date.now()]);
  });
  void sync(); // fire and forget; sync() is single-flight
}

Network.addListener('networkStatusChange', (s) => { if (s.connected) void sync(); });
App.addListener('resume', () => void sync());

The data row and its outbox entry are written in one transaction so a crash cannot leave one without the other.

Traps

  • Network.getStatus().connected === true does not mean the API is reachable (captive portals, VPN, server down). Treat fetch failures as offline; use connected only as a hint to retry.
  • networkStatusChange can fire several times in a row; make sync() single-flight.
  • Send an idempotency key (the outbox row id) with every mutation; retries after a timeout otherwise duplicate records.
  • Process the outbox in order per entity; a delete must not overtake its create.
  • Advance the pull cursor using the server's timestamp/version from the response, never the device clock.
  • Auth tokens expire while offline: refresh before draining the outbox, and keep entries on 401 instead of dropping them.
  • Do not store large blobs in SQLite rows; save files with @capacitor/filesystem and keep the path in the DB.
  • iOS background execution is opportunistic. Background tasks help but cannot guarantee sync timing; foreground sync on resume is the reliable path.

Verification

  1. Airplane mode on device: create, edit, delete records; kill and relaunch the app; data is still there.
  2. Turn network back on: outbox drains to 0, server reflects all changes once (no duplicates).
  3. Conflict test: edit the same record on two devices offline, reconnect both; result matches the chosen policy.
  4. Flaky network: Android emulator network throttling / iOS Network Link Conditioner (Settings -> Developer); retries back off, no data loss.
  5. Native checks:
grep -rn "serviceWorker.register" src/ | grep -v "isNativePlatform"   # should be empty or web-guarded
/usr/libexec/PlistBuddy -c "Print :NSAppTransportSecurity:NSAllowsLocalNetworking" ios/App/App/Info.plist
grep -n "networkSecurityConfig\|usesCleartextTraffic" android/app/src/main/AndroidManifest.xml
  1. Inspect the DB: SELECT COUNT(*) FROM outbox exposed in a debug screen, or pull the file (adb exec-out run-as com.example.app ls databases/).

Error Handling

Error / symptomCauseFix
"CapgoCapacitorFastSql" plugin is not implemented on android / Plugin not implementedService worker or WKAppBoundDomains blocking injection, or missing npx cap syncRemove SW from native build / set ios.limitsNavigationsToAppBoundDomains; run npx cap sync
iOS: The resource could not be loaded because the App Transport Security policy requires the use of a secure connectionFast SQL localhost transport blocked by ATSAdd NSAllowsLocalNetworking
Android: CLEARTEXT communication to localhost not permitted by network security policyCleartext to localhost blockedAdd network_security_config.xml localhost exception
SQLITE_CONSTRAINT: UNIQUE constraint failed during pullServer row id already exists locallyUse INSERT ... ON CONFLICT(id) DO UPDATE
database is lockedParallel writers / long transactionSerialize writes; keep transactions short; single-flight sync
Data gone after iOS storage pressureStored in localStorage / IndexedDBMove to SQLite
Duplicate server records after reconnectRetried POST without idempotency keySend outbox id as Idempotency-Key; server dedupes

Resources

Push Notifications in Capacitor

When to Use

TRIGGER when:

  • Adding remote push (FCM / APNs) to a Capacitor app
  • registration / registrationError never fire, or the token works on one platform only
  • iOS token is a 64-hex APNs token but the backend expects an FCM token
  • Notifications arrive in background but not in foreground (or vice versa)
  • Android 13+ shows no prompt and nothing is delivered
  • Upgrading to Capacitor 8.5 (UIScene) or 9 (alert presentation option removed)

Do not use:

  • Opening the app from https:// / myapp:// links: capacitor-deep-linking
  • Moving AppDelegate code to SceneDelegate: capacitor-uiscene-migration
  • Device log capture: ios-android-logs
  • Choosing other native plugins: capacitor-plugins

Choose the plugin first (ask the user if unclear)

NeedPlugin
Official plugin; APNs token on iOS, FCM token on Android@capacitor/push-notifications
FCM token on both platforms, topics, Firebase-first backend@capgo/capacitor-firebase-messaging
Capgo-managed delivery (dashboard campaigns, badges, silent live-update checks, no own push server)@capgo/capacitor-notifications
Local notifications only, rich layouts@capgo/capacitor-rich-notifications or @capacitor/local-notifications

The rest of this file covers @capacitor/push-notifications. For Capgo plugins follow https://capgo.app/docs/plugins/firebase-messaging/ or https://capgo.app/docs/plugins/notifications/getting-started/.

Workflow

  1. Inspect: package.json versions (@capacitor/core, @capacitor/push-notifications), capacitor.config.* plugins.PushNotifications, ios/App/App/AppDelegate.swift, ios/App/App/*.entitlements, android/app/google-services.json, android/variables.gradle, AndroidManifest.xml.
  2. Install: npm install @capacitor/push-notifications && npx cap sync.
  3. iOS: capability + APNs key + AppDelegate forwarding. Details: references/ios-setup.md.
  4. Android: google-services.json, channel, icon, permission. Details: references/android-setup.md.
  5. JS: listeners first, then permission, then register() (below).
  6. Backend: send a test message. Payload shapes: references/sending.md.
  7. Verify with the checklist below on physical devices.

Only load a reference when its topic is in play.

JS registration (order matters)

import { PushNotifications } from '@capacitor/push-notifications';

export async function initPush() {
  // 1. Listeners before register(), or the first token is missed
  await PushNotifications.addListener('registration', ({ value }) => sendTokenToServer(value));
  await PushNotifications.addListener('registrationError', (err) => console.error('push reg', err.error));
  await PushNotifications.addListener('pushNotificationReceived', (n) => {
    // foreground only (and Android data-only while app is alive)
  });
  await PushNotifications.addListener('pushNotificationActionPerformed', ({ notification, actionId }) => {
    routeFromNotification(notification.data); // tap handling
  });

  // 2. Permission (required on iOS and Android 13+ / targetSdk 33+)
  let perm = await PushNotifications.checkPermissions();
  if (perm.receive === 'prompt' || perm.receive === 'prompt-with-rationale') {
    perm = await PushNotifications.requestPermissions();
  }
  if (perm.receive !== 'granted') return; // explain + link to settings, do not loop prompts

  // 3. Register
  await PushNotifications.register();
}

Traps:

  • Call initPush() at bootstrap so pushNotificationActionPerformed from a cold-start tap is captured.
  • Tokens rotate. Send every registration value to the server and upsert by user + device.
  • On iOS the plugin reports the raw APNs token unless AppDelegate swaps in the FCM token (see ios-setup). Sending an APNs token to FCM fails with messaging/invalid-registration-token.
  • Ask permission after a user action that explains the value; iOS shows the system prompt only once.

Foreground presentation

// capacitor.config.ts
plugins: {
  PushNotifications: {
    presentationOptions: ['badge', 'sound', 'banner', 'list'],
  },
},
  • banner + list replace the deprecated iOS alert. Capacitor 9 removes alert on iOS; replace it when upgrading. badge is iOS only.
  • Empty array = nothing shown in foreground; handle pushNotificationReceived yourself.

Capacitor version notes

VersionChange
7firebaseMessagingVersion default 24.1.0
8firebaseMessagingVersion default 25.0.1
8.5UIScene lifecycle. Remote-notification callbacks (didRegisterForRemoteNotificationsWithDeviceToken, didFailToRegister...) stay in AppDelegate and keep working. Do not move them to SceneDelegate. Tap routing that used AppDelegate application(_:open:) must move (see capacitor-deep-linking).
9iOS alert presentation option removed; iOS 16 min; @main replaces @UIApplicationMain; google-services Gradle plugin 4.5.0

Verification

  1. iOS: codesign -d --entitlements :- path/to/App.app | grep aps-environment shows development (debug) or production (TestFlight/App Store).
  2. Android: adb shell dumpsys package com.example.app | grep POST_NOTIFICATIONS shows granted=true after accepting the prompt.
  3. App logs a registration token on a real device (iOS Simulator on Apple silicon can receive pushes via xcrun simctl push, but test real APNs on device).
  4. Send a test from Firebase Console (Messaging -> "Send test message") or your backend to that token.
  5. Check all three states: foreground (presentation + pushNotificationReceived), background (system tray), killed (tap -> pushNotificationActionPerformed routes correctly).
  6. iOS simulator smoke test without a server:
cat > /tmp/push.apns <<'EOF'
{ "Simulator Target Bundle": "com.example.app", "aps": { "alert": { "title": "Test", "body": "Hello" } }, "route": "/inbox" }
EOF
xcrun simctl push booted com.example.app /tmp/push.apns

(aps.alert in the APNs payload is the message content and is unaffected by the presentationOptions change.)

Error Handling

Error / symptomCauseFix
no valid "aps-environment" entitlement string found for applicationPush Notifications capability missing or profile not regeneratedAdd capability in Xcode, re-sign, rebuild
registration never fires on iOS, no errorAppDelegate does not post .capacitorDidRegisterForRemoteNotificationsAdd forwarding methods to AppDelegate
Default FirebaseApp is not initialized in this process (Android)google-services.json missing/empty, so google-services plugin was not applied (google-services.json not found, google-services plugin not applied. Push Notifications won't work)Put file in android/app/, rebuild
messaging/registration-token-not-registeredToken stale (app reinstalled / data cleared)Delete token server-side; rely on next registration
messaging/invalid-registration-token / BadDeviceTokenAPNs token sent to FCM, or sandbox token sent to production APNsUse FCM token on iOS (ios-setup) or match APNs environment
messaging/third-party-auth-errorAPNs key not uploaded to Firebase, wrong Key ID / Team IDUpload .p8 under Firebase Project Settings -> Cloud Messaging
Android 13+: nothing shown, no promptrequestPermissions() never calledCall it; manifest permission is added by the plugin
Android shows white square iconNo monochrome notification iconSet default_notification_icon meta-data
Android notification silent / wrong importanceChannel created with low importance (importance is immutable after creation)Create a new channel id; delete the old one
Data-only message ignored when app killed (Android)Plugin only delivers while app process livesNative FirebaseMessagingService (android-setup)
iOS silent / background push not delivered to JSPlugin does not support iOS silent pushNative handling, or @capgo/capacitor-notifications silent update checks
Duplicate class errors with Firebase after Capacitor 9Old core-ktx / Kotlin stdlib pinsSee capacitor-app-upgrade-v8-to-v9

Resources

Splash Screen in Capacitor

When to Use

TRIGGER when:

  • Configuring or regenerating splash / icon assets (npx capacitor-assets generate)
  • Splash never disappears, disappears too early, or flashes white/black before the web app paints
  • Android 12+ shows a small cropped icon on a solid color instead of the full image
  • Upgrading to Capacitor 9 and the Android fade-out animation vanished
  • iOS shows a black screen after adding SceneDelegate.swift (8.5+)

Do not use:

  • Status bar / navigation bar styling and edge-to-edge insets: safe-area-handling
  • Migrating AppDelegate to SceneDelegate: capacitor-uiscene-migration
  • Slow first paint / bundle size: capacitor-performance
  • Icon requirements for store submission: capacitor-app-store

How launch works (decide what to edit)

PhaseiOSAndroid 12+Android <= 11
OS launch screen (before any code)LaunchScreen.storyboard (UILaunchStoryboardName), image Splash in Assets.xcassets/Splash.imagesetSystem SplashScreen API: theme AppTheme.NoActionBarLaunch with Theme.SplashScreen parent - icon + background color onlyandroidx.core:core-splashscreen compat, or android:background drawable
Plugin splash (until hide())Plugin overlay on the bridge viewSame system splash held via the APIPlugin ImageView / Dialog (androidSplashResourceName, androidScaleType)

Most androidScaleType, showSpinner, splashFullScreen, layoutName, useDialog, backgroundColor options do not apply on Android 12+ launch (the OS draws it). They only affect show() and pre-12 devices.

Workflow

  1. Inspect: capacitor.config.* plugins.SplashScreen, android/app/src/main/res/values/styles.xml, android/variables.gradle (coreSplashScreenVersion), ios/App/App/Info.plist, ios/App/App/SceneDelegate.swift, assets/ or resources/ folder.
  2. Install: npm install @capacitor/splash-screen && npx cap sync.
  3. Assets: put sources in assets/ (icon-only.png, icon-foreground.png, icon-background.png, splash.png, splash-dark.png; splash >= 2732x2732, icons >= 1024x1024), then npm install -D @capacitor/assets && npx capacitor-assets generate (--ios, --android, --pwa to scope). Keep the logo inside the center ~1/3 so Android 12+ circular masking does not crop it.
  4. Hide deliberately: set launchAutoHide: false and call hide() after the first meaningful render (below).
  5. Android 12+ tuning if needed: references/android-12-splash.md.
  6. Verify (below).

Recommended config

// capacitor.config.ts
plugins: {
  SplashScreen: {
    launchAutoHide: false,     // hide from JS when the UI is ready
    launchFadeOutDuration: 200, // explicit: Capacitor 9 default on Android is 0
    backgroundColor: '#ffffff', // match the first web paint to avoid a flash
  },
},
import { SplashScreen } from '@capacitor/splash-screen';

// after the router's first view has rendered (e.g. in a root component's mounted/useEffect)
await SplashScreen.hide(); // optional: { fadeOutDuration: 300 }

Traps:

  • With launchAutoHide: false, a JS crash before hide() leaves the app stuck on the splash. Add a fallback: setTimeout(() => SplashScreen.hide(), 8000).
  • Default when auto-hiding is 500 ms (launchShowDuration). Long fixed durations hurt perceived startup; hide on readiness instead.
  • Set <body> / root background to the splash background color, or the gap between native splash and first web paint flashes white (dark mode: black).
  • Live updates (capgo-live-updates): call notifyAppReady() independently of hide(); do not gate one on the other.

Version notes

VersionChange
4Android uses the Android 12 SplashScreen API + compat library
7SplashScreenShowOptions / SplashScreenHideOptions types removed -> ShowOptions / HideOptions
8coreSplashScreenVersion = '1.2.0'
8.5 (iOS)UIScene template creates the window and CAPBridgeViewController in SceneDelegate; Main.storyboard no longer supplies the root view controller. LaunchScreen.storyboard is unchanged and still required.
9Android launchFadeOutDuration default 200 -> 0 (the old default could block UI changes right after hide()). Set 200 explicitly to keep the fade.

iOS notes (Capacitor 8.5+ scenes)

  • Keep UILaunchStoryboardName = LaunchScreen in Info.plist. Apple requires a launch storyboard; deleting it causes letterboxed / wrong-size rendering.
  • Do not add views or a custom view controller to Main.storyboard expecting them to show: the 8.5 SceneDelegate sets window.rootViewController = CAPBridgeViewController() in code. Put a custom CAPBridgeViewController subclass there instead.
  • Black screen right after launch with a scene manifest = SceneDelegate creates no window (missing window = UIWindow(windowScene:) + makeKeyAndVisible()) or UISceneDelegateClassName points to a missing class. Fix with capacitor-uiscene-migration.
  • The storyboard is cached by iOS. After changing it, delete the app from the device/simulator and reinstall.
  • On resizable windows / iPad / foldables the launch storyboard must use Auto Layout constraints, not fixed frames (see capacitor-ios-resizability if present).

Verification

  1. npx cap sync then a clean native build (Product > Clean Build Folder in Xcode; ./gradlew clean in android/).
  2. Delete and reinstall the app (both platforms cache launch screens).
  3. Cold launch on: iOS device light + dark mode, Android 12+ device, Android <= 11 emulator (if minSdk allows; Capacitor 9 minSdk is 26).
  4. Confirm: no white/black flash, splash hides once the first screen is visible, fade matches the configured duration.
  5. Grep for leftovers:
grep -rn "launchFadeOutDuration\|launchAutoHide" capacitor.config.*
grep -n "Theme.SplashScreen\|postSplashScreenTheme" android/app/src/main/res/values/styles.xml
/usr/libexec/PlistBuddy -c "Print :UILaunchStoryboardName" ios/App/App/Info.plist

Error Handling

Symptom / messageCauseFix
Splash stays foreverlaunchAutoHide: false and hide() never runs (JS error, wrong import, called before plugin load)Check web console; add timeout fallback
Fade-out gone after Capacitor 9 upgrade (Android)Default launchFadeOutDuration is now 0Set launchFadeOutDuration: 200
UI changes right after hide() not visible (Android, pre-9)200 ms fade blocked updatesSet launchFadeOutDuration: 0
Android 12+ shows small icon, image croppedOS splash is icon-only by designProvide adaptive icon-safe artwork; tune windowSplashScreenAnimatedIcon
Android 12/12L no splash from third-party launchers or Android StudioPlatform bug fixed in Android 13Test from the stock launcher
error: resource drawable/splash not foundandroidSplashResourceName or styles reference a missing drawableRegenerate assets or fix the name in both config and styles.xml
AAPT: error: style attribute 'attr/windowSplashScreenAnimatedIcon' not foundcore-splashscreen dependency missingRestore implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
iOS black screen after 8.5 scene adoptionNo window created in SceneDelegateSee iOS notes / capacitor-uiscene-migration
Old splash still shows on iOSLaunch screen cacheDelete app, reboot device if needed, reinstall

Resources

Sponsors

Details

Marketplace
Cap-go/capgo-skills
Source
plugins/capacitor-features
Author
Capgo
Category
Development
License
MIT
Keywords
capacitor, push-notifications, deep-linking, offline, keyboard, app-intents, siri

More from Cap-go/capgo-skills

All 11