Advanced SDK configuration

SDK configuration

Build files, client options, environment variables per build tool, a local backend, the no-bundler setup and Manifest V3 details for @extensionbill/sdk.

This page is for customizing the SDK setup: picking a build, setting client options, switching keys per build and loading the SDK without a bundler. For the basic setup (install, manifest, shared bill client, startBackground()), follow the Quickstart or Pick your stack.

Build files

@extensionbill/sdk is a TypeScript SDK with zero runtime dependencies. It runs in every extension context and stores its state in chrome.storage.local, mirroring the install identity to chrome.storage.sync. You do not need a backend.

FileImportFormatUse it when
dist/index.js@extensionbill/sdkESMYou bundle your extension (recommended)
dist/index.cjs@extensionbill/sdkCommonJSYour tooling still expects require()
dist/index.d.tsType definitionsTypeScript and editor autocompletion
dist/extensionbill.global.js@extensionbill/sdk/globalIIFE, global ExtensionBillYou ship plain files without a bundler
dist/paywall.js@extensionbill/sdk/paywallESMThe optional Paywall UI
dist/extensionbill-paywall.global.js@extensionbill/sdk/paywall/globalIIFE, global ExtensionBillPaywallThe paywall without a bundler

Framework bindings are separate entries too: @extensionbill/sdk/react, /preact, /vue, /svelte, /angular, /solid and /lit (Pick your stack). Entries you never import add nothing to your bundle.

Any ESM-aware bundler works: Vite (and extension tools built on it), webpack, esbuild and Rollup. Content scripts declared in manifest.json cannot be ES modules, so emit each one as a single self-contained file (the default for most extension setups). The service worker can stay an ES module ("type": "module").

Create a shared client

Create the client once in a bill.js module and import it in every context (Quickstart). Every context then uses the same key and options.

Creating the client is cheap. The install listeners, uninstall URL, alarms and messaging bridge are set up by startBackground() in the service worker only. If the install is not registered yet (for example, the first getUser() races the install event), the SDK registers it on demand.

Client options

OptionTypeDefaultDescription
publishableKeystringRequiredYour pk_test_… or pk_live_… key. Safe to ship.
apiBasestringhttps://api.extensionbill.comAPI base URL. Must be http(s)://; trailing slashes are removed. Change it only for a local backend. Exported as DEFAULT_API_BASE.
hostedOriginstringhttps://app.extensionbill.comOrigin of the hosted checkout, portal and restore pages. The background watches tabs on this origin to detect completed purchases. Origins of URLs returned by the API are learned automatically. Exported as DEFAULT_HOSTED_ORIGIN.
timeoutMsnumber15000Per-request timeout in milliseconds. Must be positive. A slower request rejects with timeout, and getUser() falls back to the cache.
debugbooleanfalseLogs API requests, bridge messages and state changes with console.debug in each context. Enable the Verbose level in DevTools to see them. Leave it off in store builds.
verifyOfflinebooleantrueVerifies the signed entitlement token before trusting cached state. See Caching and offline grace.

ExtensionBill() throws an ExtensionBillError synchronously:

  • invalid_publishable_key when the key is missing or is not a pk_test_… or pk_live_… key.
  • invalid_argument when options is not an object, apiBase or hostedOrigin is not an http(s):// URL, or timeoutMs is not a positive number.

Keys per environment

Each app has two publishable keys, both in Developers → Integrate. The key selects the environment; there is no env option, and sandbox and live data never mix.

SandboxLive
Key prefixpk_test_…pk_live_…
PayPalSandbox, no real moneyLive
Works whenPayPal sandbox is connectedYou completed go live; otherwise 403 live_not_enabled
user.env'sandbox''live'

Use the sandbox key in development builds and the live key only in the build you publish. A store build with a test key sends buyers to the PayPal sandbox, where they cannot pay.

To test live mode with an unpacked build, add the unpacked extension ID to the allowed extension IDs (it differs from the store ID), or pin it with a key in manifest.json. Otherwise requests fail with 403 extension_not_allowed.

Environment variables

The SDK cannot read .env files at runtime. Your build tool inlines the values at build time. The same four variables work with every tool, with that tool’s prefix:

VariableRequiredOption
EXTENSIONBILL_PUBLISHABLE_KEYYespublishableKey
EXTENSIONBILL_API_BASENoapiBase
EXTENSIONBILL_HOSTED_ORIGINNohostedOrigin
EXTENSIONBILL_DEBUGNo (true or false)debug

Unset variables often arrive as empty strings, and an empty apiBase or hostedOrigin throws invalid_argument. Pass overrides only when they are set:

// src/bill.ts (Vite prefix shown; swap in your tool's from the table below)
import { ExtensionBill, type ExtensionBillOptions } from '@extensionbill/sdk'

const env = import.meta.env
const options: ExtensionBillOptions = { publishableKey: env.VITE_EXTENSIONBILL_PUBLISHABLE_KEY ?? '' }
if (env.VITE_EXTENSIONBILL_API_BASE) options.apiBase = env.VITE_EXTENSIONBILL_API_BASE
if (env.VITE_EXTENSIONBILL_HOSTED_ORIGIN) options.hostedOrigin = env.VITE_EXTENSIONBILL_HOSTED_ORIGIN
if (env.VITE_EXTENSIONBILL_DEBUG) options.debug = env.VITE_EXTENSIONBILL_DEBUG === 'true'

export const bill = ExtensionBill(options)
# .env.development
VITE_EXTENSIONBILL_PUBLISHABLE_KEY=pk_test_…
VITE_EXTENSIONBILL_DEBUG=true

# .env.production
VITE_EXTENSIONBILL_PUBLISHABLE_KEY=pk_live_…

Commit a .env.example and gitignore .env and .env.* (with !.env.example).

Per build tool

ToolRead asDev loadsStore build loadsNotes
Vite + CRXJSimport.meta.env.VITE_….env.development (vite).env.production (vite build)vite build --mode development makes an unpacked sandbox build. Type the variables in src/vite-env.d.ts (interface ImportMetaEnv).
WXTimport.meta.env.WXT_… (or VITE_…).env.development (wxt).env.production (wxt build)Put the module in utils/bill.ts. Call bill.startBackground() at the top of the defineBackground main function.
Plasmoprocess.env.PLASMO_PUBLIC_….env.development (plasmo dev).env.production (plasmo build)Put the module in lib/bill.ts.
webpack, esbuildprocess.env.EXTENSIONBILL_…dotenvdotenvInline with DefinePlugin or define.
Angular CLIa declare const constantdefine in angular.jsondefine in angular.jsonSee Angular.
No bundlerglobalThis.EXTENSIONBILL_CONFIGgenerated config.jsgenerated config.jsSee Without a bundler.

webpack and esbuild

Load the env files with dotenv, most specific first. dotenv never overwrites a variable that is already set, so real environment variables (such as CI secrets) win. Run the store build with NODE_ENV=production.

// load-env.mjs
import dotenv from 'dotenv'

export const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development'
dotenv.config({ path: `.env.${mode}` })
dotenv.config() // .env fills in anything still unset

export const define = Object.fromEntries(
  ['EXTENSIONBILL_PUBLISHABLE_KEY', 'EXTENSIONBILL_API_BASE', 'EXTENSIONBILL_HOSTED_ORIGIN', 'EXTENSIONBILL_DEBUG']
    .map((name) => [`process.env.${name}`, JSON.stringify(process.env[name] ?? '')]),
)

Pass define to new webpack.DefinePlugin(define) or esbuild.build({ define, … }).

Guard release builds

Refuse a production build without a live key:

// vite.config.ts
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd()) // VITE_* variables for this mode
  if (mode === 'production' && !env.VITE_EXTENSIONBILL_PUBLISHABLE_KEY?.startsWith('pk_live_')) {
    throw new Error('Production builds require a pk_live_ key in .env.production')
  }
  return { /* your existing config, for example the @crxjs/vite-plugin */ }
})

The Going live checklist shows the same guard for an esbuild script.

Local backend

To develop against an ExtensionBill stack running on your machine, use a publishable key issued by that stack and override both URLs (with your tool’s prefix):

EXTENSIONBILL_PUBLISHABLE_KEY=pk_test_…
EXTENSIONBILL_API_BASE=http://localhost:3738
EXTENSIONBILL_HOSTED_ORIGIN=http://localhost:5173
EXTENSIONBILL_DEBUG=true

If you use instant unlock, also add http://localhost:5173/* to externally_connectable.matches in development builds.

Without a bundler

If your extension is plain JavaScript files, copy the prebuilt global build into your extension folder. Never load it from a CDN: MV3 forbids remote code.

cp node_modules/@extensionbill/sdk/dist/extensionbill.global.js ./extensionbill.global.js

The file defines a global ExtensionBill: the same factory you would import, with ExtensionBill.ExtensionBillError and ExtensionBill.hasAccess attached. Put your configuration in one classic script so every context shares it:

// bill.js (classic script, no bundler)
const bill = ExtensionBill({ publishableKey: 'pk_test_…' })

To keep keys in env files instead, have your build script write a gitignored config.js that sets globalThis.EXTENSIONBILL_CONFIG = { "publishableKey": "pk_test_…" }, load it first, and create the client with ExtensionBill(globalThis.EXTENSIONBILL_CONFIG).

In the service worker, load both files with importScripts. This needs a classic worker, so leave "type": "module" out of the background key:

// background.js (classic service worker)
importScripts('extensionbill.global.js', 'bill.js')

bill.startBackground()

In extension pages, load them with script tags before your own code:

<!-- popup.html -->
<script src="extensionbill.global.js"></script>
<script src="bill.js"></script>
<script src="popup.js"></script>
// popup.js
bill.getUser().then((user) => {
  document.body.classList.toggle('pro', bill.hasAccess(user))
})

For content scripts, list the files before your script so they run first in the same isolated world:

"content_scripts": [
  {
    "matches": ["https://example.com/*"],
    "js": ["extensionbill.global.js", "bill.js", "content.js"]
  }
]

The paywall works the same way: copy dist/extensionbill-paywall.global.js, load it after extensionbill.global.js, and call ExtensionBillPaywall.mountPaywall(…). If your copy step resolves package exports (a copy plugin or require.resolve), use @extensionbill/sdk/global and @extensionbill/sdk/paywall/global.

Manifest V3 notes

manifest.json

A complete example with a popup, an options page, a content script and instant unlock:

{
  "manifest_version": 3,
  "name": "Focus Tabs",
  "version": "1.4.0",
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "permissions": ["storage", "alarms"],
  "action": { "default_popup": "popup.html" },
  "options_page": "options.html",
  "content_scripts": [
    {
      "matches": ["https://*.example.com/*"],
      "js": ["content.js"],
      "run_at": "document_idle"
    }
  ],
  "externally_connectable": {
    "matches": ["https://app.extensionbill.com/*"]
  }
}
KeyWhy
background.service_workerRuns the SDK’s background half. "type": "module" lets you import the SDK; drop it if you use importScripts.
permissions: ["storage"]Required. The SDK keeps the install ID, install token, cached state and signing keys in chrome.storage.local, and mirrors the install ID and token to chrome.storage.sync.
permissions: ["alarms"]Optional, recommended. Schedules a periodic refresh, so renewals, cancellations and refunds arrive even if the user never opens the popup. Without it, state refreshes on browser startup, on install or update, after checkout and on bill.refresh().
action, options_page, content_scriptsYour own UI. Nothing SDK-specific is required.
externally_connectableOptional instant unlock. The hosted success page sends { type: 'extensionbill:refresh' } the moment payment completes. The SDK accepts it only from the hosted origin and only triggers a refresh; it never trusts data from the page. It grants no permissions and causes no install warning. Without it, the SDK still detects the purchase by watching the checkout tab, a few seconds later.

You need no tabs permission: the SDK opens hosted pages with tabs.create and tracks the tab IDs it created. With tabs, it can also detect hosted pages opened another way.

Why no host_permissions

The service worker and extension pages call https://api.extensionbill.com directly. The API answers with CORS headers that allow chrome-extension://, moz-extension:// and safari-web-extension:// origins. Host permissions would only add an install warning.

Content scripts are different: their requests carry the web page’s origin. So the SDK never calls the API from a content script; it forwards the call to your service worker (Checking access).

Restrict which extensions can use your key

Publishable keys are public by design. Add your extension IDs under Settings → General (allowed extension IDs) to reject every other extension with 403 extension_not_allowed. An empty list allows any extension. List both your store ID and your unpacked development ID. The check applies to chrome-extension:// origins (Chrome, Edge); Firefox and Safari use per-install origins and are not checked.

Start the background

startBackground() must run in the service worker, synchronously at the top level. It:

  • registers the install on runtime.onInstalled and runtime.onStartup, and stores the install ID and token;
  • sets the uninstall URL for install analytics;
  • schedules the periodic refresh when the alarms permission is present;
  • answers requests from popups, options pages and content scripts (the messaging bridge);
  • watches hosted checkout tabs and refreshes the state when a purchase completes.

MV3 stops the service worker after about 30 seconds without activity and restarts it when an event arrives. Chrome delivers that event only to listeners registered during the first run of the script. Call startBackground() inside a then(), after an await or in another handler, and the worker can restart without the SDK’s listeners: installs are not registered and the bridge never answers.

State lives in chrome.storage.local (install identity mirrored to chrome.storage.sync) and watched tabs in chrome.storage.session, so nothing is lost while the worker sleeps. Popups and options pages fall back to calling the API directly if the background is not running the SDK. Content scripts cannot: without startBackground() their calls reject with background_unavailable.

Firefox and Edge

Edge uses the Chrome extension platform. The same package and manifest work unchanged, and installs are reported as edge.

Firefox needs an explicit add-on ID and runs MV3 background code as an event page declared with scripts:

{
  "background": {
    "service_worker": "background.js",
    "scripts": ["background.js"],
    "type": "module"
  },
  "browser_specific_settings": {
    "gecko": { "id": "focus-tabs@yourdomain.com" }
  }
}

The add-on ID also keeps storage.local and storage.sync, and with them the SDK’s install, tied to a stable ID while you develop. Temporary add-ons cannot use storage.sync, so the SDK falls back to storage.local only. Recent Chrome and Firefox versions ignore the background key meant for the other, so one manifest serves both; for older browsers, generate one manifest per browser. Firefox does not support externally_connectable, so purchases are detected by tab watching and polling only.

The SDK resolves the extension API as globalThis.browser ?? globalThis.chrome and supports promise-based browser.* APIs, so you need no polyfill. Use the same expression in your own code:

const ext = globalThis.browser ?? globalThis.chrome

Content Security Policy

The SDK works under the default MV3 Content Security Policy, so you do not need to change content_security_policy:

  • No remote code. Everything ships in your package and only exchanges JSON with the API. Checkout, portal and restore run on hosted pages in a normal tab.
  • No eval, new Function or string timers.
  • No inline scripts or handlers. The paywall builds its DOM with createElement in a shadow root and uses addEventListener.
  • No DOM in the service worker. Signature checks use WebCrypto.

What the SDK stores

All SDK data lives in chrome.storage.local under keys prefixed with extensionbill:. The install identity is also mirrored to chrome.storage.sync:

KeyContentsSynced
extensionbill:publishableKeyThe key the stored install belongs to.Yes
extensionbill:installIdThe install’s UUID. Show it on support screens.Yes
extensionbill:installTokenThe it_… token that authenticates this install.Yes
extensionbill:userStateThe last UserState received from the API.No
extensionbill:jwksPublic keys for verifying the entitlement token offline.No
extensionbill:hostedOriginThe hosted pages origin used for checkout tab watching.No

Watched tab IDs live in chrome.storage.session under extensionbill:hostedTabs (in memory when storage.session is unavailable).

The local copy always wins. If chrome.storage.local has no install for the current publishable key, the SDK adopts the synced one (same publishable key only), copies it to local and refreshes that install. So cleared local storage, or another computer signed into the same browser profile with sync on, keeps the same install: its purchases, email link, license seat and trial. A reinstall does not: Chrome deletes an extension’s storage.sync data on uninstall, so a reinstall is a new install that needs Restore purchases or the license key and can start a new install trial. Another browser or profile, sync turned off, or clearing both storage areas also creates a new install. Two devices that register before sync propagates can still end up as two installs. Sync failures are ignored and the SDK uses local storage only.

Do not write to these keys, and avoid clearing both chrome.storage.local and chrome.storage.sync: that makes the SDK register a brand-new install. Remove your own keys individually instead.