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
| 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 |
Capacitor runtime |
The JavaScript |
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.
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
tryandcatch. -
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:
-
If the app runs on a native platform and a native implementation with that name exists, the call goes across the bridge.
-
Otherwise, if a
webimplementation was provided toregisterPlugin, it is used. This is why the Camera plugin shows a file picker and Geolocation uses the browser API underionic serve. -
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 |
|
A custom scheme handled inside the app. It is not reachable from other apps or from the network. |
Android |
A virtual HTTPS origin answered by the app itself. It is not a real network server. |
|
Browser |
The dev server used by |
The origin matters because browsers apply the same-origin policy to everything the page does:
-
CORS. A request from
capacitor://localhostorhttps://localhosttohttps://api.example.com/v1/trailsis cross-origin, so the API must answer with a matchingAccess-Control-Allow-Originheader 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://localhostorigin means requests to plainhttp://addresses are blocked unless explicitly allowed; use HTTPS for every API. -
Storage scope.
localStorageand 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 |
|
Typed promise-based plugins |
Configuration |
|
|
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 |
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. |