Skip to content
Valence is in beta. The bundle format and update protocol are meant to stay stable; the CLI, the generated code and the two runtime packages’ APIs may still change. What beta means

Your own backend

For an online action, http.request calls your existing API from the native host without the WebView’s CORS restrictions. To keep selected responses offline, revision-18 REST caching adds disposable SQLite overlays behind compiled bucket grants. For server-managed offline datasets and queued user edits, use an adapter that translates your API into Valence’s sync protocol.

Add only API origins you control to valence/valence.config.json:

{ "http": { "origins": ["https://api.example.com"] } }

Merge this into the existing config. Regenerate with node valence/valence.mjs codegen, then ship a new store build. This list compiles into ValenceConfig.httpOrigins; changing only an OTA bundle’s CSP cannot authorize a new native HTTP destination. Empty means deny all, and sync.base does not implicitly grant access. Use exact origins: no paths, credentials or wildcards.

http.request is new at since: 4; version 3 includes data.getMany and sync.status. Existing apps add the method and type below to their schema at a since above their shipped version (raise the schema version to match), regenerate, and ship a host. Preserve all older entries.

{
"methods": {
"http.request": {
"since": 4,
"params": { "url": "string", "method": "string?", "headers": "json?", "body": "string?" },
"returns": "HttpResponse"
}
},
"types": { "HttpResponse": { "status": "int", "headers": "json", "body": "string" } }
}
import { call, connect, has } from '#lib/valence/bridge.g';
await connect();
if (has('http.request')) {
const response = await call('http.request', {
url: 'https://api.example.com/chart',
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ place: 'Pokhara' }),
});
if (response.status === 200) {
const chart = JSON.parse(response.body);
// Render chart in this app's UI.
}
}

The host reads the token stored by auth.setToken for each request and sets Authorization: Bearer itself. A Dart ValenceConfig.authToken callback takes precedence, just as it does for sync. The page cannot supply Authorization, cookies, Origin, Host, transport headers, Proxy-* or Sec-* — nor, when a cookie jar is configured, the CSRF header it mirrors. Do not put a shared server secret in a web bundle or APK: native HTTP does not make that secret safe. Use user tokens and keep service credentials on your server. Every allowed origin is trusted with the user token; an API that reflects credentials in its response can disclose them to the page.

Behavior Result
Method omitted GET; also supports HEAD, POST, PUT, PATCH, DELETE and OPTIONS
GET/HEAD body, malformed URL or headers E_PARAMS
Origin absent from the compiled allowlist, forbidden header E_DENIED
HTTP error status Returned as {status, headers, body}, including 401 and 500
Redirect Returned as 3xx, never followed, even to the same origin
401 with a host bearer token Also emits auth.expired once per request; retains the token
Text body Strict UTF-8; JSON must be stringified by the caller
Request body above 64 KiB, decompressed response above compiled http.maxBodyBytes (default 64 KiB), headers above 16 KiB E_TOO_LARGE, naming the observed size and the limit
20-second total deadline E_TIMEOUT
Network failure while the device reports no network interface E_OFFLINE
Any other network failure, or invalid UTF-8 E_INTERNAL with no credential or remote exception text

E_OFFLINE is the one failure worth a different UI: nothing was reachable, so the honest screen is silence rather than an apology. It is read from the same value app.online reports, at the moment the request failed, so you do not have to sample app.state() separately and hope the two agree. It is not reachability — a captive portal, a firewall or a server that is down is E_INTERNAL, because the host sees network interfaces and cannot tell those apart.

For larger responses, configure compiled http.maxBodyBytes (1..262144), regenerate and ship a store build. See Response size grants. To read less, send a Range header. It is not on the forbidden list, and a 206 comes back as an ordinary response. There is no streaming form, so an API that only offers one representation exceeding the compiled body grant or escaped bridge envelope and does not support Range needs server pagination or a native plugin.

Set-Cookie headers are omitted from what your page receives, always. The usual 262144-byte encoded bridge cap still applies, including JSON escaping. This method is for bounded text RPC, not binary downloads or multipart uploads. It does not queue, retry, populate SQLite or work offline.

Section titled “A session-cookie API needs the cookie jar, and it is off by default”

With no jar configured, a cookie-paired CSRF token cannot be completed, so an endpoint that requires one is unreachable from a Valence page. The host can send neither half of the pair: not the cookie, since a page that can set one could forge it for the origin trusted with your bearer token, and not the matching header, since getting that token means a prior GET whose Set-Cookie is also discarded.

That is the default shape of a Django POST (csrftoken cookie plus X-CSRFToken) and of the Rails equivalent — two of the most widely deployed server frameworks — so it is worth a minute while you are choosing the API rather than after you have shipped against it. A bearer-token or header-key API, or an endpoint marked csrf_exempt, needs nothing below.

The opt-in: one origin, a host-held jar your page never sees.

"http": {
"origins": ["https://api.example.com"],
"cookieJar": {
"origin": "https://api.example.com",
"csrf": { "cookie": "csrftoken", "header": "X-CSRFToken" }
}
}

The host then replays that origin’s cookies on every request to it, and sets X-CSRFToken from the csrftoken cookie it holds. Your page is unchanged: it still cannot read a cookie, set one, or send one anywhere. Cookie stays on the forbidden list, and so does the mirrored header — a value your page chose would not match the cookie the server is about to compare it with, so supplying it is E_DENIED. Drop csrf if your API only needs a session cookie replayed.

Four rules, all of them refusals at codegen rather than warnings, because each one is configuration that looks like it works and does not:

  • The origin must also be in http.origins. A jar for an origin http.request cannot reach never fills.
  • One origin. Not a list. A jar is a credential store.
  • HTTPS, except loopback. 127.0.0.1, [::1] and localhost may be cleartext for local testing; anything else must be HTTPS, because a jar replays a credential on every request rather than on a grant you make per call.
  • The mirrored header cannot be one the host already sets — Authorization, Cookie, Sec-* and the rest of the forbidden list.

valence doctor has a cookie jar row that prints the configured origin and the pair, so “is the jar on?” is answerable without reading generated Dart.

What the jar does with a cookie. It is host-only: a Domain that is not exactly your host is dropped, so a cookie can never reach a sibling subdomain. Path is matched the way a browser matches it, for the mirrored header as well as for Cookie — but the jar holds one cookie per name, not one per name and path, so a second Set-Cookie for the same name replaces the first whatever its Path. Max-Age wins over Expires, and a Max-Age of zero deletes. A Secure cookie is dropped rather than downgraded when the jar origin is the cleartext loopback one. A cookie with no expiry is a session cookie and lives in memory only by default. A compiled sessionCookieDays of 1–30 opts into a fixed lifetime from receipt; see Keep an API session across restarts. One with an expiry is kept in the same Keystore/Keychain storage as your bearer token, where nothing can read it back. The jar holds at most 16 cookies, 4096 bytes each, 8 KiB in total; a cookie over a cap is dropped and logged, and the request still succeeds, because a server’s Set-Cookie is not your page’s mistake.

When it is cleared. Signing the user out clears the jar in the same step: auth.setToken(null) — including the sign-out of an app that never passed an account and therefore clears no rows — and an account switch. A token refresh for the same account clears nothing, exactly as it moves no row, and neither does auth.setToken({token: ''}), which is not a sign-out. The clear runs before the token is written, so a device whose Keystore cannot delete the jar fails the sign-out with the user still signed in, rather than leaving their session cookie behind for whoever signs in next. It survives an OTA update, deliberately: the jar’s origin is compiled into the native build, no manifest can change it, and signing a user out of their session for a UI update would cost something and protect nothing. If you drop cookieJar from a later store build, or point it somewhere else, the old origin’s cookies are revoked on the next launch.

One thing the jar does not change: your page could already make the host send the user’s bearer token to this origin, and it can now make the host send the user’s cookies to the same origin. What it still cannot do is read either, set either, or aim either anywhere else.

Use HTTPS in production. Explicit HTTP origins can send tokens in cleartext in release builds too. Android’s loopback-only network security XML does not enforce that boundary for native Dart HTTP: a release-device check reached an allowlisted 10.0.2.2 origin with a synthetic bearer token. The compiled http.origins list is the native token trust grant; the debug-only dev proxy is a separate path.

For local Android tests, use http://127.0.0.1:8787 in http.origins and run adb reverse tcp:8787 tcp:8787. The example’s RPC button uses that address. Re-run codegen and rebuild the host after changing the origins; rebuild the signed web bundle if its request URL changes. Remove local test origins from production configs and use HTTPS for remote APIs. A browser shim uses fetch and still needs normal browser CORS permission. Android is tested; iOS is experimental and untested.

Pointing sync.base at an arbitrary REST service does not translate its endpoints. Valence needs the pull and push shapes in Data and sync. Put an adapter on your server when the existing API does not speak that protocol.

The reference Node adapter uses only Node’s standard library and SQLite. It provides one authenticated user’s writable items bucket at schema 1. Your REST API supplies a complete GET /items snapshot and idempotent PUT /items/:id / DELETE /items/:id operations. Its README gives commands and the expected API.

  1. Compare a complete REST snapshot with durable rows. Assign monotonically increasing USNs only for changes; retain removed keys as tombstones. Never infer deletions from a partial snapshot.
  2. Return rows ordered by USN. When more is true, max must be the last row included, so the next request cannot skip the rest. Unknown schemas return 404, not an empty successful page.
  3. Forward pushes using the operation id as the upstream idempotency key. Persist the row and id receipt atomically. After a lost reply, a retry must acknowledge without another upstream write and return the current winning row, including any newer writer’s value.
  4. Keep every read-only schema that a live bundle needs. Writable buckets always stay at schema 1.

Keep the adapter database: deleting it loses cursors, tombstones and idempotency history. This example binds to loopback and uses one database for one identity; production must isolate users, authorize rows, terminate TLS and set workload and retention policies. Its operation history deliberately grows until a retention protocol is designed. Upstream APIs that normalize writes need a mapping to their canonical returned values. Requests and snapshots are capped at 1 MiB; pushes accept all operations within that cap, including backlogs above 200. Larger workloads need a paged snapshot and bounded push design. These are application backend decisions.

A POST can succeed on the server while the page receives E_TOO_LARGE or E_INTERNAL, for example when reading a response fails after the server writes. Use server-enforced idempotency keys for retried writes. JSON escaping can expand a 64 KiB text response beyond the 256 KiB bridge cap. HEAD, 204 and 304 ignore representation Content-Length during the pre-check; actual streamed bytes remain bounded.

Keep browser-only maps and analytics in web.connect. They do not receive the host token. Only the separate http.origins list grants native requests and token trust.