Data, Storage and Networking

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 is a web app, so its data layer is a web data layer: Angular’s HttpClient for the network, signals and RxJS for in-memory state, and browser storage APIs for persistence. What changes inside a Capacitor shell is the reliability of those pieces. The WebView enforces CORS, the operating system may evict web storage when the device is short on space, and the device goes offline far more often than a desktop browser tab. This page builds the data layer of Trailhead, the hiking-journal app used throughout this section (REST API at https://api.example.com/v1, app id com.example.trailhead), on Ionic Framework 9.0.10, Capacitor 8.6.0 and Angular 22.2.5, using standalone components and signals.

It assumes the project from Getting Started with Ionic and Capacitor and the plugin basics from Capacitor Plugins. For the Angular side in more depth, see the Angular HttpClient reference and RxJS and async. The overall section starts at Hybrid Apps.

Typed Models

Start with the shapes the API returns. Plain interfaces cost nothing at runtime and give the compiler something to check the rest of the app against.

// src/app/trails/trail.model.ts
export type Difficulty = 'easy' | 'moderate' | 'hard';

export interface Trail {
  id: string;
  name: string;
  lengthKm: number;
  difficulty: Difficulty;
}

export interface NewHike {
  hikedAt: string; // ISO 8601 date
  notes: string;
  latitude: number;
  longitude: number;
}

HttpClient with Functional Interceptors

Angular standalone applications register the HTTP client with provideHttpClient() in the application configuration. Interceptors are plain functions passed to withInterceptors(); they replace the older class-based interceptors for new code.

// src/app/app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideIonicAngular } from '@ionic/angular/standalone';
import { routes } from './app.routes';
import { authInterceptor } from './core/auth.interceptor';
import { baseUrlInterceptor } from './core/base-url.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, withComponentInputBinding()),
    provideIonicAngular(),
    provideHttpClient(withInterceptors([baseUrlInterceptor, authInterceptor])),
  ],
};

Two small interceptors cover the common cross-cutting needs: prefixing relative URLs with the API base and attaching a bearer token.

// src/app/core/base-url.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';

const API_BASE = 'https://api.example.com/v1';

export const baseUrlInterceptor: HttpInterceptorFn = (req, next) =>
  req.url.startsWith('http') ? next(req) : next(req.clone({ url: API_BASE + req.url }));

// src/app/core/auth.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { TokenStore } from './token-store';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(TokenStore).accessToken();
  return token
    ? next(req.clone({ setHeaders: { Authorization: 'Bearer ' + token } }))
    : next(req);
};

A TrailsApi service then exposes typed calls (list(), get(id) and logHike(id, hike, photo)) over HttpClient, and nothing else.

State: Signals First, RxJS Where It Fits

Angular’s HttpClient returns observables, and that is still the right type for a request that can be cancelled, retried or composed. For screen state, signals are simpler: a component reads them synchronously in the template and no subscription needs cleaning up. A conservative split works well in an Ionic app:

  • Keep the HTTP layer returning Observable values.

  • Convert to a signal at the edge with toSignal() from @angular/core/rxjs-interop for read-only data, or keep a writable signal in a store service when the screen also modifies it.

  • Use RxJS operators (debounceTime, switchMap, retry) for the genuinely stream-shaped parts, such as the search box.

// src/app/trails/trails-store.ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { Trail } from './trail.model';
import { TrailsApi } from './trails-api';

@Injectable({ providedIn: 'root' })
export class TrailsStore {
  private readonly api = inject(TrailsApi);

  readonly trails = signal<Trail[]>([]);
  readonly query = signal('');
  readonly loading = signal(false);
  readonly error = signal<string | null>(null);

  readonly visible = computed(() => {
    const q = this.query().trim().toLowerCase();
    return q ? this.trails().filter((t) => t.name.toLowerCase().includes(q)) : this.trails();
  });

  refresh(): void {
    this.loading.set(true);
    this.error.set(null);
    this.api.list().subscribe({
      next: (trails) => {
        this.trails.set(trails);
        this.loading.set(false);
      },
      error: () => {
        this.error.set('Could not load trails');
        this.loading.set(false);
      },
    });
  }
}

Angular also ships experimental-to-stable resource primitives (resource() and rxResource()) that bundle value, loading and error signals for a request. Their API surface has moved between releases, so check the Angular resource guide for the version in your project before adopting them. The hand-written store above uses only long-stable APIs and is trivially replaceable later.

CapacitorHttp and CORS in the WebView

In the browser, the same-origin policy and CORS apply: a page served from http://localhost:8100 calling https://api.example.com needs the server to send matching Access-Control-Allow-Origin headers. A Capacitor app is no different. The WebView loads the app from a local origin (by default https://localhost on Android and capacitor://localhost on iOS), and that origin must be allowed by the API. See CORS for the mechanism itself.

Capacitor includes a core HTTP plugin, CapacitorHttp, that sends requests through the native networking stack instead of the WebView. It sidesteps CORS and can be enabled so that fetch and XMLHttpRequest calls are patched to use it:

// capacitor.config.ts (excerpt)
import type { CapacitorConfig } from '@capacitor/cli';

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

export default config;

Enabling the patch changes how requests are made on a device, so progress events, streaming and some multipart behaviour may differ from the browser. Treat it as an option for APIs you cannot configure, not as a default. The preferable fix is a server that allows the app origins. Always test uploads such as the hike photo on a real device after toggling it. When you need one specific call to go native without patching everything, call CapacitorHttp.get() or CapacitorHttp.post() directly.

Choosing a Storage Mechanism

Mechanism Good for Watch out for

localStorage / sessionStorage

Throwaway UI state during development

Synchronous, small, and may be evicted by the OS; never store secrets

Preferences plugin (@capacitor/preferences 8.0.1)

Small key-value data: settings, flags, last-sync time

Not encrypted; not for large payloads or secrets

IndexedDB

Structured browser data, larger blobs

Same eviction risk as other web storage on a low-storage device

SQLite (@capacitor-community/sqlite)

Relational data, queries, migrations, large offline datasets

Community plugin: check its Capacitor 8 compatibility and pin a version

Filesystem plugin (@capacitor/filesystem 8.1.5)

Photos, exported files, downloaded documents

Paths and permissions differ per platform; pick the directory deliberately

Secure storage (community Keychain/Keystore plugins)

Tokens and credentials

Choose a maintained plugin and verify it supports your Capacitor version

Preferences versus localStorage

Web storage lives in the WebView’s profile. On iOS and Android the operating system can clear it under storage pressure, and uninstalling the app removes it. The Preferences plugin stores values with the native key-value facilities (UserDefaults on iOS, SharedPreferences on Android), which is more durable for small values.

import { Preferences } from '@capacitor/preferences';

await Preferences.set({ key: 'lastSync', value: new Date().toISOString() });
const { value } = await Preferences.get({ key: 'lastSync' });
await Preferences.remove({ key: 'lastSync' });

SQLite and IndexedDB

For a trail catalogue that grows beyond a few hundred records, or that needs filtering by difficulty and length offline, a relational store is a better fit than JSON blobs. @capacitor-community/sqlite wraps native SQLite on iOS and Android; it also offers a web implementation based on sql.js for ionic serve, which needs extra setup. Because the plugin is community-maintained and its version must match your Capacitor major, consult its README before installing. IndexedDB is available everywhere with no plugin and suits moderate structured caches; wrap it with a small library such as idb rather than the raw API.

Filesystem

Use @capacitor/filesystem for files, not for records. A downloaded GPX track or a cached hike photo belongs there:

import { Directory, Encoding, Filesystem } from '@capacitor/filesystem';

await Filesystem.writeFile({
  path: 'tracks/ridge-loop.gpx',
  data: gpxText,
  directory: Directory.Data,
  encoding: Encoding.UTF8,
  recursive: true,
});

Directory.Data is private to the app; Directory.Cache may be purged by the system; documents you intend to share belong in Directory.Documents, with the platform permission rules that implies.

Secrets

Never put refresh tokens in localStorage or Preferences. Use a plugin backed by the iOS Keychain and Android Keystore. Several community and commercial plugins exist; evaluate maintenance status and Capacitor 8 support, then hide the choice behind a TokenStore service so it can be swapped. Keep short-lived access tokens in memory (a signal) and persist only the refresh token.

Offline-First: Cache, Then Network

Trailhead should show the last known trail list immediately and refresh it when the network allows. The pattern is cache-then-network: emit cached data first, then replace it with the fresh response, falling back silently to the cache on failure.

sequenceDiagram participant Page as Trail list page participant Store as TrailsStore participant Cache as Local cache participant Api as REST API Page->>Store: refresh() Store->>Cache: read trails Cache-->>Store: cached trails Store-->>Page: show cached trails Store->>Api: GET /trails alt online and success Api-->>Store: fresh trails Store->>Cache: write trails Store-->>Page: show fresh trails else offline or error Api--xStore: failure Store-->>Page: keep cached trails and show offline hint end

TrailsCache has read() and write() methods that wrap Preferences.get and Preferences.set with the key trails-cache and JSON.parse / JSON.stringify.

In refresh() the store first sets trails from cache.read(), then subscribes to api.list(), replacing the list and calling cache.write() on success and keeping the cached list on error. Preferences is acceptable for a short list; for a larger catalogue move TrailsCache to SQLite without touching the store.

Network Status

@capacitor/network 8.0.1 reports connectivity and fires an event when it changes. Turn it into a signal so templates can react:

// src/app/core/connectivity.ts
import { Injectable, signal } from '@angular/core';
import { Network } from '@capacitor/network';

@Injectable({ providedIn: 'root' })
export class Connectivity {
  readonly online = signal(true);

  constructor() {
    Network.getStatus().then((status) => this.online.set(status.connected));
    Network.addListener('networkStatusChange', (status) => this.online.set(status.connected));
  }
}

A common use is replaying queued work: hikes logged offline are saved locally with a pending flag, and an effect() that watches online posts them when it flips to true. Treat the status as a hint, not a guarantee; connected can be true on a network with no route to the API, so keep the error handling shown above.

Authentication and Token Handling

  • Use the OAuth 2.0 authorization code flow with PKCE through the system browser, not an embedded login form in the WebView, so credentials are never visible to your own JavaScript.

  • Return to the app with a custom URL scheme or a universal/app link (see Platform Integration) and handle it with the @capacitor/app appUrlOpen event.

  • Keep access tokens in memory, the refresh token in secure storage, and clear both on sign-out.

  • Never log tokens; no client secret belongs in the bundle, because anyone can unpack the app.

Next Steps

Test this layer with fakes as shown in Testing; photo handling is covered in Media Optimization. See also Ionic Cheat Sheet, Hybrid Apps: IDEs & Tools and React Native.