Helpers: paywall, flags, updates, language, theme, sharing
These are small helpers in the dgclient SDK. Each one replaces code you would otherwise write yourself, and none needs any setup on the platform. They need dgclient 0.2.0 or newer:
npm install dgclient@latest
All the examples assume you created the client once:
import { createDg } from 'dgclient'
const dg = createDg()
| I want to... | Use |
|---|---|
| Let only paying users open a feature | dg.billing.require('pro') |
| Turn a feature on or off for everyone, without a new upload | dg.flag('new-ui') |
| Tell people "a new version is available" | dg.onUpdate(...) |
| Show my app in the user's language, with the right digits, dates and money | dg.t() and dg.i18n |
| Support light and dark mode | dg.theme |
| Let people share my app, with a QR code | dg.share() and dg.qr() |
| See crashes in my dashboard | captureErrors: true |
| Use all of this from React, Vue or Svelte | dgclient/react, dgclient/vue, dgclient/svelte |
Gate a feature behind a plan
Without this helper, a paid feature takes four steps: check whether the user is signed in, send them to sign in if not, check their subscription, and send them to pay if they have none. dg.billing.require does all four.
async function exportPdf() {
const access = await dg.billing.require('pro')
if (!access) return // the browser is leaving for the sign-in or the pay page
makePdf()
}
require('pro') looks at who the user is and answers like this:
| The user is... | What happens | It resolves to |
|---|---|---|
| Signed out | The browser goes to the dg.run sign-in page, then comes back to this page | null |
Signed in, without the pro plan |
The browser goes to the dg.run pay page for pro, then comes back to this page |
null |
Signed in, with the pro plan active |
Nothing | The entitlement: { plan, trial, periodEnd, validUntil, source } |
So null always means "the page is being left". Test it with if (!access) return and stop there.
When the user comes back
The user lands on the same page (or on returnTo, if you pass one). The page loads fresh, so run your check again. The simplest way is to let the user click the button a second time. If you want it to continue by itself, use dg.billing.checkout, which tells you how the trip to the pay page ended:
const back = await dg.billing.checkout // { result: 'ok' | 'cancel', plan } on the return page, else null
if (back?.result === 'ok' && (await dg.billing.has('pro', { refresh: 'always' }))) makePdf()
Several plans
Pass a list to accept any of them. A user who holds any plan in the list gets through:
await dg.billing.require(['pro', 'team'])
When the user has none, require has to decide which plan to send them to to pay:
- If exactly one plan fits (
require('pro'), or a list of which only one exists), it sends them there. - If several fit, you choose. Give
choosea function that returns a plan key, for example to show your own picker:
await dg.billing.require(['monthly', 'yearly'], {
choose: (plans) => askUser(plans), // plans: the Plan objects that fit; return the key of one, e.g. 'yearly'
})
- Or name the plan yourself:
require(['monthly', 'yearly'], { plan: 'yearly' }). - With several plans and neither
choosenorplan, it throws aDgErrorwith the codeplan_not_found.
require() with no argument means "any plan will do".
Options
| Option | What it does |
|---|---|
plan |
The plan to send the user to when they have none. |
choose |
A function that picks the plan when several fit. It may be async. |
returnTo |
Where to land after signing in or paying (default: the current page). |
refresh |
'auto' (default), 'always' or 'never': how to treat the subscription proof kept on the device. See Plans and subscriptions. |
Only checking, without sending the user anywhere
dg.billing.has answers yes or no and never redirects. Use it to show a lock icon, or to decide which buttons to draw:
const isPro = await dg.billing.has('pro') // or has(['pro', 'team']), or has() for any plan
proBadge.hidden = !isPro
What this protects. Like
dg.billing.status(),requireonly decides what your page shows. Static code runs in the user's browser, so someone determined can edit it. Data that must stay private belongs in a collection whose rules the server enforces (see Roles and permissions), not behind anifin your page.
Feature flags
A flag is a setting you can turn on or off from the dashboard without uploading a new build. Use one to ship a feature switched off, then turn it on when you are ready, or to switch something off quickly if it misbehaves.
1. Declare it in your web manifest, with its default:
{
"config": {
"new-ui": false,
"show-beta-banner": true
}
}
Keys start with a letter and may contain letters, digits, _, . and - (up to 40 characters). An app can declare up to 50 settings. A boolean default (true / false) is what makes it a switch in the dashboard.
2. Read it in your app:
if (dg.flag('new-ui')) showNewUi()
else showOldUi()
dg.flag(key, fallback) answers right away (it never waits for the network). The second argument, false by default, is what you get until a value has been received, and when the setting isn't a switch.
3. Flip it. Open My apps → Config, change the switch and save. Pages that are open get the change within about a second if you listen for it:
const stop = dg.config.onFlag('new-ui', (on) => (on ? showNewUi() : showOldUi()))
// call stop() when you no longer need it
onFlag keeps the live connection open (the same one collection.live uses). Without it, the new value arrives the next time the page is shown or the network comes back.
What counts as a switch:
| Value of the setting | dg.flag() gives |
|---|---|
true / false |
The same |
The text on, yes, true, 1, enabled (any capitals) |
true |
The text off, no, false, 0, disabled |
false |
| Any other text, or a number | The fallback |
Good to know:
- Values are public. Every visitor can read them, signed in or not. Never put a secret or anything personal in a setting.
- Offline. The last values are kept on the device, so an installed app starts with them even without internet.
- Sandbox, review and live. Your sandbox and the admin's preview use the settings of your newest upload; the live app uses the ones of the approved version. So you can try a new flag in the sandbox before it exists in the live app.
- A flag is for the whole app: everyone sees the same value. (Turning it on for some users only is not available yet.)
See Remote config for settings that aren't switches (numbers and text).
A new version is available
When you publish a new version, people who have the app open keep running the old one until they reload. dg.onUpdate tells the page when a different version has gone live, so you can offer a reload:
dg.onUpdate(({ reload }) => {
banner.textContent = 'A new version is available.'
banner.hidden = false
banner.onclick = reload // loads the page again, which fetches the new files
})
The callback gets { build, reload }. build is the number of the version that is live now. reload() reloads the page.
How it works: the first version number the page sees is the one it is running. If a different number shows up later, there is an update. That includes a rollback (an admin putting an older version back): the page is told that a different version is live, so it can reload into it too. If the live version goes back to the one the page is running, nothing is announced.
- It fires once per version, not on every check.
- If you register a listener after an update was already noticed, it is called right away (on the next tick).
- It rides on the settings connection, so it arrives within about a second while the page is visible. When the page was hidden, or realtime is off (
createDg({ realtime: false })), it is checked when the page is shown again or the network returns. dg.updates.availableistruewhile an update is waiting.dg.onUpdatereturns a function that stops listening.- It works on your sandbox too: upload a new test build and open sandbox pages hear about it.
Installed apps with a service worker. If your app caches
index.htmlin a service worker, the page you are looking at may already be older than the live version when it opens, andonUpdateonly reports versions that go live after the page started. Handle that case with the service worker update check in Installing and offline use, and useonUpdatefor apps that stay open.
Language and formatting
dg.t() shows your own texts in the user's language. dg.i18n formats numbers, money and dates the way that language writes them: Persian digits, the Jalali calendar, rials and toman.
Set it up
Say which languages you support and give your texts:
const dg = createDg({
locales: ['en', 'fa', 'fr'], // the first one is the fallback
messages: {
en: { save: 'Save', welcome: 'Welcome, {name}', files_one: '{count} file', files_other: '{count} files' },
fa: { save: 'ذخیره', welcome: 'خوش آمدید، {name}', files_other: '{count} فایل' },
fr: { save: 'Enregistrer', welcome: 'Bienvenue, {name}', files_one: '{count} fichier', files_other: '{count} fichiers' },
},
})
dg.i18n.apply() // puts lang="fa" dir="rtl" on <html>, and keeps it right when the language changes
Then use it:
dg.t('save') // "Save", "ذخیره" or "Enregistrer"
dg.t('welcome', { name: 'Sara' }) // "Welcome, Sara"
dg.t('files', { count: 1 }) // "1 file"
dg.t('files', { count: 5 }) // "5 files" (in Persian: "۵ فایل")
How t() finds the text, for the key you give:
- The user's language (
fr-CAis tried asfr-CA, thenfr). - Your fallback language (the first of
locales, orfallbackif you set it). - The key itself, so a missing text shows up on screen instead of breaking the page.
Rules for texts:
{name}is replaced from the second argument. A placeholder with no value stays as it is, so you can see the mistake.- Numbers you pass are written the way the language writes them (
{count}becomes۵in Persian,1 234in French). To keep the plain number, pass it as text:{ count: String(n) }. - Plurals. When you pass
count,t()looks forkey_one,key_other, and where the language has themkey_zero,key_two,key_few,key_many, thenkey_other, then plainkey. English and French useoneandother; Persian usesother; Arabic and Russian have more forms.
Which language is used
The first of these that you support:
- The language the user chose with
dg.i18n.set(...)(remembered on this device). - The
localeoption, if you set one. - The browser's languages, in the user's order (
fr-CAmatchesfr). - The page's
<html lang>. - The fallback.
Without locales and messages, any language the browser says is accepted. This is also why a language picker is two lines:
select.value = dg.locale // "en", "fa"...
select.onchange = () => dg.i18n.set(select.value)
dg.i18n.onChange((locale) => render()) // redraw your texts when the language changes
dg.i18n.reset() // forget the choice and follow the browser again
Also available: dg.locale (the language in use), dg.i18n.dir ('rtl' or 'ltr': right-to-left for Persian, Arabic, Hebrew, Urdu and a few more) and dg.i18n.add('de', { ... }) to add texts later.
Numbers, money and dates
| Call | English | Persian | French |
|---|---|---|---|
dg.i18n.number(1234567.5) |
1,234,567.5 | ۱٬۲۳۴٬۵۶۷٫۵ | 1 234 567,5 |
dg.i18n.money(9, 'USD') |
$9.00 | $۹٫۰۰ | 9,00 $US |
dg.i18n.date(date) |
Nov 21, 2026 | ۳۰ آبان ۱۴۰۵ | 21 nov. 2026 |
dg.i18n.dateTime(date) |
Nov 21, 2026, 3:04 PM | ۳۰ آبان ۱۴۰۵، ۱۵:۰۴ | 21 nov. 2026, 15:04 |
dg.i18n.relative(minutesAgo) |
3 minutes ago | ۳ دقیقه پیش | il y a 3 minutes |
dg.i18n.list(['a', 'b', 'c']) |
a, b, and c | a، b، و c | a, b et c |
Money. money(amount, currency) takes a normal amount (dollars, whole rials) and a currency code. That is what dg.billing.plans() gives you, so dg.i18n.money(plan.price, plan.currency) is a correct price label. Two options:
dg.i18n.money(1999, 'USD', { minor: true }) // $19.99: the amount is in cents
dg.i18n.money(1_500_000, 'IRR', { as: 'toman' }) // "۱۵۰٬۰۰۰ تومان": rials shown as toman (÷ 10)
dg.i18n.money(2500, 'IRT') // "۲٬۵۰۰ تومان": IRT means toman itself
Dates. A date can be a Date, a number of milliseconds or an ISO text. For Persian the Jalali calendar is used by default, so the same day reads ۳۰ آبان ۱۴۰۵. Choose another calendar with calendar, and use any option of Intl.DateTimeFormat (dateStyle, month, timeZone...):
dg.i18n.date(Date.now(), { calendar: 'gregory' }) // "۲۱ نوامبر ۲۰۲۶" in Persian: the usual calendar
dg.i18n.date(Date.now(), { month: 'long', day: 'numeric' }) // your own fields
dg.i18n.date(Date.now(), { timeZone: 'Asia/Tehran' })
relative(date) says how long ago (or how far ahead): "3 minutes ago", "tomorrow", "in 2 months".
Light and dark mode
dg.theme remembers whether the user wants light or dark mode and gives your CSS the same neutral palette dg.run uses, so your app looks at home next to the platform.
const dg = createDg({ theme: { apply: true, accent: '#6d5dfc' } })
apply: true puts the theme on the page right away: <html data-theme="dark"> (and the dark class, which Tailwind's dark mode looks for), the browser's color-scheme, and a <style id="dg-theme"> that defines the variables below. Without apply, nothing is changed until you call dg.theme.apply().
Use the variables in your CSS:
body { background: var(--dg-background); color: var(--dg-foreground); }
.card { background: var(--dg-muted); border: 1px solid var(--dg-border); }
.hint { color: var(--dg-muted-foreground); }
.button { background: var(--dg-brand); color: var(--dg-brand-foreground); }
| Variable | What it is |
|---|---|
--dg-background / --dg-foreground |
Page background and normal text |
--dg-muted / --dg-muted-foreground |
Cards and panels, and quiet text |
--dg-surface |
A slightly stronger panel colour (hover states, chips) |
--dg-border |
Lines and outlines |
--dg-primary / --dg-primary-foreground |
The neutral strong colour of dg.run (black in light mode, white in dark mode) and the text on it |
--dg-brand / --dg-brand-foreground |
Your colour and a black or white text that reads well on it. Only defined when you set accent |
Your own CSS always wins: redefine any variable in your stylesheet to change it.
Let the user choose
dg.theme.set('dark') // 'light', 'dark' or 'system' (follow the device). Remembered on this device.
dg.theme.toggle() // light <-> dark
dg.theme.mode // what was chosen: 'light' | 'dark' | 'system'
dg.theme.resolved // what is shown now: 'light' | 'dark'
dg.theme.onChange((scheme, mode) => icon.textContent = scheme === 'dark' ? '☀️' : '🌙')
The default mode is system. While the mode is system, the page follows the device when the user switches it, with no reload. Change the starting mode with theme: { mode: 'light' }; the user's own choice always wins over it.
dg.theme.accent = '#ff6600' changes your colour later. Only #rgb and #rrggbb are accepted; anything else is ignored. If you don't want apply(), dg.theme.tokens() returns the variables as an object (name to value) for the current mode, to use however you like.
Where the theme comes from. The mode and the language are remembered by the browser, for your app only. They are not read from the user's dg.run account: the dg.run site keeps its own settings on its own address, which an app cannot see. A user who picks dark mode on dg.run therefore still gets
systemin your app until they choose here.
Use it from React, Vue or Svelte
dgclient/react, dgclient/vue and dgclient/svelte wrap the client you already have: the user, a live list, remote config, flags, billing, theme and language, with nothing to keep in step by hand. They need dgclient 0.3.0 or newer (React 18+ or Vue 3.3+ is a peer dependency; Svelte needs nothing). Wrap the app once, then use them anywhere below:
// React
import { DgProvider, useUser, useCollection, useFlag, useBilling, useI18n } from 'dgclient/react'
<DgProvider client={dg}><App /></DgProvider>
const { user, ready, signIn, signOut } = useUser()
const { items, loading, error, put, remove } = useCollection(notes, { orderBy: 'createdAt', desc: true })
const newUi = useFlag('new-ui')
const { has, subscribe } = useBilling({ plans: true })
const { t, money } = useI18n()
// Vue: app.use(createDgPlugin(dg)); everything returned is a ref
import { createDgPlugin, useUser, useCollection } from 'dgclient/vue'
<script>
import { collectionStore } from 'dgclient/svelte' // userStore, configStore, flagStore, billingStore, themeStore, i18nStore...
const notes = collectionStore(dg, dg.db.collection('notes'))
</script>
{#each $notes.items as n (n.key)}<p>{n.data.text}</p>{/each}
| I want... | React / Vue | Svelte |
|---|---|---|
| The signed-in user and whether sign-in has finished | useUser |
userStore |
| A list that stays fresh, with add / change / delete | useCollection (read only: useLive) |
collectionStore (liveStore) |
| Remote-config values or a feature flag | useConfig, useFlag |
configStore, flagStore |
| The plan the user holds, the plans, the paywall | useBilling |
billingStore |
| Light / dark mode | useTheme |
themeStore |
| Language, texts, numbers, money, dates | useI18n |
i18nStore |
| Realtime status, online / offline | useRealtimeStatus, useOnline |
realtimeStatusStore, onlineStore |
What to know:
- Lists use
collection.liveunderneath. A private list loads only while someone is signed in and starts over when the user changes, so one account's items never show under another.put,patchandremoverefresh the list when they finish and throw the same errors as the collection. Pass{ live: false }to list once, or{ enabled: false }to switch the list off. - Billing is shared: every component that calls
useBillingwith the same settings uses one load, and it reads again after the user comes back from the pay page (checkoutsays how it ended).{ details: false }uses only the signed proof on the device, so it needs no request and works offline. In Svelte,billing.subscribe(plan)is calledsubscribeTo(plan), becausesubscribeis the name of the store contract. - Theme and language. Create the client with
theme: { apply: true }and calldg.i18n.apply()once if the page itself (<html>class,langanddir) should follow the choice.useI18n()returns new helpers when the language changes, so anything that depends ontrefreshes. - Everything else (
dg.log,dg.share(), the collections) stays on thedgclient, and the client works as before without a framework.
The React and Vue templates and the examples are written this way.
Share your app and show a QR code
shareButton.onclick = async () => {
const r = await dg.share({ title: 'My app', text: 'Try this app' })
if (r.method === 'clipboard') toast('Link copied')
}
qrBox.innerHTML = dg.qr({ size: 200 }) // a QR code of the app's address, as an SVG image
dg.share() opens the share sheet of the phone or computer when it has one. Otherwise it copies the link to the clipboard. Call it from a click: browsers only allow sharing in response to one. It resolves to { method, url }:
method |
Meaning |
|---|---|
native |
The share sheet was used. |
clipboard |
There is no share sheet: the link was copied. Tell the user. |
none |
Nothing could be done. If the user simply closed the sheet, cancelled is true. |
By default the link is your app's address (https://your-app.dg.run/). Share a particular page with url: dg.share({ url: location.href }). title defaults to the page title.
QR codes
dg.qr() returns SVG markup, which you can put straight into the page. For an <img>, use dg.sharing.qrDataUrl():
img.src = dg.sharing.qrDataUrl({ url: 'https://your-app.dg.run/', size: 240 })
| Option | Default | |
|---|---|---|
url |
the app's address | What the code contains |
size |
scales to its container | Width and height in pixels |
margin |
4 |
Light border, in modules. The standard asks for 4 |
dark / light |
#000 / #fff |
Colours of the code and its background |
The code holds up to 213 bytes (a long URL fits; a paragraph doesn't). A longer text throws a RangeError. Keep enough contrast between dark and light, or phones can't read it.
See crashes in your dashboard
const dg = createDg({ captureErrors: true, version: '1.4.2' })
Uncaught errors and unhandled promise rejections are sent to My apps → Logs, with their stack and the page. version tells you which build they came from. This is the same as calling dg.log.captureErrors() yourself. See Logs for what is kept and for how long.
Several tabs, and the network
If a user has your app open in two tabs, they stay in step on their own: signing in or out in one signs the other in or out, and the theme (dg.theme.set) and language (dg.i18n.set) they choose follow too. Your dg.onChange, dg.theme.onChange and dg.i18n.onChange listeners fire in every tab, so render from them and there is nothing else to do. Tabs also take turns renewing the session, so they don't compete for the sign-in cookie. Turn it off with createDg({ syncTabs: false }).
dg.online // false only when the browser says there is no network
await dg.whenOnline() // resolves at once when online, else when the network is back
const stop = dg.onNetwork((online) => { banner.hidden = online })
dg.online being true means a network is attached, not that the server answers, so keep handling failed requests; false is reliable. A typical use is to wait before retrying: await dg.whenOnline(); await save().
Everything at a glance
| Call | Returns |
|---|---|
dg.billing.require(plan?, options?) |
Promise<Entitlement | null>: access, or null while the user is sent to sign in or pay |
dg.billing.has(plan?, { refresh? }) |
Promise<boolean> |
dg.flag(key, fallback = false) |
boolean |
dg.config.onFlag(key, fn, fallback = false) |
A function that stops listening |
dg.onUpdate(({ build, reload }) => ...) |
A function that stops listening |
dg.updates.available |
boolean |
dg.t(key, params?) |
string |
dg.locale |
The language in use, e.g. 'fa' |
dg.i18n.set(locale) / reset() / onChange(fn) / apply() / add(locale, messages) |
Choose, forget, listen, put on <html>, add texts |
dg.i18n.number / money / date / dateTime / relative / list |
Formatted string |
dg.theme.set(mode) / toggle() / mode / resolved / onChange(fn) / accent / tokens() / apply() |
Light and dark mode |
dg.online |
boolean |
dg.whenOnline({ signal? }) |
Promise<void>: resolves when online |
dg.onNetwork(fn) |
A function that stops listening |
dg.sync.enabled |
boolean: tabs are being kept in step |
dg.share(options?) |
Promise<{ method, url, cancelled? }> |
dg.qr(options?) / dg.sharing.qrDataUrl(options?) |
SVG markup / a data: address |
All of them are methods of classes (I18n, Theme, Sharing, Updates) that you can import for typing or testing, like the rest of the SDK. The shortcuts on dg (dg.t, dg.flag, dg.share...) are bound, so button.onclick = dg.share works.