@symbo.ls/fetch
v3.14.683
Published
Declarative data fetching for DOMQL with pluggable adapters. Supports caching, stale-while-revalidate, pagination, infinite queries, retry, deduplication, optimistic updates, and more.
Maintainers
Keywords
Readme
@symbo.ls/fetch
Declarative data fetching for DOMQL with pluggable adapters. Supports caching, stale-while-revalidate, pagination, infinite queries, retry, deduplication, optimistic updates, and more.
Setup
Add fetch to config.js — this is the connection/adapter config (distinct from the per-element fetch query declaration; the runtime resolves it onto context.fetch):
// REST
fetch: {
adapter: 'rest',
url: 'https://api.example.com',
headers: { Authorization: 'Bearer token' },
fetchOptions: { credentials: 'include', mode: 'cors' },
auth: {
baseUrl: 'https://api.example.com/auth',
sessionUrl: '/me',
signInUrl: '/login',
signOutUrl: '/logout'
}
}
// Local
fetch: { adapter: 'local', data: { articles: [] }, persist: true }
// The Symbols platform, from a published site (see A published site and the platform SDK)
fetch: { adapter: 'symbols', load: () => import('@symbo.ls/sdk') }
// Custom/registered adapter (see Registering a named adapter)
fetch: { adapter: 'sdk', sdk: getSDK() }
dbis not a config key — it's the local name for the resolved adapter you get fromawait this.getDB()(db.select(...),db.insert(...), …).
The REST adapter ships inside the plugin. The local and symbols adapters are files of their own: an app loads one only when its config names it (adapter: 'local', adapter: 'symbols').
A published site and the platform SDK (adapter: 'symbols')
A site published on the Symbols platform reads and writes platform data — for example a workspace's public booking services — through the platform SDK, for a signed-out visitor:
// config.js
fetch: { adapter: 'symbols', load: () => import('@symbo.ls/sdk') }
// an element
Services: {
state: { services: [] },
fetch: { from: 'publicBookings', params: { workspace: 'ws_…' }, as: 'services', transform: (d) => d.services }
}
// a form
Form: {
tag: 'form',
fetch: { method: 'insert', from: 'publicBookings', on: 'submit', params: { workspace: 'ws_…' } }
}loadis the site's own literalimport()of the SDK. The SDK is a host-registered package: smbls never bundles it and no public CDN serves it. frank publishes the literalimport('@symbo.ls/sdk')as the lazy host-package marker, the page runtime then declares the SDK's file instead of inlining it, and the adapter callsload()on the first query. A page that never runs such a query never downloads the SDK. Write the specifier only there: any other quoted'@symbo.ls/sdk'in the site (copy, a comment, a static import) makes every page inline the whole SDK.- The op mapping is the platform 'sdk' adapter's (the workspace shell's), so a
frommeans the same in the shell and on the site. Every call issdk.execute(from, op, args):select → 'list'with{ filter: params, params, single, limit, offset, order, options, ...params },rpc → 'rpc'(params as is),insert → 'create'with{ payload: data, data, ...params },update → 'update'anddelete → 'remove'(withid/number),upsert → 'upsert',subscribe. Every answer is{ data, error }; a server error comes back aserrorwith the server's code as its message (onFetchErrorgets it). - Anonymous only. The adapter has no
getSession/onAuthStateChange; the SDK it builds keeps tokens in memory (tokenStorage: 'memory'), never reads a stored session, and keeps its own telemetry off (tracking: { enabled: false }). - One SDK per page. The first query loads the SDK, builds it with the page's API base (
window.__SYMBOLS_ENV__.apiUrl, which the page runtime injects; without it the SDK's own channel default) and initializes it once. Every later query reuses it. A failed load is tried again on the next query. - Server renders skip it. The adapter's
setup(options, env)getsenv.serverRender(a context withisolateFetchCache, and @symbo.ls/brender'screateSSRAdapter) and answersnullthere: the query is skipped (no status, noonFetchError), the server never loads the SDK or calls the API, and the browser loads the data. - An SDK the page already holds works too:
{ adapter: 'symbols', sdk }or{ adapter: 'symbols', executor }(sdk.execute's signature). - Why not
adapter: 'sdk': hosts that run the platform's own apps (the workspace shell, standalone apps) register their own'sdk'adapter — the viewer's session — and resolution waits for it (see Registering a named adapter). A built-in of that name would answer a host's first elements before the host's registration. So the site's adapter has its own name.
Declarative fetch
// Minimal
{ state: 'articles', fetch: true }
// With options
{ state: 'articles', fetch: { params: { status: 'published' }, cache: '5m', order: { by: 'created_at', asc: false }, limit: 20 } }
// String shorthand
{ state: 'data', fetch: 'blog_posts' }as — state key mapping
{ state: { articles: [], loading: false }, fetch: { from: 'articles', as: 'articles' } }RPC
{ state: { articles: [] }, fetch: { method: 'rpc', from: 'get_content_rows', params: { p_table: 'articles' }, as: 'articles', cache: '5m' } }transform
{
state: { featured: null, items: [] },
fetch: {
from: 'videos',
transform: (data) => ({
featured: data.find(v => v.is_featured) || data[0],
items: data.filter(v => !v.is_featured)
})
}
}select — data selector
Like TanStack's select, pick or reshape data before it hits state. Runs after cache read and before transform:
{
state: { titles: [] },
fetch: {
from: 'articles',
select: (data) => data.map(a => a.title)
}
}Dynamic params
{
state: { item: null },
fetch: {
method: 'rpc',
from: 'get_content_rows',
params: (el) => ({ p_table: 'articles', p_id: window.location.pathname.split('/').pop() }),
transform: (data) => ({ item: data && data[0] || null })
}
}For an RPC bound to on: 'submit', collected form data is used as the RPC params. Use transformParams to reshape the form data before it's sent:
{
tag: 'form',
fetch: {
method: 'rpc',
from: 'submit_application',
on: 'submit',
transformParams: (formData, el, state) => ({ p_payload: formData })
}
}Array fetch (parallel)
{
state: { articles: [], events: [] },
fetch: [
{ method: 'rpc', from: 'get_content_rows', params: { p_table: 'articles' }, as: 'articles', cache: '5m' },
{ method: 'rpc', from: 'get_content_rows', params: { p_table: 'events' }, as: 'events', cache: '5m' }
]
}Triggers
{ fetch: { from: 'articles' } } // on: 'create' (default)
{ tag: 'form', fetch: { method: 'insert', from: 'contacts', on: 'submit' } } // on: 'submit'
{ fetch: { method: 'delete', from: 'items', params: (el) => ({ id: el.state.itemId }), on: 'click' } }
{ fetch: { from: 'articles', params: (el, s) => ({ title: { ilike: '%' + s.query + '%' } }), on: 'stateChange' } }on: 'stateChange' runs the query when the state it reads changes: the values its params, enabled, skip and page resolve to. It does not run on create, and its own rows landing in state do not run it again. It stops when the element is removed.
A list of triggers. on also takes a list: one config, one params, run on every trigger it names. A list that loads at once and follows its filter is
{ fetch: { from: 'articles', params: (el, s) => ({ kind: s.kind }), on: ['create', 'stateChange'], as: 'rows' } }instead of two configs with the same params (one on: 'create', one on: 'stateChange'). Each trigger in the list does what it does alone. With 'create' in it the config is a create-time query: it mounts its cache entry, refetches on focus, reconnect and refetchInterval, is refetched by an invalidation, and takes a seeded or early answer. 'stateChange' then runs it again when its inputs change (the first values are the ones the create run asked with). With 'submit' or 'click' in it an rpc is an action. A list of one is that trigger; an empty list is 'create'; a trigger named twice counts once.
Enabled / disabled queries
// Boolean
{ fetch: { from: 'profile', enabled: false } }
// Function — resolves at fetch time
{ fetch: { from: 'profile', enabled: (el, state) => !!state.userId } }skip is the inverse alias — skip: true (or a function returning true) suppresses the fetch:
{ fetch: { from: 'profile', skip: (el, state) => !state.userId } }Cache
Default: all queries cache with staleTime: 1m, gcTime: 5m.
cache: true // staleTime 1m, gcTime 5m (default)
cache: false // no caching
cache: '5m' // 5 min stale
cache: 30000 // 30s stale
cache: { stale: '1m', gc: '10m' }
cache: { staleTime: '30s', gcTime: '1h', key: 'custom-key' }Stale-while-revalidate
When cached data exists but is stale, it's served immediately while a background refetch happens. Fresh data replaces it once the refetch completes — no loading spinner for stale data.
Garbage collection
Unused cache entries (no active subscribers) are cleaned up after gcTime (default 5 minutes).
Retry
Failed queries automatically retry with exponential backoff. A write — insert, update, upsert, delete or an rpc action — is sent once unless retry asks for more: a write that failed by timing out may have been applied, and sending it again applies it twice.
What the answer's status says decides whether a try comes again — the result's status (the REST adapter's), else the error's status or statusCode (the SDK's errors), returned or thrown:
| Answer | Sent again |
|--------|------------|
| A network failure, a 5xx, an error with no status | yes — retry times, delay apart |
| 408 | yes — as a 5xx |
| 429 | once, after the server's Retry-After (the delay when there is none); not at all when Retry-After asks for more than 30 s |
| Any other 4xx (400, 401, 403, 404, 409, 422 …) | no — the server read the request and refused it; the same request gets the same answer, so the error reaches onFetchError at once |
The rule holds for an explicit retry count too: a count sets how many times a transient failure is tried again, never a refusal. An adapter's failed result can carry retryAfter: the Retry-After header as the server sent it (seconds or an HTTP date); the REST adapter sets it when the server sends one.
// Default: 3 retries with exponential backoff (1s, 2s, 4s... max 30s)
{ fetch: { from: 'articles' } }
// Disable retry
{ fetch: { from: 'articles', retry: false } }
// Custom count
{ fetch: { from: 'articles', retry: 5 } }
// Full control
{
fetch: {
from: 'articles',
retry: {
count: 3,
delay: (attempt, error) => Math.min(1000 * 2 ** attempt, 30000)
}
}
}Query deduplication
Multiple elements fetching the same query simultaneously share a single network request (the same cache key). If that request fails, every element that shares it gets the error (onFetchError, an error status), not empty rows.
An element takes each answer once per declaration: one state write, one onFetchComplete. A run of its own that shares its request in flight (a window focus while the first answer is still out) does not hand it that answer a second time, and a reply or a failure that comes in after a newer answer of the same key is not taken: no state write, no status change, no callback. A failure does not hold off the rows that come after it. A reply for a key the declaration no longer asks for — its language, params or page moved since, and a newer run asks for the new key — is not taken either: the newer run brings its own answer.
// Both share one request
{ Header: { state: 'user', fetch: { from: 'profile', cache: '5m' } } }
{ Sidebar: { state: 'user', fetch: { from: 'profile', cache: '5m' } } }Refetch on window focus
Stale queries automatically refetch when the user returns to the tab. Enabled by default.
A query whose entry is missing or stale is asked for again when the window gains focus or the tab turns visible. The refetch shares a request already in flight on the query's key, as any query does: a focus while the first answer of a cold load is still on its way sends nothing more, and a stale key that several elements declare is asked for once. A request that started before the key's last invalidation is never shared.
// Disable
{ fetch: { from: 'articles', refetchOnWindowFocus: false } }Refetch on reconnect
Queries refetch when the browser comes back online, fresh cache or not. Enabled by default.
Each key is asked for once per reconnect: several elements that read one key share one request. A request that started before the reconnect is never shared — it went out before the connection dropped, or while offline, and may hang or fail — so the reconnect asks afresh, and so does a query that mounts after it.
// Disable
{ fetch: { from: 'articles', refetchOnReconnect: false } }Polling / refetch interval
Each tick sends a request, also while the cached entry is still fresh.
// Poll every 30 seconds
{ fetch: { from: 'notifications', refetchInterval: 30000 } }
{ fetch: { from: 'notifications', refetchInterval: '30s' } }
// Also poll when tab is in background
{ fetch: { from: 'alerts', refetchInterval: '1m', refetchIntervalInBackground: true } }Focus, reconnect and interval refetches belong to a live page. A server render (brender) binds none of them: its page is markup once the render ends (one cache per render).
Placeholder data
Show temporary data immediately while the real query loads:
{
state: { articles: [] },
fetch: {
from: 'articles',
placeholderData: [] // show empty array instead of undefined while loading
}
}
// Function form
{
fetch: {
from: 'article_detail',
placeholderData: (el, state) => state.articles?.find(a => a.id === state.currentId)
}
}Initial data
Pre-populate the cache (counts as fresh data, won't trigger a refetch until stale):
{
fetch: {
from: 'settings',
initialData: { theme: 'dark', lang: 'en' }
}
}
// Function form
{
fetch: {
from: 'settings',
initialData: () => JSON.parse(localStorage.getItem('settings'))
}
}Keep previous data
Prevent UI flicker during page changes — keep showing current data while the next page loads:
{
state: { items: [], page: 1 },
fetch: {
from: 'articles',
page: (el, s) => s.page,
keepPreviousData: true
}
}Pagination
Offset-based
// Page number — auto-calculates offset from pageSize
{
state: { items: [], currentPage: 1 },
fetch: {
from: 'articles',
page: 1,
pageSize: 20, // default: limit or 20
keepPreviousData: true
}
}
// Manual offset/limit
{
fetch: {
from: 'articles',
page: { offset: 0, limit: 20 }
}
}Cursor-based
{
fetch: {
from: 'articles',
page: { cursor: 'abc123', limit: 20 }
}
}
// Top-level `cursor` is also accepted — passed through to params.cursor
{ fetch: { from: 'articles', cursor: 'abc123' } }Infinite queries
Load pages incrementally with automatic page tracking:
{
state: { items: [] },
fetch: {
from: 'articles',
limit: 20,
infinite: true,
getNextPageParam: (lastPage, allPages) => {
if (lastPage.length < 20) return null // no more pages
return lastPage[lastPage.length - 1].id // cursor
}
}
}Fetching pages
After mount, use the imperative methods exposed on element.__ref:
// In an event handler or callback
el.__ref.fetchNextPage() // loads next page, appends to state
el.__ref.fetchPreviousPage() // loads previous page, prepends to state
// Status
el.__ref.__hasNextPage // boolean
el.__ref.__hasPreviousPage // boolean
el.__ref.__pages // array of page arrays
el.__ref.__nextPageParam // current next cursor
el.__ref.__prevPageParam // current previous cursorEach page is cached under its own key (the cursor is part of it), and the next / previous page is always asked from the network. A first page served from the cache keeps its cursors, so fetchNextPage() goes on from it. A refetch (el.__ref.refetch(), an invalidation) starts the list again from the first page. getNextPageParam receives the last page and all pages, getPreviousPageParam the first page and all pages.
Object answers
An rpc often answers one object per page — { items, total, has_more } — and pages by named arguments. Give infinite an object:
{
state: { list: null },
fetch: {
method: 'rpc',
from: 'list_entries',
params: { p_table: 'articles', p_limit: 24 }, // the first page, sized by you
as: 'list',
infinite: {
rows: 'items', // where an answer keeps its rows: a dot path, or (answer) => rows
param: 'p_offset' // the params name the next step goes in, or (step, params) => params
},
getNextPageParam: (lastPage, allPages) =>
lastPage.has_more ? allPages.reduce((n, page) => n + page.items.length, 0) : null
}
}rows: the pages' rows add up in order. The state takes the last answer with that path holding every row so far (state.list.itemsgrows,state.list.totalstays). With a functionrows, the state takes the rows alone.merge(pages, el, state): the value the state takes, built from every answer so far. It wins overrows.param: where the next / previous step goes. A string names one params key; a function returns the whole params of that page, e.g.(step, params) => ({ ...params, p_offset: step, p_limit: 12 })for later pages of another size. Without it, the step goes inparams.cursor.getNextPageParam/getPreviousPageParamreceive whole answers.
fetchNextPage() / fetchPreviousPage() page the element's infinite config, wherever it is in its fetch list, so a search config (on: 'stateChange') can come first.
Bidirectional infinite scroll
{
fetch: {
from: 'messages',
infinite: true,
getNextPageParam: (lastPage) => lastPage[lastPage.length - 1]?.id,
getPreviousPageParam: (firstPage) => firstPage[0]?.id
}
}Mutations
Mutations (insert, update, upsert, delete) support optimistic updates, cache invalidation, and lifecycle callbacks.
{ tag: 'form', fetch: { method: 'insert', from: 'articles', on: 'submit', fields: true } }
{ tag: 'form', fetch: { method: 'insert', from: 'contacts', on: 'submit', fields: ['name', 'email'] } }Optimistic updates
Update the UI immediately, roll back if the mutation fails:
{
extends: 'Button',
text: 'Like',
fetch: {
method: 'update',
from: 'posts',
params: (el) => ({ id: el.state.postId }),
on: 'click',
optimistic: (mutationData, currentState) => ({
...currentState,
likes: currentState.likes + 1
}),
invalidates: ['posts']
}
}Cache invalidation
After a successful mutation, invalidates marks the matching cache entries stale. The queries mounted on those keys refetch at once; the others refetch on their next mount (stale-while-revalidate: the old rows show until the new ones arrive).
{
fetch: {
method: 'insert',
from: 'articles',
on: 'submit',
fields: true,
invalidates: true // every "articles:*" key (the write's own `from`)
}
}
// Keys that contain a string (same matches as queryClient.invalidateQueries)
{ fetch: { method: 'delete', from: 'items', invalidates: ['items:select:', 'item_counts'] } }
// `'*'` is the same as `true`: every key of the write's own `from`
{ fetch: { method: 'update', from: 'settings', invalidates: ['*'] } }Each item of an invalidates list is a match: a string selects every key that contains it, a RegExp tests the key, and a function (key) => boolean decides. true and '*' select the keys of the write's own from. (Earlier releases compared a string with whole keys, so invalidates: ['posts'] matched nothing, and mounted queries were only marked stale.)
A reply that was already on its way when the keys were invalidated never replaces the refetched rows, and the cache never serves it as fresh.
Actions (rpc that writes)
An rpc can read or write. It is an action when a user event fires it (on: 'submit', on: 'click'), when it declares invalidates, or with mutation: true. An action:
- sends one request on every trigger — it is never answered from the cache, written to it, or shared with another call;
- runs its
invalidatesafter a successful call (also when the element that fired it was removed meanwhile, for example a dialog that closes on submit); - never refetches on window focus, reconnect or an interval, and an invalidation never fires it again.
// A save button: every click sends the RPC, then the article lists refetch
{ extends: 'Button', fetch: { method: 'rpc', from: 'save_article', params: (el, s) => ({ p_id: s.id }), on: 'click', invalidates: ['get_content_rows'] } }
// An RPC that writes when the element is created
{ fetch: { method: 'rpc', from: 'mark_seen', params: { p_id: 7 }, mutation: true, invalidates: ['notifications'] } }
// An RPC fired by a click that only reads, and may be cached
{ fetch: { method: 'rpc', from: 'get_quote', on: 'click', mutation: false, as: 'quote' } }An rpc without a submit/click trigger, invalidates or mutation: true stays a cached query. An action reports through the query callbacks (onFetchStart, onFetchComplete, onFetchError); the mutation callbacks (onMutate, onSuccess, onError, onSettled) and optimistic are for insert / update / upsert / delete.
Mutation callbacks
{
fetch: {
method: 'insert',
from: 'contacts',
on: 'submit',
fields: true,
onMutate: (data, el) => console.log('Sending...', data),
onSuccess: (responseData, sentData, el) => console.log('Done!', responseData),
onError: (error, sentData, el) => console.error('Failed', error),
onSettled: (data, error, sentData, el) => console.log('Finished')
}
}Callbacks
{
fetch: true,
onFetchComplete: (data, el) => {},
onFetchError: (error, el) => {},
onFetchStart: (el) => {}
}Fetch status
Every fetch exposes status on element.__ref.__fetchStatus:
{
isFetching, // true while any request is in-flight (including background)
isLoading, // true only on first load (no cached data)
isStale, // true if data is past staleTime
isSuccess, // true after successful fetch
isError, // alias: !!error
error, // error object or null (the REST adapter: the message)
httpStatus, // a failure's HTTP status (403, 503 …); null otherwise and for a network failure
code, // a failure's error code: the error body's `code` (PostgREST), else the error's; or null
status, // 'pending' | 'success' | 'error'
fetchStatus // 'fetching' | 'idle'
}Also available: el.__ref.__fetching, el.__ref.__fetchError.
The status is written before the fetched rows reach state, so a render that the rows trigger reads the final status. It is not reactive: writing it re-renders nothing, and if: / text: functions that read only the status never re-run. The plugin writes no loading or error key into state (no s.__loading, no s.__error) — a __-prefixed state key is non-reactive, and a shared state would carry one fetch's flag for every fetch on it. The one key it writes besides the rows is one a query names itself: partialAs, for a list's early first part (fetch.early slice, below).
Loading and error state in the UI
Keep the flags in the element's own state and set them from the callbacks:
export const DataList = {
state: { items: [], loading: false, error: null },
fetch: { from: 'items', as: 'items', cache: '5m' },
onFetchStart: (el, s) => s.update({ loading: true, error: null }),
onFetchComplete: (data, el, s) => s.update({ loading: false }),
onFetchError: (error, el, s) => s.update({ loading: false, error: error?.message || String(error) }),
Loader: { if: (el, s) => s.loading, text: 'Loading…' },
Failure: { if: (el, s) => Boolean(s.error), text: (el, s) => s.error },
Items: {
if: (el, s) => !s.loading && !s.error,
children: (el, s) => s.items,
childrenAs: 'state',
childProps: { text: (el, s) => s.title }
}
}- Start with
loading: false: a fresh cache hit sends no request, so neitheronFetchStartnoronFetchCompleteruns. - The REST adapter's
erroris a string; other adapters may give an object withmessage. - To tell a refusal from a failure that can pass, read the status in
onFetchError(it is written first):const { httpStatus, code } = el.__ref.__fetchStatus.httpStatusis401/403… for a refusal,nullwhen no answer came;codeis the server's stable error code (role_not_allowed), never the message, which is copy. - The same three callbacks also work inside the
fetchobject (fetch: { …, onFetchStart }), with the same arguments.
Every request's outcome (fetchSettled)
To see what each request got, app-wide (an error reporter, a trail of requests), give a plugin a fetchSettled hook; never wrap window.fetch for it.
export const requestTrail = {
name: 'requestTrail',
fetchSettled (el, info) {
// info: { mode, from, method, ok, status, code, message, durationMs, cached }
if (!info.ok || info.durationMs >= 3000) keep(info)
}
}
// in the app's context.plugins: create(App, { plugins: [requestTrail] })- It runs once for each answer a
fetchdeclaration gets: a request when it settles, or the cache (cached: true, no request). A query that shares a request already in flight sends no call of its own: that request reports, once. - It runs, the same way, for each call in code on the adapter
el.getDB()hands out (db.select,db.rpc,db.insert,db.update,db.upsert,db.delete) when it settles, and for each prefetch (el.call('prefetchQuery', config),queryClient.prefetchQuery), as a query: its request, or the cache when a fresh entry answers it. A prefetch that joins a request in flight, or a query that joins a prefetch's, sends no call of its own. elis the element that asked: the one that declared thefetch, whosegetDB()it was, or that calledprefetchQuery;nullforqueryClient.prefetchQuery, which no element calls.infois a frozen object, one for each listener, with exactly these fields:
| Field | Value |
|---|---|
| mode | 'mutation' for insert / update / upsert / delete, else 'query' (an rpc too) |
| from, method | the config's; for a call in code, the from it names and the adapter method ('select', 'rpc' …). A from that is a URL loses its query and hash. |
| ok | true when the answer came with no error |
| status | the HTTP status (200, 403 …), or null: no answer, the cache, an adapter that gives none |
| code | the server's error code, as __fetchStatus.code reads it (role_not_allowed, 42501), when it is a short token (letters, digits, ., _, -; 40 at most), else null |
| message | the error's message, or null |
| durationMs | from the request's start to its answer, on performance.now(), rounded, never below 0; 0 for the cache |
| cached | true when the cache answered |
- Nothing the request was asked with: no params, cache key, body, headers or URL.
- Listen-only: the return value is ignored. A listener that throws is caught and logged (
[@symbo.ls/fetch] fetchSettled hook threw:); the request, the element's callbacks and the other listeners go on as before. With no listener, nothing is measured or built. - It runs when the answer lands, before the element takes it. A request whose element is gone by then, or whose tenant scope (
root.__fetchScope) changed, still reports what it got; the element takes nothing, as before. A run that sends nothing reports nothing: its element left before the request went out, or while a retry waited (its failed try before is not reported either). - A write refused before it goes out (
auth: true, no session) reportsok: falsewithmessage: 'Not authenticated'. - A call in code: while a plugin listens,
getDB()hands out a view of the adapter, one for each element. Each call is the adapter's own (its method, on the adapter, with your arguments), and your code gets what the adapter gives: the same result, the same rejection, the same throw. It reports when the answer lands, before your code gets it, and also when your code drops the answer. Everything else on the view is the adapter's (subscribe, the auth methods,name, what you read or set). With no listener,getDB()hands out the adapter itself, as before. - Not covered: the auth calls (
getSession,signIn,signOut),subscribe, and the reads in code that a stale pre-built page asks again (revalidateSeed). - With
@symbo.ls/analyzeand network capture on, itsfetch.success/fetch.errorevents carrystatusandcodetoo, with the same limits.
Imperative refetch
el.__ref.refetch() sends the request even while the cached entry is fresh.
// Refetch all queries on this element
el.__ref.refetch()
// Force (skip dedup)
el.__ref.refetch({ force: true })Query client
Global cache management, importable anywhere:
import { queryClient } from '@symbo.ls/fetch'It manages the page's cache. A server render has a cache of its own (one per render): its elements reach it through el.call, and prefetchQuery takes its context.
Project code (components, pages, functions) cannot import it — frank serializes an import of @symbo.ls/fetch to a stub. It calls the same controls through el.call instead (see From project code).
Cache keys
A query's key is from:method: + its params as JSON, then :infinite, :p<page> and :c<cursor> when set (a page or cursor written as a function is resolved first), then :<lang> when a language is active, e.g. get_content_rows:rpc:{"p_table":"articles"}:ka. A tenant scope (state.root.__fetchScope) sits after from:method:. cache: { key } replaces the whole key.
Invalidate queries
queryClient.invalidateQueries('articles') // every key that contains "articles"
queryClient.invalidateQueries(['articles', 'select']) // every key that contains "articles:select"
queryClient.invalidateQueries(/^articles:select:/) // a RegExp tests the key
queryClient.invalidateQueries((key) => key.endsWith(':en')) // a predicate decides
queryClient.invalidateQueries() // every keyThe matching entries become stale, and the queries mounted on them refetch now (one request per key, shared by every element on it). The returned promise resolves when those refetches settle, so a page can wait for fresh rows before it moves on. A query that is not mounted refetches on its next mount and shows the stale rows meanwhile; use removeQueries when it must load without them. Invalidation also drops the early answers that no call has taken yet.
Get / set cache
const articles = queryClient.getQueryData('articles:select:')
// Direct set
queryClient.setQueryData('articles:select:', newArticles)
// Updater function
queryClient.setQueryData('articles:select:', (old) => [...old, newArticle])Remove queries
queryClient.removeQueries('articles') // same matches as invalidateQueries
queryClient.removeQueries() // clear allA removed key loads afresh on its next mount (no stale rows first). A mounted query keeps the rows it shows.
Raw cache access
queryClient.getCache() // the underlying Map of cache entries
queryClient.clear() // remove every entryLanguage eviction
dropNonLang(keepLang) removes every cache entry whose language suffix isn't keepLang, leaving entries with no language suffix untouched. A language switch keeps the other languages' entries (a switch back answers from the cache while they are fresh); call it when they should go, keeping the fallback locale (typically 'en') warm:
queryClient.dropNonLang('en') // keep English + lang-less entries, drop the restPrefetch
Prefetch data before it's needed (e.g. on hover):
await queryClient.prefetchQuery({
from: 'article_detail',
method: 'select',
params: { id: 42 },
cache: '5m'
}, context)The prefetched entry has the key an element of that context builds for the same query — with its language and tenant scope from context.state.root — and the request carries the same Accept-Language, so a later mount reads it without a request. It lands in that context's cache: a server render's own (isolateFetchCache), else the page's. A browser context often has no state: from project code, use el.call('prefetchQuery', config), which keys the entry by the calling element.
A prefetch shares requests both ways. Its request is in flight under its key, so a query on that key that starts while it is out joins it instead of sending a second request; and a prefetch while that query is out joins the query's request. A fresh entry answers with no request. It resolves to the answer ({ data, error }).
From project code (el.call)
When fetch is configured, smbls registers the query client's controls as project functions (a project function of the same name wins):
| el.call(…) | Does |
|---|---|
| el.call('invalidateQueries', match) | queryClient.invalidateQueries(match) — returns its promise |
| el.call('removeQueries', match) | queryClient.removeQueries(match) |
| el.call('getQueryData', keyOrConfig) | the cached rows |
| el.call('setQueryData', keyOrConfig, valueOrUpdater) | writes the cached rows (seeds the next mount; a mounted query keeps its state) |
| el.call('prefetchQuery', config) | asks for a query ahead of its mount (Prefetch); resolves to the answer |
getQueryData / setQueryData take a key, or a fetch config — { from, method, params } — whose key is built the way the calling element would build it (params resolved with that element, its language and tenant scope). prefetchQuery takes a fetch config and keys it the same way, so the element that later mounts that query in the same language and tenant reads the entry:
// functions/entryPrefetch.js — a link to an entry pointed at
export const entryPrefetch = function entryPrefetch (slug) {
return this.call('prefetchQuery', {
method: 'rpc',
from: 'get_content_rows',
params: { p_table: 'articles', p_slug: slug, p_limit: 1 },
cache: '5m'
})
}Each works on the calling element's cache: the page's in a browser, its own render's in a server render (isolateFetchCache) — what a render's project code writes, removes or invalidates stays in that render.
A write made through getDB() does not know which queries it changed — invalidate them after it:
// functions/saveArticle.js
export const saveArticle = async function saveArticle (form) {
const db = await this.getDB()
const res = await db.rpc({ from: 'save_article', params: form })
if (res.error) throw new Error(res.error)
await this.call('invalidateQueries', 'get_content_rows') // mounted lists refetch, now
this.router('/blog/' + res.data.slug, this.getRoot()) // the page shows the saved rows
}The adapter returned by getDB() is the transport itself (shared by every element, and sometimes handed across frames), so it takes no invalidates option: cache policy stays in the plugin.
Anonymous reads (reads)
Every RPC is a POST with a JSON body, and every call carries the configured headers. A cross-origin browser sends neither as a "simple" request, so each read waits for a CORS preflight first (one more round trip per read). With reads (REST adapter, opt-in) an anonymous read goes as a simple GET:
// config.js
fetch: {
adapter: 'rest',
url: 'https://<project>.supabase.co/rest/v1',
headers: { apikey: '<publishable key>' },
reads: {
// Configured headers an anonymous read carries as query parameters (header → parameter).
// A PUBLIC key only: a URL lands in server logs and the browser history. Only for a
// backend that reads it from the query string (Supabase's API gateway reads `apikey`).
query: { apikey: 'apikey' },
// The backend answers read-only RPCs as GETs with the arguments in the query string
// (PostgREST does, for STABLE/IMMUTABLE functions).
rpc: 'get'
}
}queryapplies to every anonymousselectand every anonymous read RPC. The named headers leave the request and become query parameters. A configuredContent-Typeis not sent on these GETs (there is no body).rpc: 'get'sends an RPC asGET <url>/rpc/<from>?<params>when the call is a read: a declarativefetchwithmethod: 'rpc'that is a query (not an action — noon: 'submit'/'click', noinvalidates, nomutation: true), aprefetchQueryof one, ordb.rpc({ …, read: true }). Setread: falseon a declarative rpc query to keep it a POST. AgetDB().rpc()withoutread: truestays a POST.- Only arguments that read back the same from a query string go as a GET: strings, finite numbers and booleans. A
null, an object or an array keeps the call a POST. - A signed-in call is not anonymous: with the adapter's token (
setToken,auth.token) or a per-callAuthorizationheader the call keeps the header path exactly as withoutreads. A session token never goes into a URL. - A GET answered
405(PostgREST refuses a GET for a VOLATILE function — before anything is written) is sent again as the POST. Other errors are the answer. - A relative
url(same origin) keeps RPCs as POSTs.
Other configured headers stay headers (and still cost a preflight). Without reads nothing changes. fetch.early uses the same two options and takes them from reads when it does not set its own, so one declaration drives both: the GET the pre-boot script sends is the GET the call sends, and the call adopts its answer.
Early requests (fetch.early)
A page's first view waits for its data until the app bundle has downloaded, booted and mounted. With fetch.early (REST adapter, opt-in) the build adds a small script that sends the first view's GETs while the HTML is still parsing; the adapter then adopts each answer for the first call that asks for exactly that request, instead of sending it again.
// config.js
fetch: {
adapter: 'rest',
url: 'https://<project>.supabase.co/rest/v1',
headers: { apikey: '<publishable key>' },
early: {
// Configured headers the early GETs carry as query parameters (header → parameter).
// Any custom header makes a cross-origin GET non-simple (a CORS preflight, a round
// trip before the request). Only for a backend that reads it from the query string
// (Supabase's API gateway reads `apikey`).
query: { apikey: 'apikey' },
// The backend answers read-only RPCs as GETs with the arguments in the query string
// (PostgREST does, for STABLE/IMMUTABLE functions). Without it only `select` goes early.
rpc: 'get',
// Requests every route's first view makes.
always: (params, ctx) => [
{ from: 'site_settings', select: 'key,value', lang: false }
],
// Route pattern (as in pages) → that page's first-view requests.
routes: {
'/': [
{ method: 'rpc', from: 'get_content_rows', params: { p_table: 'articles', p_limit: 20 } }
],
'/blog/:id': ({ id }, ctx) => [
{ method: 'rpc', from: 'get_content_rows', params: { p_table: 'articles', p_slug: id, p_limit: 1 } }
]
}
}
}early.query and early.rpc default to the adapter's reads — declare them once there, and the adapter's own reads match the early GETs.
A request is the adapter call it stands for: { method: 'select' | 'rpc', from, params, select, limit, offset, order, single } (method defaults to 'select'). Write a page's requests as a list, or as a function (params, ctx) => list of the route params and ctx = { path, query, lang, storage(key), meta(name), prerendered } (query is a URLSearchParams, storage reads localStorage). A function runs before the app: it must stand alone — no imports, no project functions, nothing outside its arguments and the browser's globals. Falsy items are skipped.
Language. A request asks in the active language (Accept-Language), the one a declarative fetch sends — the language the app starts in: the address's (/en/…, unless polyglot.addressLang says otherwise), else polyglot's stored choice (polyglot.storageLangKey), else state.lang, else polyglot.defaultLang. Set lang: false for a request that a getDB() call or polyglot's own loader makes — they send no language, or lang: 'en' for one that asks in a language of its own.
Start language (startLang). The rule above is the build's: it knows the languages polyglot.languages listed at build time and whatever choice is stored. A project whose languages are data (an admin adds one) or whose addresses decide the language its own way names it: startLang(ctx) returns the language the first view is in. The requests ask in it, ctx.lang is it, and the script stores it as polyglot's choice (polyglot.storageLangKey) before the app starts, so the app starts in it too — one language, no answer asked twice. It runs at once, on every page the script is on (a page built ahead, one that sends nothing, included); ctx.meta sees only the tags before the script. The app starts in its answer in every polyglot.addressLang mode, 'strict' too: the script records it (polyglotEarlyStartLang in @symbo.ls/utils), so it does not depend on the stored copy, which 'strict' never reads. null or '' keeps the rule and stores nothing — an admin that keeps its staff's language:
startLang: (ctx) => {
if (/^\/admin(\/|$)/.test(ctx.path)) return null
const prefix = /^\/([a-z]{2})(?=\/|$)/.exec(ctx.path)
return prefix ? prefix[1] : 'ka'
}A polyglot.defaultLang function (a default that is data) runs in the script as well, before it decides, with { languages }: it must stand alone, like a request function.
Adoption. A call takes an early answer only when it is the same request: the same address (the order of params does not matter), the same Accept-Language, and no other header — a signed-in call (the adapter's token, a per-call Authorization) or one with its own headers never takes the anonymous answer. Each answer is taken once. Everything else is a normal request:
- an early request that failed or came back not ok (a refused GET, a key the backend does not read from the query);
- an answer older than
early.maxAge(ms, default 30000, counted from when the script sent it); - any answer still waiting after an invalidation (a write may have happened since);
- an RPC argument that is not a string, number or boolean (
null, objects and arrays read back differently from a query string), so such an RPC never goes early.
Early GETs skip the HTTP cache (cache: 'no-store') unless the adapter's fetchOptions.cache says otherwise; they copy credentials, mode, redirect, referrerPolicy and priority from fetchOptions.
When the script decides, and on which pages. The script comes right after the page's <meta charset> (else it is the head's first child), so at once it sees nothing after itself.
wait: 'head'— the requests are decided once the head is parsed (once the<body>element exists). A request function can then read tags later in the head withctx.meta(name)(the content of<meta name="…">,nullwhen absent) — an edge's<meta name="hero" content="spring">— and ask for that entry in the same round trip as the page, instead of chaining withafter.prerendered: 'skip'— send nothing on a page built ahead (its head carries<meta name="brender">): it carries its own answers (the seed block). Implieswait: 'head'. The app shell (200.html) still gets its requests. The script is still on the built pages: the browser parses and runs it there, and its hooks (startLang,firstPaint,firstView,afterFirstView) and the module named byscriptrun there.prerendered: 'omit'—smbls buildleaves the script out of every page built ahead (the inline script or the file's tag); the app shell keeps it. For built pages that carry their language and their answers, where nothing of the script must run — its hooks and its module included. The build log,brender-report.json(early.builtPages: 'omit') andsmbls cspsay so; the inline script's hash stays on thescript-srclist for the shell. Where a built page carries the script anyway (a page the build did not make), it stands down as with'skip'.<meta name="smbls-early" content="off">in a page's head — that page sends nothing (read once the head is parsed: withwait: 'head'orprerendered).ctx.prerendered— true on a page built ahead, for a request function that chooses per request.
Without these options the script decides at once, as before.
A smaller page of a list (slice). A select with a limit (no offset, not single) and slice: true — or an rpc with slice: '<its limit argument>', slice: 'p_limit' — also stands in for a call that asks the same with a smaller limit: the call takes the first rows of the early answer (a list), once, and sends nothing. The page asks for 24 entries early; its list's first view asks for 6 and gets the first 6. A call for another offset, filter or order asks the network.
The other way round, with adopt: 'init': an early answer with FEWER rows than the call asks for is the call's first part. The element shows it at its init and asks for all of them at once; their answer replaces the first part. The page asks for its first view's 2 rows early, its list for 12. A first part that is not in yet when the element is created is not waited for: the call asks for its rows as usual.
routes: {
'/:lang': ({ lang }, ctx) => [
{ from: 'entries', select: 'id,title', order: 'published_at.desc', limit: 24, slice: true },
ctx.meta('hero') && { from: 'entries', params: { slug: 'eq.' + ctx.meta('hero') }, single: true }
]
},
wait: 'head',
firstPaint: (ctx) => { /* below-the-fold work, an analytics beacon */ }The first part, for the view (partialAs). A query that names a state key with partialAs (~/key for the root state, as with as) keeps it true while the element shows the first part and asks for the rest, and false once an answer replaced it or the request for the rest failed (the first part then stays). It is written with the first part's rows, so the element's first render sees both. Nothing else sets it: a filter's refetch, an invalidation or el.__ref.refetch() leaves it false. The status cannot do this: el.__ref.__fetchStatus.isFetching re-renders nothing, and it is the same while a filter's refetch runs. The key is for the view, not for transform: transform runs for the first part AND for the full answer, before the key is written, so it cannot tell them apart. Keep "more rows" logic (a "Show more", the list's end) in the view, behind the key:
ArticleList: {
state: { items: [], firstPart: false },
fetch: { method: 'rpc', from: 'get_list', params: { p_limit: 12 }, as: 'items', cache: '5m', partialAs: 'firstPart' },
Items: { children: (el, s) => s.items, childrenAs: 'state', childProps: { text: (el, s) => s.title } },
// "Show more" on a full page only: a first part's 2 rows are none.
Button: {
text: '{{ showMore | polyglot }}',
visibility: (el, s) => (!s.firstPart && s.items.length === 12 ? 'visible' : 'hidden')
}
}Show an answer at once (adopt: 'init'). By default an early answer is taken by the call that asks for it — after the element was created, from its empty state (its loading look), a few awaits later. With adopt: 'init' the script reads each answer as it comes in, and an element whose create-time query (select, or a read rpc, with a cache) asks for exactly an answer that is in takes it at its init, as a page built ahead's recorded answer is taken: it renders with its data from its first render, nothing shows a loading look, and its onFetchComplete runs once. Only on the app shell: on a page built ahead (its <meta name="brender">) the adoption stays as it is. Implies wait: 'head'.
First view (firstView). firstView(ctx) runs once the first view is in, for work that must not compete with it (an analytics beacon, page views, files for the next visit): once smbls reports its first view (where it runs afterFirstView: on a page built ahead, after the takeover) and the page has loaded, at the next idle moment (2 s at most). The app's first view is its first content, so the script waits for no paint of its own; a tab opened in the background runs it at its first idle moment too. An app that never reports is not waited for past 20 s after load. It runs on every page the script is on.
Your own pre-boot code in the same file (script). script: './early.js' (relative to the project's source directory) bundles the project's own pre-boot module into early.<hash>.js — one request instead of two. The module runs first, on every page, before the requests; it may import what it likes (it is bundled from source). The hooks it exports — startLang, firstPaint, firstView, afterFirstView — are the script's, with the module's closure: what its top level set up (a page-view counter installed before the app's router) is there when firstView runs. A hook declared in fetch.early and exported too stops the script's build (Early data requests skipped: … declared twice). Remove the module's own <script> from the page.
// symbols/early.js
let views = 0
export const startLang = (ctx) => /^\/en(\/|$)/.test(ctx.path) ? 'en' : 'ka'
export const firstView = (ctx) => { views++ /* the beacon */ }First paint (firstPaint). firstPaint(ctx) runs once, when the page first painted (the paint timing entry; a frame and a task where the browser has none). On a page built ahead that is long before the app takes the page over, where afterFirstView runs. Like a request function it runs before the app and must stand alone. It runs on every page the script is on.
Build. smbls build (and smbls deploy to Cloudflare or Netlify) writes the script next to the built page as early.<hash>.js and references it right after the page's <meta charset> — the charset declaration stays first — else first thing in <head>: <script async fetchpriority="high" data-symbols-early src="…">. A file, not an inline script, so a Content-Security-Policy without 'unsafe-inline' allows it. At high priority, as the app's own scripts: a browser fetches an async script at low priority, and a server that follows the browser's priorities would send the app's files before it, so its requests would start late. The script carries only the parts the declaration uses, found in the declaration's own text. When every request list is data (no function in it, no after request), the build makes each request's address and identity with the adapter's own code, and the script only sends them: one list of settings is under 0.3 KB Brotli. A request list that is a function is decided in the browser, by the script's own code; a request with a key that text never names (a computed order, limit, offset or single) is not sent early, and the app sends it as usual. The build minifies the script with esbuild, then renames its locals with terser: names only, no expression rewritten, because terser's names compress better. The optimized page counts as written: unquoted attributes (<script type=module src=/index.1a2b.js>) and a dropped optional <head> tag (the script then goes in the implied head, after <meta charset>). Inline (inline: true). As a file the script shares the line with the app's script, its preloads, the fonts and the first photo: on slow 4G it can arrive long after the page, and its requests start only then. With fetch.early.inline: true the build writes the script into the page at the same place, <script data-symbols-early>…</script>, so its requests start as the parser reaches it. A Content-Security-Policy without 'unsafe-inline' allows it by its hash: the build logs it (Allow the inline early script with 'sha256-…' in script-src), returns it, and writes it in brender's page report (early: { mode: 'inline', hash, bytes }). Every page built from the shell carries the same script, so one hash allows it everywhere; the hash changes when the declaration or the CLI changes. The page grows by the script's bytes, and a returning visitor gets them with each page instead of from the cache. A script whose text holds <!-- or </script (only without terser, which escapes both) stays a file, and the build says why. When fetch.early is set and nothing could be added — no app script on the page, or no request the script can make (it needs the REST adapter, url, and always or routes) — the build says why (Early data requests not added: …) and still succeeds. Without fetch.early the build output is unchanged. Other build paths can generate the script with createEarlyScript({ fetch, polyglot, state }) from @symbo.ls/fetch/early-script. The script never runs on the server (brender), and an adapter without early never looks for its answers.
Server-seeded answers (brender)
A page pre-rendered by @symbo.ls/brender carries the answers its render got, so the client does not ask for them again: a JSON data block after the markup (no Content-Security-Policy blocks one).
<script type="application/json" data-fetch-seed>[{"k":"<earlyKey>","s":200,"t":"application/json","b":"[…]"}]</script>- Recorded on the server: a GET whose only headers are
Accept/Accept-Language— an anonymous read; withreadsits configured key travels in the query string, so a keyed backend's reads (Supabase) count, and read-only RPCs (reads.rpc: 'get',read: true) too — with an ok JSON or text answer. Never a POST, a call withAuthorizationor another header. - Read on the client: the REST adapter reads the block when it opens (the block goes once read). A call takes a seeded answer when it sends exactly the recorded request: the same URL (query included) and
Accept-Language, no other header. Each answer is taken once, within 30 s, and read without aResponse— its data lands in the task the app booted in. Withoutfetch.earlytoo. The 30 s count from when the page is read, not from the build: the answers are the build's (a pre-built page shows the data of its build). - Taken at the element's init: an element whose
on: 'create'query has a recorded answer takes it before its node, attributes and children are made, so it is built with the page's data and never shows a loading look; its own run is then answered from the cache. - Queries that run later: a render also records which of its queries each element ran — also one that ran after the element's create, on a state change or once its
enabledturned true (fetchRunsOf(context):{ [element path]: [index in its fetch list, …] }). The page carries it as the block's last item,{"r":{…}}. In the browser such an element takes those queries' recorded answers at its init, whatever their trigger andenabledsay then: a part that asks for its data later (on: 'stateChange',enabled: (el, s) => s.below) is taken over as the page shows it, not from its empty state, and its query, once due, is answered from the cache. An element that never ran a query in the render never takes another element's answer to the same request. A page without the record (an older build) works as before. - Build side:
createEarlySeedBlock(entries, runs)(entries:[{ url, lang, status, type, body }],runs:fetchRunsOf's record, optional);createEarlySeedScript(entries)is the older inline form. - One query cache per render: a context with
isolateFetchCache: true(brender sets it on every render) has a cache of its own — its entries, its requests in flight, its invalidations and its mounted queries — made at its first query and dropped with the context. A render starts empty and makes every request its markup depends on itself, so its seed carries every answer it shows, even when an earlier page read the same key. Renders in one process — one after another or at once, of one project or of several — never share a row, a request in flight or an invalidation, and a request that outlives its render never reaches another one.queryClientstays the page's cache; a render's own is reached through its elements (el.call('invalidateQueries', …),getQueryData, …) andprefetchQuery(config, context). Such a context also binds no window focus, reconnect orrefetchIntervalrefetch: once its markup is taken, a render's queries leave no listener, no timer and no request behind. A browser context never sets it; the cache works as described above.
A pre-built page shows the data of its build
A page smbls build pre-rendered carries the answers of the build time until the next build: its visitor sees them, and the calls that take them never reach the server. When the data can change between builds, tell the page it is stale. It then shows the build's data at once (adopted as on any page — no flash, no empty state), and after the adoption, at idle, asks again for exactly what took a recorded answer and swaps in what changed (stale-while-revalidate).
Each pre-rendered page says which build it is: <meta name="brender-stamp" content="<stamp>" data-time="<ms>"> in <head> (brender stamp: the project's version of its data, else the build time as an ISO string). A page is stale when:
- the host marks it —
<html data-smbls-stale>(an edge Worker that compares the stamp with its data's last change sets it without parsing the page); - the project says so —
fetch.seed.isStale(stamp, { time })returns true (or a promise of true). It runs once, when the page's seed is read, and is published with the config: keep it self-contained (no closure, no import); - its build is older than
fetch.seed.maxAge(ms, or'30m','6h').
// config.js
export default {
fetch: {
adapter: 'rest',
url: 'https://xxx.supabase.co/rest/v1',
seed: {
maxAge: '6h', // a build older than 6 h refreshes
onRefresh: (changes, root) => { // imperative reads that changed
for (const { from, data } of changes) {
if (from === 'settings') root.state.root.update({ settings: data })
}
}
}
}
}What the refresh asks again, once per page:
- A declarative query that took a recorded answer: its key is invalidated, so every mounted query on it refetches and writes its rows into state. A keyed list keeps the nodes of the rows that did not change and adds the new ones.
- An imperative read (
getDB()→db.select/db.rpc) that took one: its request is sent again. Only the project knows where it put the old answer, so the ones whose answer changed go tofetch.seed.onRefresh(changes, root)—changes:[{ method, from, params, data, previous }],rootthe app's root element. - The recorded answers no call took are dropped: a later call asks the network.
A page that is not stale records nothing and sends nothing extra. smbls starts the refresh when the first view is in (the hydration window closed; on a replaced page, its first view settled) AND the page took a recorded answer. The REST adapter reads the seed only when it opens, so a page whose only answers are reads in code (getDB() in onRender) can take its first one later: the refresh then starts after that take, once the view settled again. smbls reports the outcome on window.__BRENDER_HYDRATION__.refreshed ({ queries, reads, changed }). On a replaced page (hydrate: false, no registry) that object is { replaced: true } with no adoption counts. A page that was never pre-rendered has no window.__BRENDER_HYDRATION__. From code: seedIsStale(), whenSeedTaken(listener) and revalidateSeed(root) (from @symbo.ls/fetch); STALE_ATTRIBUTE is 'data-smbls-stale'.
fetch.seed: false adopts no recorded answer: the client asks for everything itself, and brender writes no seed into the page.
requestsInFlight() and whenRequestsIdle() (from @symbo.ls/fetch) count the REST adapter's requests from the call until the body is read — smbls holds the hydration window over a pre-rendered page open until the first view's requests are done.
Auth guard
{ fetch: { from: 'profile', auth: true } }Subscribe (realtime)
{ state: 'messages', fetch: { method: 'subscribe', from: 'messages', subscribeOn: 'INSERT' } }An element holds one subscription: a re-run (el.__ref.refetch()) closes the old one before it opens the new one, and window focus, reconnect and invalidation do not re-open it. It is closed when the element is removed.
Element removal
When an element is removed, the plugin releases what it bound for it: the refetchInterval timer, the window focus / online listeners, the submit / click listeners, an on: 'stateChange' watcher and a realtime subscription.
Per-request overrides (REST)
{ fetch: { from: '/users', baseUrl: 'https://api.example.com/auth', headers: { 'X-Custom': 'value' } } }Per-call headers
A call's headers merge over the adapter's configured headers and its token. Names match case-insensitively and the call's value wins, so one call can send its own Bearer token (for example a per-user token). A null value removes a configured header. headers can be a plain object, a Headers instance or an array of [name, value] pairs.
const db = await el.getDB()
await db.select({ from: '/me', headers: { Authorization: `Bearer ${userToken}` } })
await db.select({ from: '/public/feed', headers: { Authorization: null } }) // no token on this callresponseType
responseType sets how the REST adapter reads the response body. It works on select, rpc, insert, update, upsert and delete, and on the declarative fetch options.
| Value | data on success |
|-------|-------------------|
| 'auto' (default) | JSON when the content-type contains json, else text |
| 'json' | parsed JSON, whatever the content-type says (null for an empty body) |
| 'text' | the body as a string |
| 'blob' | a Blob — binary bytes and the content type stay intact (audio, xlsx, csv) |
| 'arrayBuffer' | an ArrayBuffer |
| 'stream' | the body ReadableStream, returned before the body is read (null when there is no body) |
| 'response' | the raw Response, unread (use it when you need the response headers) |
A failed response keeps the { data, error, status } contract for every type, plus retryAfter (the Retry-After header as sent) when the server sends one. The adapter reads the body (JSON by content-type, else text) for the message. error is its message or error field, else the status text, else HTTP <status> (an HTTP/2 or HTTP/3 response has no status text), so a failed response always has a truthy error. data is the error body. With 'response', data stays the unread Response, and the message comes from a copy. An unknown responseType throws before the request is sent.
Read a streamed (SSE) answer chunk by chunk:
const db = await el.getDB()
const { data: stream, error } = await db.insert({ from: '/ask', data: { question }, responseType: 'stream' })
if (error) return
const reader = stream.pipeThrough(new TextDecoderStream()).getReader()
while (true) {
const { value, done } = await reader.read()
if (done) break
onChunk(value) // 'data: …\n\n' lines, as the server sends them
}Download a file as a Blob:
const { data: blob, error } = await db.select({ from: '/finops/report.xlsx', params: { month: 9 }, responseType: 'blob' })
if (!error) el.state.update({ reportUrl: URL.createObjectURL(blob) }) // blob.type is the server's content-typeIn a declarative fetch:
{ state: { answerAudio: null }, fetch: { from: '/voice/answer', responseType: 'blob', as: 'answerAudio' } }- A
Blob,ArrayBuffer, stream orResponsegoes into state only underas, as the value itself. Withoutas, read it intransformor `onFe
