Architecture and the Native Bridge

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

An Ionic app looks like a single program, but at runtime it is three cooperating layers: a native shell written in Kotlin or Swift, a WebView that renders the user interface, and the Capacitor runtime that connects the two. Understanding those layers explains most of the behaviour that surprises web developers on a device: why a plugin call is asynchronous, why a request that works in the browser fails with a CORS error, why the android/ and ios/ folders belong in git, and why a native crash and a JavaScript exception are different problems. This page builds on Getting Started with Ionic and Capacitor and uses the Trailhead hiking journal as the running example.

The Layers of a Capacitor App

flowchart TB subgraph web["Web layer (TypeScript)"] ui["Ionic components and Angular pages"] svc["Services such as TrailService"] api["Plugin APIs from @capacitor/*"] end subgraph runtime["Capacitor runtime"] core["@capacitor/core: registerPlugin and call routing"] bridge["Native bridge: JSON messages and callbacks"] end subgraph native["Native shell"] android["Android: Activity, System WebView, Kotlin plugins"] ios["iOS: ViewController, WKWebView, Swift plugins"] end os["Operating system: camera, GPS, files, sensors"] ui --> svc --> api --> core --> bridge bridge --> android bridge --> ios android --> os ios --> os
Layer Role

Web layer

Your Angular, React or Vue code and the Ionic components. It is ordinary web code and runs unchanged in a browser during ionic serve.

Capacitor runtime

The JavaScript @capacitor/core package plus matching native libraries. It decides whether a plugin call is served by native code or by a web implementation.

Native shell

A real Android or iOS app project that owns the application lifecycle, permissions, icons, signing and the WebView instance.

Operating system

The platform services reached through native APIs.

The WebView

The user interface is rendered by the platform’s embedded web engine, not by a browser app:

  • On iOS the engine is WKWebView, the same WebKit engine used by Safari, delivered with the operating system.

  • On Android the engine is the Android System WebView, a Chromium-based component that Google updates through the Play Store independently of the operating system.

Consequences follow from that design. The rendering engine version on Android depends on the device’s WebView update, not on your app, so modern CSS and JavaScript features generally work but very old devices can lag. The iOS engine matches the operating system version, so a feature available in the latest Safari may be unavailable on an older iOS. Test on the oldest operating system the app supports. The WebView is also a normal web environment: the same debugging tools — Safari Web Inspector for iOS and chrome://inspect for Android — attach to a running app and show the DOM, network requests and console of the device.

How a Plugin Call Crosses the Bridge

JavaScript running in a WebView cannot touch the camera or the file system directly. Capacitor solves this with the native bridge: a plugin method call in TypeScript is serialized as a message, delivered to native code, executed there, and the result is delivered back as a resolved or rejected promise.

sequenceDiagram participant Page as Trailhead page participant Proxy as Plugin proxy in core participant Bridge as Native bridge participant Native as Kotlin or Swift plugin participant System as Operating system Page->>Proxy: Geolocation.getCurrentPosition() Proxy->>Bridge: Message with plugin id, method name, options, call id Bridge->>Native: Dispatch to the matching plugin method Native->>System: Request a location fix System-->>Native: Latitude and longitude Native-->>Bridge: Resolve the call with a JSON result Bridge-->>Proxy: Result for the call id Proxy-->>Page: Promise resolves with the position

The important properties of this flow:

  • Everything is asynchronous. Every plugin method returns a promise (or accepts a listener for events), so the user interface is never blocked by native work.

  • Data is JSON. Arguments and results are plain JSON values: strings, numbers, booleans, arrays and objects. Binary data such as a photo is passed as a base64 string, a data URL or, better, a file path or web-viewable URI, never as a raw object.

  • Calls are matched by id. Several calls can be in flight at once; each result is routed to the promise that made the call.

  • Errors cross the bridge too. A native plugin can reject a call with a message, which surfaces as a rejected promise in TypeScript. Always wrap calls in try and catch.

  • Permission prompts happen in native code. The plugin asks the operating system, and the promise settles after the user answers.

Plugin Registration

A plugin is identified by a name shared by its three parts: the TypeScript definitions, the optional web implementation and the native implementations. In TypeScript, registerPlugin creates the proxy that routes calls:

import { registerPlugin } from '@capacitor/core';

export interface TrailShareOptions {
  trailId: string;
}

export interface TrailSharePlugin {
  share(options: TrailShareOptions): Promise<{ shared: boolean }>;
}

const TrailShare = registerPlugin<TrailSharePlugin>('TrailShare', {
  web: () => import('./web').then((module) => new module.TrailShareWeb()),
});

export { TrailShare };

On startup the native side must also know the plugin. Official plugins installed through npm are discovered by npx cap sync, which lists them in the native project. A custom plugin kept inside the app project is registered explicitly in the native activity or view controller; the full walkthrough is on Capacitor Plugins.

The lookup at call time follows a fixed order:

  1. If the app runs on a native platform and a native implementation with that name exists, the call goes across the bridge.

  2. Otherwise, if a web implementation was provided to registerPlugin, it is used. This is why the Camera plugin shows a file picker and Geolocation uses the browser API under ionic serve.

  3. Otherwise the call rejects with an "unimplemented" error.

Capacitor.isNativePlatform() and Capacitor.getPlatform() (returning 'web', 'ios' or 'android') let application code branch when behaviour must really differ:

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

export function supportsBackgroundSync(): boolean {
  return Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android';
}

The Local Server Scheme

The web assets are not loaded from the file system with a file:// address. Capacitor serves them from a local scheme and host, so the page has a stable origin like a real website:

Platform Origin Notes

iOS

capacitor://localhost

A custom scheme handled inside the app. It is not reachable from other apps or from the network.

Android

https://localhost

A virtual HTTPS origin answered by the app itself. It is not a real network server.

Browser

http://localhost:8100

The dev server used by ionic serve.

The origin matters because browsers apply the same-origin policy to everything the page does:

  • CORS. A request from capacitor://localhost or https://localhost to https://api.example.com/v1/trails is cross-origin, so the API must answer with a matching Access-Control-Allow-Origin header and handle preflight requests, or the WebView blocks the response. The browser origin and the two native origins are three different values to allow. The backend side of this is covered on Data, Storage and Networking.

  • Cookies. Cookies set by the API are third-party cookies from the page’s point of view, and WebViews restrict them. Prefer token-based authentication stored with the Preferences plugin or secure storage over cookie sessions.

  • Mixed content. Android’s https://localhost origin means requests to plain http:// addresses are blocked unless explicitly allowed; use HTTPS for every API.

  • Storage scope. localStorage and IndexedDB are tied to the origin. Changing the scheme or hostname in configuration makes the app lose previously stored data, and the operating system can evict WebView storage under pressure, so persistent data belongs in a native-backed store.

Capacitor can also route fetch and XMLHttpRequest through native HTTP code, which avoids CORS entirely. This is enabled with the CapacitorHttp plugin in capacitor.config.ts:

import type { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.example.trailhead',
  appName: 'trailhead',
  webDir: 'www',
  plugins: {
    CapacitorHttp: {
      enabled: true,
    },
  },
};

export default config;

Native HTTP removes browser CORS checks but also behaves differently from the browser in the details of cookies and streaming, so it is a deliberate decision, not a default. Fixing the server’s CORS configuration is usually the cleaner answer, because it keeps ionic serve and the device behaving the same way.

The Native Projects Are Source Code

Capacitor does not regenerate the android/ and ios/ folders on every build. They are the source of truth for everything native and are committed to git:

  • permissions and usage descriptions (AndroidManifest.xml, Info.plist);

  • application id, version code and name, icons, splash resources and signing settings;

  • custom Kotlin and Swift plugins and extra native dependencies;

  • Gradle and Swift Package Manager or CocoaPods configuration.

What is generated and ignored by git are the copied web assets inside the native projects and build outputs. Run npx cap sync to refresh them from the web build. Because the native files are hand-editable, a native upgrade is a deliberate step: npx cap migrate applies the version bump and shows what else to change. The iOS project uses Swift Package Manager by default in new Capacitor 8 projects; selecting CocoaPods is a flag at creation time. Edge-to-edge display on Android is handled in the web layer with CSS env() safe-area variables and the System Bars core plugin, covered on Components and Theming.

Cordova Compatibility and Migration

Capacitor grew out of the same ideas as Apache Cordova, and the two share a WebView-plus-plugins model. The differences matter when migrating an older app:

Topic Cordova Capacitor

Native projects

Generated and treated as build output

Committed source code

Plugin API

cordova.exec with callbacks

Typed promise-based plugins

Configuration

config.xml and hooks

capacitor.config.ts and normal native editing

Tooling

Cordova CLI

Capacitor CLI, Android Studio and Xcode

Capacitor can run many Cordova plugins through its compatibility layer: npx cap sync detects Cordova plugins in package.json and links them into the native projects. A migration usually follows these steps: add Capacitor to the existing web project, replace Cordova plugins that have an official Capacitor equivalent (Camera, Geolocation, File and Network all do), keep the remaining ones through the compatibility layer, and then retire config.xml. Prefer a maintained Capacitor plugin over a Cordova one whenever there is a choice.

Debugging Across the Layers

Symptom Where to look

Layout, CSS or Angular error

The WebView inspector (Safari Web Inspector or chrome://inspect).

Plugin rejects or "not implemented"

The JavaScript console first, then Logcat (Android) or the Xcode console (iOS).

Native crash or Gradle failure

Android Studio Logcat and Build output, or Xcode’s crash log.

Request blocked by CORS

The WebView network tab, then the API’s response headers.