@capgo/capacitor-asset-cache

June 26, 2026 ยท View on GitHub

Capgo - Instant updates for Capacitor

Get instant updates for your app with Capgo

Missing a feature? We will build the plugin for you

Transparent persistent media cache for Capacitor images, videos, and other large CDN assets.

Why Asset Cache?

@capgo/capacitor-asset-cache lets app code ask for a media source and bind it directly to an <img>, <video>, React component, Vue template, or any other web UI.

  • Pass a CDN path like videos/intro.mp4 and get a local display-ready URL back.
  • Uses persistent app storage: iOS Application Support and Android internal files.
  • src(...) and resolve(...) only resolve after a local file exists; if the plugin cannot create a local file, the call rejects.
  • bind(...) updates an image or video element from loading to ready when the local file is available.
  • Supports cache-only, TTL, ETag, Last-Modified, and always-revalidate modes.
  • Keeps lower-level get, list, remove, and clear helpers for advanced cache management.

The cache is removed when the app is uninstalled, but it is not stored in the platform cache directory that the system may flush under pressure.

Documentation

The most complete doc is available here: https://capgo.app/docs/plugins/asset-cache/

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*Yes
v7.*.*v7.*.*On demand

Install

npm install @capgo/capacitor-asset-cache
npx cap sync

Usage

Configure the CDN once, then bind media elements to CDN paths. The element only receives the local webview URL after the native fetch is done.

import { AssetCache } from '@capgo/capacitor-asset-cache';

AssetCache.configure({
  cdnUrl: 'https://cdn.example.com/assets/',
  revalidate: {
    strategy: 'ttl',
    maxAgeSeconds: 86400,
  },
});

const video = document.querySelector('video');
if (video) {
  AssetCache.bind(video, 'videos/intro.mp4');
}
video[data-asset-cache-state='loading'],
img[data-asset-cache-state='loading'] {
  opacity: 0.4;
}

video[data-asset-cache-state='ready'],
img[data-asset-cache-state='ready'] {
  opacity: 1;
}

React

import { useEffect, useRef } from 'react';
import { AssetCache } from '@capgo/capacitor-asset-cache';

AssetCache.configure({ cdnUrl: 'https://cdn.example.com/assets/' });

export function HeroImage() {
  const imageRef = useRef<HTMLImageElement>(null);

  useEffect(() => {
    if (!imageRef.current) return;

    const binding = AssetCache.bind(imageRef.current, 'hero.jpg');
    return () => binding.cancel();
  }, []);

  return <img ref={imageRef} alt="" />;
}

Vue

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { AssetCache, type AssetCacheBinding } from '@capgo/capacitor-asset-cache';

const image = ref<HTMLImageElement | null>(null);
let binding: AssetCacheBinding | undefined;

onMounted(() => {
  if (image.value) {
    binding = AssetCache.bind(image.value, 'hero.jpg', {
      cdnUrl: 'https://cdn.example.com/assets/',
    });
  }
});

onUnmounted(() => binding?.cancel());
</script>

<template>
  <img ref="image" alt="" />
</template>

Direct Source

Use src(...) when your framework already manages loading state. It resolves only after the local file is ready.

const src = await AssetCache.src('images/hero.jpg');

Protected Assets

Pass headers to the native fetch. The web element receives only the local file URL returned by the plugin.

const src = await AssetCache.src('private/videos/intro.mp4', {
  cdnUrl: 'https://cdn.example.com/assets/',
  headers: {
    Authorization: `Bearer ${token}`,
  },
});

Inspect the Resolution

Use resolve(...) when you also want metadata about the local file resolution.

const source = await AssetCache.resolve('images/hero.jpg');

console.log(source.src, source.fromCache, source.status);

Advanced Cache Control

Use get(...) directly only when you need the raw native file metadata.

const asset = await AssetCache.get({
  url: 'https://example.com/videos/intro.mp4',
  key: 'intro.mp4',
  revalidate: { strategy: 'etag' },
});

Platform notes

  • iOS stores files under Application Support and excludes the cache root from iCloud backup.
  • Android stores files under the app internal files directory.
  • Web uses the browser Cache API and localStorage metadata as a development fallback.

API

Persistent asset cache for large Capacitor images, videos, and other media.

configure(...)

configure(options: AssetCacheConfigOptions) => void

Set defaults for future src(...), resolve(...), and bind(...) calls.

ParamType
optionsAssetCacheConfigOptions

resolve(...)

resolve(path: AssetCacheSourceInput, options?: AssetCacheSourceOptions | undefined) => Promise<ResolvedAssetSource>

Resolve a CDN path or remote URL into a local display-ready source URL.

ParamType
pathAssetCacheSourceInput
optionsAssetCacheSourceOptions

Returns: Promise<ResolvedAssetSource>


src(...)

src(path: AssetCacheSourceInput, options?: AssetCacheSourceOptions | undefined) => Promise<string>

Resolve a CDN path or remote URL into a local string ready for img.src or video.src.

ParamType
pathAssetCacheSourceInput
optionsAssetCacheSourceOptions

Returns: Promise<string>


bind(...)

bind(element: AssetCacheBindableElement, path: AssetCacheSourceInput, options?: AssetCacheBindOptions | undefined) => AssetCacheBinding

Bind an image or video element to a local asset and update it when ready.

ParamType
elementany
pathAssetCacheSourceInput
optionsAssetCacheBindOptions

Returns: AssetCacheBinding


get(...)

get(options: GetAssetOptions) => Promise<CachedAsset>

Resolve an asset URL into a local persistent file.

ParamType
optionsGetAssetOptions

Returns: Promise<CachedAsset>


remove(...)

remove(options: AssetCacheKeyOptions) => Promise<RemoveAssetResult>

Remove one cached asset by key or URL.

ParamType
optionsAssetCacheKeyOptions

Returns: Promise<RemoveAssetResult>


clear()

clear() => Promise<ClearCacheResult>

Remove every cached asset managed by this plugin.

Returns: Promise<ClearCacheResult>


list()

list() => Promise<AssetCacheListResult>

List cached assets that still exist on disk.

Returns: Promise<AssetCacheListResult>


getCacheSize()

getCacheSize() => Promise<AssetCacheSizeResult>

Return total cached asset bytes.

Returns: Promise<AssetCacheSizeResult>


getPluginVersion()

getPluginVersion() => Promise<PluginVersionResult>

Returns the platform implementation version marker.

Returns: Promise<PluginVersionResult>


Interfaces

AssetCacheConfigOptions

Shared defaults used by AssetCache.src(...) and AssetCache.resolve(...).

PropTypeDescription
cdnUrlstringBase CDN URL used when path is relative.
revalidateAssetCacheRevalidateOptionsDefault revalidation behavior for resolved assets.

AssetCacheRevalidateOptions

Revalidation options for cached assets.

PropTypeDescriptionDefault
strategyAssetCacheRevalidateStrategynever returns the local file when present. ttl re-downloads after maxAgeSeconds. always revalidates on every call and sends known validators. etag and last-modified use the matching HTTP validator when present.'never'
maxAgeSecondsnumberFreshness window in seconds for the ttl strategy.

ResolvedAssetSource

Result returned by AssetCache.resolve(...).

PropTypeDescription
srcstringLocal URL ready to assign to HTMLImageElement.src, HTMLVideoElement.src, or framework bindings.
pathstringOriginal path passed by the caller.
remoteUrlstringFully resolved remote URL used by the native fetch.
keystringStable cache key used when one is known.
localtrueAlways true for successful resolve(...) calls.
fromCachebooleanTrue when the persistent local copy already existed before this call.
status'hit' | 'downloaded' | 'notModified'Result of the local source resolution.
assetCachedAssetNative cached asset payload for the local file.

CachedAsset

A cached asset stored in app-owned persistent storage.

PropTypeDescription
keystringStable cache key used by the plugin.
urlstringOriginal remote URL.
pathstringAbsolute native filesystem path.
uristringFile URI that can be passed to Capacitor.convertFileSrc.
mimeTypestringBest known MIME type from the HTTP response.
etagstringLast known HTTP ETag validator.
lastModifiedstringLast known HTTP Last-Modified validator.
sizenumberFile size in bytes.
updatedAtnumberUnix timestamp in milliseconds for the last successful download.
checkedAtnumberUnix timestamp in milliseconds for the last cache check.
fromCachebooleanTrue when the returned asset came from local persistent storage.
status'hit' | 'downloaded' | 'notModified'Result of the cache lookup.

ResolveAssetSourceOptions

Input used by AssetCache.src(...) and AssetCache.resolve(...).

PropTypeDescription
pathstringCDN-relative path or absolute remote URL for an image, video, or other media asset.

AssetCacheSourceOptions

Per-asset options used by AssetCache.src(...) and AssetCache.resolve(...).

PropTypeDescription
keystringStable cache key. Include a file extension when the URL path does not have one.
headers{ [key: string]: string; }HTTP headers sent while fetching or revalidating the asset.

AssetCacheBinding

Binding returned by AssetCache.bind(...).

PropTypeDescription
promisePromise<ResolvedAssetSource>Resolves with the local source metadata after the element is updated.
MethodSignatureDescription
cancel() => voidPrevents this binding from updating the element after it resolves.

AssetCacheBindOptions

Options used by AssetCache.bind(...).

PropTypeDescriptionDefault
stateAttributestringAttribute updated with loading, ready, or error.'data-asset-cache-state'
loadingClassstringClass added while the local file is being fetched.
readyClassstringClass added after the local file is assigned to the element.
errorClassstringClass added when local resolution fails.

GetAssetOptions

Options used to resolve a remote asset into a local persistent file.

PropTypeDescription
urlstringRemote asset URL.
keystringStable cache key. If omitted, the plugin uses a SHA-256 hash of url. Include a file extension when the asset will be used directly in an &lt;img&gt; or &lt;video&gt; tag.
headers{ [key: string]: string; }HTTP headers sent while fetching or revalidating the asset.
revalidateAssetCacheRevalidateOptionsControls when an existing persistent file should be checked again.

RemoveAssetResult

Remove result.

PropTypeDescription
removedbooleanTrue when a cached file or its metadata was removed.

AssetCacheKeyOptions

Identifies an asset by cache key or by URL. key wins when both are set.

PropTypeDescription
keystringStable cache key.
urlstringRemote asset URL used to derive the default key.

ClearCacheResult

Clear result.

PropTypeDescription
removednumberNumber of cached assets removed.

AssetCacheListResult

List result.

PropTypeDescription
assetsCachedAsset[]Cached assets that still have files on disk.

AssetCacheSizeResult

Cache size result.

PropTypeDescription
sizenumberTotal cached asset size in bytes.

PluginVersionResult

Plugin version payload.

PropTypeDescription
versionstringVersion identifier returned by the platform implementation.

Type Aliases

AssetCacheRevalidateStrategy

Revalidation mode used when an asset already exists in persistent storage.

'never' | 'ttl' | 'always' | 'etag' | 'last-modified'

AssetCacheSourceInput

Convenience input accepted by AssetCache.src(...) and AssetCache.resolve(...).

string | ResolveAssetSourceOptions

AssetCacheBindableElement

Element supported by AssetCache.bind(...).

HTMLImageElement | HTMLVideoElement