CHRToffline
Render official ENC charts on a device with no network connection. Download once over Wi-Fi, render forever from a local MBTiles file, refresh the license with periodic heartbeats.
Overview
CHRToffline serves the same official ENC data the online API does, packaged as a single MBTiles file per region. Customers download the bundle while connected, then their app renders charts locally — useful for marine, aviation, defence, and other use-cases where connectivity is spotty or expensive.
When to use the offline path: the device may be away from network for hours-to-days; you want predictable rendering performance with no per-tile latency; or you're shipping into an environment (ship, aircraft, remote vehicle) where connectivity isn't guaranteed.
When to stay online: rendering happens in a browser on a desk; you only need a fraction of a region; or storage on the device is tight (a typical region MBTiles is 200–500 MB).
CHRToffline is for situational awareness, not primary navigation. CHRT is not an ECDIS and is not SOLAS-compliant.
CHRToffline requires the Pro plan or above. The entitlement is enforced server-side at mint time: keys on Free or Dev get a 403 with { "code": "offline_requires_pro_plan", "plan": "free" } from POST /v1/mint/offline-token — step 1 below. The per-key offline:download scope is a separate, narrower switch: a Pro key still needs that scope, and requesting it on an unentitled plan is refused at key-creation time. See Error Codes and Plans.
How it works
- Mint — your app calls
POST /v1/mint/offline-tokenwith your API key and a stable per-install device ID. Returns a short-lived ES256 JWT scoped tooffline:download, plus anoffline_untilgrace timestamp (60 days out). - Bundle — call
GET /v1/offline/bundles/{region}with the JWT. Returns a 15-minute presigned R2 URL pointing at the consolidated MBTiles, plusbytesandsha256. - Download — your app fetches the MBTiles directly from R2. No worker egress; the bytes go straight from R2 to the device. Verify SHA-256 before use.
- Style — call
GET /v1/offline/styles/{region}?palette=DAY&protocol=mbtiles. Returns a MapLibre style JSON ready to hand to MLN — sources already point at the localmbtiles://URL. Cache it next to the MBTiles so you can render offline at next launch. - Render — open the cached style with MapLibre Native (iOS/Android) or MapLibre GL JS (web/desktop). Source URLs resolve against the local MBTiles file.
- Heartbeat — every 24 hours while online, call
POST /v1/offline/heartbeatwith the device ID, regions, and total bytes on disk. Refreshesoffline_untilby 60 days. A device that stops heartbeating loses rendering at the 60-day mark even if the MBTiles file is still present.
iOS integration guide
The reference implementation lives at tools/demo-ios/ in the CHRT monorepo. Single-screen UIKit app with three buttons (Download / Heartbeat / Remove) and an MLN MapView. Below are the key code paths — copy verbatim and adapt to your app's networking conventions.
1. Generate a stable device ID
static let deviceId: String = {
let key = "yourapp.device_id"
if let existing = UserDefaults.standard.string(forKey: key) {
return existing
}
let new = UUID().uuidString
UserDefaults.standard.set(new, forKey: key)
return new
}()2. Mint an offline token
var req = URLRequest(url: mintTokenURL) // .../functions/v1/mint-offline-token
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue(apiKey, forHTTPHeaderField: "x-api-key")
req.httpBody = try JSONSerialization.data(withJSONObject: [
"device_id": Self.deviceId,
"regions": ["NOAA_ENC"],
])
let (data, _) = try await URLSession.shared.data(for: req)
let token = try JSONDecoder().decode(MintTokenResponse.self, from: data).token3. Fetch bundle metadata + download MBTiles
var req = URLRequest(url: apiBaseURL.appendingPathComponent("offline/bundles/NOAA_ENC"))
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (data, _) = try await URLSession.shared.data(for: req)
let bundle = try JSONDecoder().decode(BundleResponse.self, from: data)
// bundle.signed_url, bundle.bytes, bundle.sha256
let (tempURL, _) = try await URLSession.shared.download(
from: URL(string: bundle.signed_url)!
)
// Verify SHA-256 with CryptoKit before moving into place.4. Verify SHA-256
import CryptoKit
let handle = try FileHandle(forReadingFrom: tempURL)
defer { try? handle.close() }
var hasher = SHA256()
while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty {
hasher.update(data: chunk)
}
let computed = hasher.finalize()
.map { String(format: "%02x", $0) }
.joined()
guard computed == bundle.sha256.lowercased() else {
throw OfflineError.sha256Mismatch
}5. Fetch the offline style
var req = URLRequest(url: apiBaseURL
.appendingPathComponent("offline/styles/NOAA_ENC")
.appending(queryItems: [
URLQueryItem(name: "palette", value: "DAY"),
URLQueryItem(name: "protocol", value: "mbtiles"),
]))
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (styleData, _) = try await URLSession.shared.data(for: req)
// styleData is the wrapper { region, palette, protocol, build_id, style: {...}, ... }
// Persist styleData alongside the MBTiles for offline reopens.
try styleData.write(to: cachedStyleURL, options: .atomic)6. Hand the style to MapLibre Native
import MapLibre
let envelope = try Data(contentsOf: cachedStyleURL)
let json = try JSONSerialization.jsonObject(with: envelope) as! [String: Any]
var style = json["style"] as! [String: Any]
var sources = style["sources"] as! [String: Any]
var src = sources["NOAA_ENC"] as! [String: Any]
src["tiles"] = ["mbtiles://\(localMBTilesURL.path)"]
sources["NOAA_ENC"] = src
style["sources"] = sources
let resolved = try JSONSerialization.data(withJSONObject: style)
let tmp = FileManager.default.temporaryDirectory
.appendingPathComponent("NOAA_ENC.resolved.style.json")
try resolved.write(to: tmp)
mapView.styleURL = tmp7. Heartbeat (every 24 h while online)
var req = URLRequest(url: apiBaseURL.appendingPathComponent("offline/heartbeat"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
req.httpBody = try JSONSerialization.data(withJSONObject: [
"device_id": Self.deviceId,
"regions": ["NOAA_ENC"],
"total_bytes": Int(localMBTilesSize),
"platform": "ios",
])
_ = try await URLSession.shared.data(for: req)JS / TypeScript integration
The @chrtco/sdk wraps the entire flow above. Use it in Node, Bun, or any runtime with a filesystem.
import { Chrt } from '@chrtco/sdk';
import { nodeFileSystemAdapter } from '@chrtco/sdk/node';
const chrt = new Chrt({
apiKey: process.env.CHRT_API_KEY!,
deviceId: 'persisted-uuid-v4',
manifestPath: '/var/lib/myapp/chrt-manifest.json',
});
const fs = nodeFileSystemAdapter();
// Set a storage budget (optional — enforced at the start of each download)
await chrt.offline.setStorageBudget(2 * 1024 * 1024 * 1024, fs);
// Download
const result = await chrt.offline.download('NOAA_ENC', {
path: '/var/lib/myapp/NOAA_ENC.mbtiles',
fs,
onProgress: (p) => console.log(`${(p.fraction * 100).toFixed(1)}%`),
});
// Get the offline style — pre-baked by the worker
const styleEnvelope = await chrt.offline.fetchStyle('NOAA_ENC', { palette: 'DAY' });
// → { region, palette, protocol, style: <MapLibre style>, offline_until, ... }
// OR generate it locally from an online style (if you have the atlas available)
import { buildOfflineStyle } from '@chrtco/sdk';
const offlineStyle = buildOfflineStyle(myOnlineStyle, '/var/lib/myapp/NOAA_ENC.mbtiles', {
platform: 'desktop',
});
// Heartbeat every 24h
await chrt.offline.heartbeat({ fs });Android integration guide
A first-party Android demo is on the roadmap. The flow is identical to iOS — substitute Kotlin/Java HTTP clients for URLSession, java.security.MessageDigest for CryptoKit, and the MapLibre Native Android SDK for MLN. The protocol=mbtiles URL scheme works identically.
PRs welcome — fork the demo iOS app's structure into tools/demo-android/.
Desktop integration guide
For Electron, Tauri, native macOS/Linux/Windows apps, or browser PWAs with the File System Access API: use the JS SDK's offline.download() with a filesystem adapter, then call offline.fetchStyle(region, { protocol: 'file' }) to get a style with file:// source URLs.
MapLibre GL JS supports custom protocols — wire one to read MBTiles via better-sqlite3 on Node/Electron, or sql.js in pure browsers.
Managing storage
The JS SDK tracks downloaded regions in a manifest file you point it at via ChrtConfig.manifestPath. With the manifest configured, you can enforce a budget:
// Enforce a 2 GB cap. Refuses new downloads that would exceed it.
await chrt.offline.setStorageBudget(2 * 1024 * 1024 * 1024, fs);
// Drop a region (file + manifest entry + heartbeat update)
await chrt.offline.remove('NOAA_ENC', {
path: '/var/lib/myapp/NOAA_ENC.mbtiles',
fs,
});The budget is advisory — setting it smaller than current usage doesn't auto-prune. Customer code calls remove() to free space. iOS/Android apps following the demo pattern enforce per-region size at the API key level via the platform's api_keys.offline_storage_budget_bytes.
Heartbeat semantics
The heartbeat is a renewal handshake, not a usage metric. Each successful response refreshes the device's offline_until by 60 days. A device that stops heartbeating loses rendering at the 60-day mark even if the MBTiles file is still on disk — this is the licensing spine.
Cadence: every 24 hours while the device has connectivity. Apps should call once at launch (if more than 24 h since last heartbeat) and on a background timer when running.
Failure handling: a failed heartbeat (network down, etc.) is fine — keep using the device. The cached offline_until from the last successful call governs rendering. If wall-clock time exceeds it, the SDK refuses to render. Customer flow: surface a "reconnect to refresh license" prompt before that window closes.
Reference
For situational awareness only — not for primary navigation. CHRT is not an ECDIS and is not SOLAS-compliant.