React Native
permdock/react-native adds a persisted snapshot so Expo Router Stack.Protected and Tabs.Protected guards answer synchronously on the first frame and revalidate in the background.
Purpose
Expo Router's Stack.Protected and Tabs.Protected (SDK 53 and later) take a plain boolean guard. They are evaluated synchronously during the first render, before any network request can complete. permdock/react-native re-exports everything from permdock/react and adds one option, storage, so the last known snapshot is read from device storage on launch, guards answer immediately, and a fresh snapshot is fetched and swapped in without a flash.
Why a persisted snapshot
The guard has no promise, loading state or pending value: when it flips to false the protected screens stop existing and Expo Router moves the user off them. A library that answers usePermission() by calling a server or waiting for a session can only drive it with a splash screen on every cold start or a guard that briefly lies. A snapshot (roles, grants and portable conditions as JSON) persisted on the device answers every guard on the first frame, and because it carries the where conditions, ownership checks such as usePermission(permissions.post.update, post) also work offline without a second copy of the policy in the app. That rules out hooks that suspend or return undefined, boolean-only client state, and a splash screen on every launch; the splash is needed once per install, before the first snapshot arrives.
Stack.Protected and Tabs.Protected decide which screens exist; Protected decides which sections of a screen render, with pending and denied render props. Both read the same snapshot.
| Concern | permdock/next (web) | permdock/react-native (Expo) |
|---|---|---|
| First-frame answer | Snapshot in the prefetched App Shell | Snapshot in device storage |
| What makes it available before render | 'use cache: private' with cacheLife | A synchronous storage.getItem() on launch |
| Refresh trigger | updateTag after a mutation | Fetch on launch, on foreground, or on refresh() |
| Revocation path | SSF receiver invalidates the tag | The revalidate interval; no push without an app channel |
| Closure grants | Batched call to permdockHandler() | Same endpoint; server-only while offline |
Everything above the transport is shared: the snapshot format, the condition evaluator, usePermission's return shape and the decision endpoint.
Set up an Expo app
These steps build a native Expo Router app with tabs that a role hides, a snapshot kept in the device keychain, and a refresh when the app returns to the foreground. apps/examples/expo runs them.
1. Store the snapshot
expo-secure-store has synchronous getItem and setItem, so guards answer on the first frame. Its keys may contain only letters, digits, ., - and _; PermDock writes permdock.snapshot and permdock.tenant. It has no web implementation, so a universal app picks another store on web:
import * as SecureStore from "expo-secure-store";
import {
memorySnapshotStorage,
type SnapshotStorage,
} from "permdock/react-native";
import { Platform } from "react-native";
export const storage: SnapshotStorage =
Platform.OS === "web"
? memorySnapshotStorage()
: {
getItem: (key) => SecureStore.getItem(key),
setItem: (key, value) => {
SecureStore.setItem(key, value);
},
removeItem: async (key) => {
await SecureStore.deleteItemAsync(key);
},
};MMKV is the faster choice when the snapshot need not be encrypted at rest; what it validates lists what a snapshot reveals.
2. Guard the tabs
Tabs.Protected takes a boolean, so the hook runs in a component inside the provider:
import { Tabs } from "expo-router";
import { AppState } from "react-native";
import { PermDockProvider, usePermission } from "permdock/react-native";
const onForeground = (listener: () => void) => {
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") listener();
});
return () => subscription.remove();
};
function AppTabs() {
const billing = usePermission(permissions.billing.manage);
return (
<Tabs>
<Tabs.Screen name="index" />
<Tabs.Protected guard={billing.allowed}>
<Tabs.Screen name="billing" />
</Tabs.Protected>
</Tabs>
);
}
export default function Layout() {
return (
<PermDockProvider
storage={storage}
snapshotUrl="https://api.example.com/permdock/snapshot"
headers={{ authorization: `Bearer ${accessToken}` }}
revalidate="focus"
subscribeForeground={onForeground}
>
<AppTabs />
</PermDockProvider>
);
}Define storage and onForeground outside the component: the provider rebuilds its store when either identity changes. Inline headers, fetch and verifier do not: headers compare by value, and a new token in them rebuilds the store. When the guard turns false, the tab stops existing and Expo Router moves the user to the first allowed route.
3. Refresh on foreground
revalidate: 'focus' with subscribeForeground fetches snapshotUrl on launch and whenever AppState reports active, so a role removed while the app was in the background applies when the user returns. With a local snapshot source, subscribeForeground also re-reads its rows on each return to the foreground.
4. Clear on sign-out
Call usePermDock().clear() before switching user. It removes permdock.snapshot from the keychain and drops every cached decision, so nothing from the previous user is read on the next launch. Pass subjectId as well: a persisted snapshot for another user is then treated as empty storage.
5. Plan for offline
Portable grants, including ownership conditions, answer offline from the stored snapshot. Closure grants report server-only and allowed: false until the device is back online (offline behaviour). A guard that must work offline needs a portable grant.
API
import {
PermDockProvider,
usePermDock,
usePermission,
Protected,
} from "permdock/react-native";
import { permissions } from "@/permissions";
<PermDockProvider
storage={mmkvStorage} // { getItem, setItem, removeItem }, sync or async
endpoint="https://api.example.com/permdock"
snapshotUrl="https://api.example.com/permdock/snapshot"
>
<Stack>
<Stack.Protected guard={usePermission(permissions.admin.access).allowed}>
<Stack.Screen name="admin" />
</Stack.Protected>
</Stack>
</PermDockProvider>;| Option or export | Role |
|---|---|
storage | Any object with getItem, setItem, removeItem (MMKV, expo-secure-store, AsyncStorage). A synchronous store answers on the first render. An asynchronous store reports status: 'pending', with guards false, until its read resolves. |
snapshotUrl | Where to fetch a fresh snapshot after launch and on refresh(). The request carries the app's session token through the headers or fetch option. |
source | A SnapshotSource such as localSnapshot({ manifest, read, subscribe }): the snapshot is built from the device's own rows (Local snapshot). |
endpoint | Same batched decision endpoint as React, for closure grants. |
revalidate | 'launch' (default), 'focus' (also on app foreground when subscribeForeground is set) or a number of seconds. |
subscribeForeground | Optional (listener) => unsubscribe for revalidate: 'focus'. Pass AppState.addEventListener('change', ...) from react-native so the snapshot refreshes when the app returns to the foreground. |
refreshOn | Optional RefreshTrigger[], such as eventSourceRefresh(url), that refetch snapshotUrl on an event; see refresh on events. |
nativeRefresh | nativeRefresh({ supabase, appState, netInfo?, powersync? }), where powersync is { db, connector, manifest?, source? }, returns a RefreshTrigger for refreshOn that follows role and tenant changes: session refresh, PowerSync reconnect, snapshot refresh (role and tenant changes). |
usePermission, usePermDock, Protected | Identical to permdock/react; status gains no new values, stale covers the persisted-but-revalidating case. |
usePermissions, useFilter, useTenant, useMemberships, useRoles, useAssignableRoles, useAssignablePermissions, useApproval, useSubject | Identical to permdock/react (UI). useTenant().switchTo persists the chosen tenant next to the snapshot so the app reopens in the same organisation; a tenant already in the persisted snapshot (tenants: 'all') switches locally and works offline; any other tenant refetches the snapshot with ?tenant=, and a failed refetch (offline, non-2xx, invalid body) keeps the previous tenant and snapshot. Nothing is queued: call switchTo again when the connection returns. |
Request lifecycle
- Launch. The provider reads the persisted snapshot from
storageand validates it, and drops it when its principal is notsubjectId. A valid snapshot answers at once. WithsnapshotUrlorsourceits status isstaleuntil the first revalidation lands, andreadywithout either. - Revalidate. A fetch to
snapshotUrlruns in the background. On success the snapshot is validated, written back tostorageand swapped in through the external store. Asourceread whose content did not change is dropped, so it re-renders nothing; a failed read keeps the current snapshot. - Check.
usePermissionandProtectedbehave exactly as on the web: portable grants answer locally, closure grants go toendpointin batches. - Sign-out or account switch.
subjectIdbecomesnullor another id, or the app callspermdock.clear(). The provider removes the persisted snapshot and tenant and drops every cached endpoint answer, so no grant from the previous user survives on disk.
If storage holds no snapshot for subjectId (first launch), guards receive false, which Expo Router treats as "not allowed" and redirects to the anchor route. The status is pending while an asynchronous read or the first fetch runs. With neither snapshotUrl nor source and nothing stored, it settles on server-only. Apps that need a splash screen until the first snapshot arrives read usePermDock().status.
Offline behaviour
A device with no connectivity keeps answering from the persisted snapshot. Portable grants (including ownership conditions such as authorId equals principal.id, and sqlFunction grants whose twin is portable) work fully offline because the condition and the resource are both on the device. Closure grants cannot be answered offline: the hook reports server-only and allowed: false, and Protected renders fallback. Apps that need a specific permission offline should express it with a portable condition rather than a closure; permdock doctor lists those referenced from React Native code (PD065).
Because the on-device answer is a UI hint, an API request made while offline and replayed later is still checked by the server with the current policy, so a stale local grant can never turn into a successful write.
Local snapshot
An app that syncs its membership and custom-role rows to the device (SQLite, a PowerSync or Electric replica) can build the snapshot from those rows instead of fetching it. The policy stays on the server: localSnapshotManifest(policy) from permdock writes, at build time, the JSON that localSnapshot reads on the device.
import { writeFileSync } from "node:fs";
import { localSnapshotManifest } from "permdock";
import { policy } from "../src/policy";
writeFileSync(
"app/permdock-manifest.json",
JSON.stringify(localSnapshotManifest(policy)),
);import {
localSnapshot,
PermDockProvider,
type LocalSnapshotManifest,
} from "permdock/react-native";
import manifest from "./permdock-manifest.json";
// readMemberships, readCustomRoles and watchTables are the app's own queries over its local database.
const source = localSnapshot({
manifest: manifest as LocalSnapshotManifest, // a JSON import widens `v: 1` to number
read: async () => ({
principal: {
id: userId,
tenant: organizationId,
memberships: await readMemberships(userId), // [{ scope: 'tenant', id: 'acme', roles: ['admin'] }]
attributes: { claims: { team_ids: teamIds } },
},
customRoles: await readCustomRoles(organizationId),
}),
subscribe: (listener) =>
watchTables(["organization_users", "roles"], listener),
});
<PermDockProvider storage={secureStorage} source={source}>
{children}
</PermDockProvider>;read() returns what a MembershipSource and a CustomRoleSource would on the server: the memberships, global roles, plans and custom roles of the signed-in user. attributes carries the principal values conditions read, such as principal.claims.team_ids. On every subscribe call the provider rebuilds the snapshot and persists it to storage. A failed read() keeps the current snapshot.
The local snapshot decides like the server snapshot for the same rows, with these limits:
- A grant on a relation grantee (
relation(job, 'watcher')) isserver-onlyon the device: the relation graph is not in the manifest. - A custom role resolves through tables the server computed per permission, level and included role. An entry the manifest does not know, such as a permission added after the build, grants nothing until the manifest is rebuilt.
useAssignableRoles,useAssignablePermissionsandassignableLevelsanswer for the activetenantfrom the same rows, the wayassignableRoles()andassignablePermissions()do on the server: theassignsgraph or the held grants,manageRoles,orderedLevels, and the tenant's custom roles the subject may hand out. A grant through a relation counts as held but reaches no level, as on the server. Without atenant, the lists are empty.
With snapshotUrl set as well, the latest answer wins: the server snapshot after a revalidation, the local one after the next row change.
PowerSync source
With PowerSync, permdock powersync generate writes the manifest to powersync.manifest and adds permdock_* streams for the rows read needs (PowerSync). powerSyncSource replaces the hand-written read and subscribe: the first get runs every query with db.getAll, and one db.watch per query reports changes. permdock/react-native never imports @powersync/*; the app passes its PowerSyncDatabase.
Why cache per query
Each source keeps its own row cache. Watch callbacks in the same microtask turn produce one notification; the next read refreshes only the queries that fired and combines them with the other cached rows. Watch payloads are not trusted as rows. Concurrent reads share the pending refresh, and a callback during a read forces another read of that query before publishing. Failed reads reject and remain pending for retry; they never return the cached snapshot as a successful refresh.
When the mapped data is unchanged, the source returns the same snapshot object instead of rebuilding grants. Membership expiry still triggers a rebuild on the next read. An explicit pull without a pending watch change rereads every query, so foreground refresh does not depend on callbacks delivered while JavaScript was suspended. Caches are closure-local, never shared between users, tenants or source instances; create a new source when the session changes.
powerSyncSource(db, { manifest, user, tenant?, attributes? }) reads the tables the manifest's rows section names (wire formats): the user's memberships from every membership table and source, the global roles, and the tenant's custom roles with their levels. A row with a null role, or a value in expiresAt or disabledAt, holds no role. tenant is the active tenant and attributes the principal values conditions read, such as { claims: { team_ids } }. A manifest without rows throws a TypeError; run generate with powersync.manifest set.
import {
powerSyncSource,
type LocalSnapshotManifest,
} from "permdock/react-native";
import manifest from "./permdock-manifest.json";
const source = powerSyncSource(db, {
manifest: manifest as LocalSnapshotManifest, // a JSON import widens `v: 1` to number
user: userId,
tenant: tenantId,
attributes: { claims: { team_ids: teamIds } },
});Build the source once per signed-in user and tenant, not on every render. PermDockProvider reconnects when source changes, so a source rebuilt per render runs every db.watch and db.getAll again. Create it where the session changes (the sign-in handler or a session store), or at module scope for a fixed user. In an app built with the React Compiler, a source created in a component from db, userId and tenantId keeps its identity while those values do.
Without the React Compiler, or where the options are rebuilt on every render, create one powerSyncSourceCache(db) beside the database and call cache.source(options) in the component. It answers the same source for the same manifest object and the same user, tenant and attributes content; with queries and read, for the same queries and read objects. Switching tenant answers another source, and switching back answers the first again with its rows cached. Entries live as long as their manifest.
import { powerSyncSourceCache } from "permdock/react-native";
export const sources = powerSyncSourceCache(db);
// In a component:
const source = sources.source({ manifest, user: userId, tenant: tenantId });Pass subscribeForeground={appStateForeground(AppState)} as well. A db.watch reports rows that sync while the app runs; on the return to the foreground the provider reads the tables again, so rows synced while JavaScript was suspended apply at once:
import { AppState } from "react-native";
import { appStateForeground, PermDockProvider } from "permdock/react-native";
const foreground = appStateForeground(AppState);
<PermDockProvider
storage={storage}
source={source}
subjectId={userId}
subscribeForeground={foreground}
>
{children}
</PermDockProvider>;For tables the manifest does not describe, pass queries and read instead:
import {
powerSyncSource,
type LocalSnapshotManifest,
} from "permdock/react-native";
import manifest from "./permdock-manifest.json";
const source = powerSyncSource(db, {
manifest: manifest as LocalSnapshotManifest,
queries: {
memberships: {
sql: "SELECT organization_id, tier FROM organization_users WHERE user_id = ?",
parameters: [userId],
},
},
read: ({ memberships }) => ({
principal: {
id: userId,
tenant: organizationId,
memberships: memberships.map((row) => ({
tenant: row.organization_id,
roles: [row.tier],
})),
},
}),
});Role and tenant changes
A role or tenant change on the server takes four steps to reach the device:
- The
authz:<uid>message arrives. - The app refreshes the Supabase session, so the token carries the new claims.
- The app reconnects PowerSync, because a stream that reads a token claim keeps the claims it connected with. PD084 lists those streams.
store.refresh()re-reads the rows.
nativeRefresh runs these steps as a refreshOn trigger. The Supabase token hook bumps permdock_authz_version and broadcasts changed on the user's private authz:<uid> topic.
import { AppState } from "react-native";
import NetInfo from "@react-native-community/netinfo";
import {
appStateForeground,
nativeRefresh,
PermDockProvider,
type LocalSnapshotManifest,
} from "permdock/react-native";
import manifest from "./permdock-manifest.json";
const refreshOn = [
nativeRefresh({
supabase,
appState: AppState,
netInfo: NetInfo,
powersync: { db, connector, manifest: manifest as LocalSnapshotManifest },
}),
];
<PermDockProvider
storage={storage}
source={source}
subjectId={userId}
subscribeForeground={appStateForeground(AppState)}
refreshOn={refreshOn}
>
{children}
</PermDockProvider>;Each pass runs auth.refreshSession(), then db.disconnect() and db.connect(connector), then the snapshot refresh. Passes run one at a time. Signals during a pass run one more pass, and a signal while NetInfo reports offline waits for the connection. A failed session refresh still refreshes the snapshot, and the next signal retries the session.
The channel closes when the app moves to the background and rejoins on the return to the foreground. A message sent in between is lost, so the return runs a catch-up:
- With
powersync.manifestfrompermdock powersync generate, the catch-up runs a pass only when the device'spermdock_authz_versionrow is above the token'sauthz_ver.generatenames that table in the manifest and does not add a stream for it: sync the hook table yourself. The same check runs whenever the row changes, which covers a message sent while the app was closed.powerSyncSourcesets the synced version assnapshot.authzVersion. - With
powersync.source, the catch-up reads the version through the source'sauthzVersion()instead of its own query. Pass the source the provider reads, so both see the same user. The check on each sync still needsmanifest. - Without either, every return to the foreground runs a full pass.
powerSyncSource(db, { manifest, user }) answers authzVersion(): the user's synced version from manifest.rows.version, or undefined before the row syncs, without user, or without that table in the manifest.
const source = sources.source({ manifest, user: userId, tenant: tenantId });
const refreshOn = [
nativeRefresh({
supabase,
appState: AppState,
netInfo: NetInfo,
powersync: { db, connector, manifest, source },
}),
];A tenant switch is a new source (and PermDockProvider reconnects to it); build refreshOn from the same source so the catch-up reads the user the provider shows. On sign-out, call usePermDock().clear() before the next user's source is built (clear on sign-out).
nativeRefresh takes the supabase-js client, the PowerSyncDatabase and the connector structurally and never imports @supabase/* or @powersync/*. It reads authz_ver from the access token without verifying it; the value only decides whether to refresh.
What it validates
- The persisted snapshot against the snapshot v2 schema before use. A snapshot written by an older app version, a v1 snapshot included, fails validation and is discarded and refetched rather than trusted.
- The snapshot's principal id against
subjectId, which the provider requires (nullwhen signed out). A mismatch clears the stored snapshot and tenant, and is treated as empty storage. - Nothing else client-side. As on the web, on-device answers are UI hints; every mutation is re-checked by the API.
The snapshot is stored as the storage implementation stores it. The entry ships only memorySnapshotStorage and the three-method interface; an app that wants the snapshot encrypted at rest (it reveals role names, condition shapes and, with tenants: 'all', every organisation the user belongs to, but no rows) passes expo-secure-store or an encrypted MMKV instance. testSnapshotStorage(storage) from permdock/testing checks a custom storage. Memberships whose expiresAt has passed are ignored by the evaluator at read time. A persisted snapshot keeps serving grants that the server has since removed until the next revalidation; the threat model accepts this for UI hints because every mutation is re-checked server-side.
How denials surface
- Guards receive
false, including whilestatusispendingon a cold start with empty storage, so aTabs.Protectedtab is hidden until the first snapshot arrives; Expo Router redirects to the nearest allowed route. Because the answer comes from storage there is no denied-then-allowed flash after launch. Protectedrendersdenied, and thedecisionis available for an "approval required" screen.- Persisted grants are stale by design until revalidation finishes. A role downgrade takes effect on the next successful fetch; for immediate revocation the API should reject the mutation and the app can call
refresh(), or a Shared Signals receiver on the server can rotate the snapshot.
Example app
apps/examples/expo: an Expo Router app with expo-secure-store storage (memorySnapshotStorage on web), a localSnapshot over in-memory rows that stand in for a sync engine, an AppState foreground listener, Tabs.Protected and Protected. pnpm gen writes src/permdock-manifest.json from the policy; the app bundle never imports the policy. http://127.0.0.1:3486/ shows edit, locked for publish and one tab; "Sync admin role" changes the row, and publish and the Publish tab appear with no request.
Related standards
Last updated on
React
permdock/react gives client components a snapshot-backed PermDock through PermDockProvider, usePermDock, usePermission, usePermissions, useFilter, useTenant, useMemberships, useRoles, useAssignableRoles, useAssignablePermissions, useApproval, useSubject and Protected, with a batched decision endpoint for closure grants.
Vue
permdock/vue maps the snapshot-backed provider, hook and guard from the React adapter onto a Vue plugin, composables and a component.