Every "build an AI Chrome extension" tutorial ends in the same place: a popup, a textarea, a fetch to OpenAI, and document.body.innerHTML = answer.
That is an afternoon. The other ninety percent — the part between "works on my machine" and "someone pays for it" — is where the extension actually gets built: a side panel that doesn't lose its stream when React re-renders, page text that doesn't feel like surveillance, permissions a reviewer will approve, and a licence that can't be forged in localStorage.
I rebuilt that shape and shipped it as a starter kit. This post is the structure, with the decisions and the code that matter. You can follow it without buying anything: the three Vite configs, the message router and the SSE parser below are the whole trick.
Three runtimes, three bundles
Manifest V3 gives you three different execution environments, and Vite's defaults are designed for none of them.
| Runtime | Module rules | What that means for the build |
|---|---|---|
| Side panel, popup | normal documents | ESM, code splitting, CSS files, React |
| Background service worker | started and stopped by the browser | one self-contained file; no runtime chunk imports |
| Content script | classic script in the page | no ESM syntax, no extension-scoped dynamic import() |
So the build is three configs. One command runs them in order:
"scripts": { "typecheck": "tsc --noEmit", "clean": "node scripts/clean.mjs", "build": "npm run typecheck && npm run clean && vite build && vite build --config vite.background.config.ts && vite build --config vite.content.config.ts" } The page build is ordinary Vite with two HTML inputs:
// vite.config.ts export default defineConfig({ plugins: [react()], build: { outDir: 'dist', emptyOutDir: true, // the only build allowed to clear dist/ target: 'chrome116', rollupOptions: { input: { sidepanel: 'sidepanel.html', popup: 'popup.html' }, output: { entryFileNames: 'assets/[name]-[hash].js', chunkFileNames: 'assets/[name]-[hash].js', assetFileNames: 'assets/[name]-[hash][extname]', }, }, }, }) The worker and the content script are library builds with a single output file:
// vite.background.config.ts export default defineConfig({ publicDir: false, build: { outDir: 'dist', emptyOutDir: false, // never delete what the page build wrote target: 'chrome116', minify: 'esbuild', lib: { entry: 'src/background/index.ts', formats: ['iife'], name: 'PagePilotBackground', fileName: () => 'background.js', }, }, }) emptyOutDir: false is not cosmetic. It is the difference between a build folder with three bundles and a build folder with one bundle and two 404s.
Why IIFE for the worker, when MV3 supports "type": "module"? Because a module worker imports its chunks at runtime. Ship an update, and a worker that wakes up to a stale chunk reference fails in a way you will only hear about from users. One file has no such failure mode, and it costs nothing at this size.
The manifest is the product decision
Five permissions, and a reason for each:
"permissions": ["sidePanel", "storage", "contextMenus", "activeTab", "scripting"], "host_permissions": ["https://api.openai.com/*"], "optional_host_permissions": ["https://*/*", "http://localhost/*"], "minimum_chrome_version": "116", "side_panel": { "default_path": "sidepanel.html" } sidePanel needs Chrome 116. activeTab + scripting exist so I can inject the content script on demand into a tab that was already open when the extension was installed — the classic "Receiving end does not exist" case. contextMenus is the right-click "Ask about this selection".
The interesting one is host access. Declaring https://*/* up front turns the Web Store permission justification into fiction, and reviewers are good at spotting fiction. Instead the extension declares only the default provider and asks for the origin the user actually configures:
export async function ensureHostPermission(baseUrl: string): Promise<boolean> { const origin = new URL(baseUrl).origin const pattern = `${origin}/*` if (await chrome.permissions.contains({ origins: [pattern] })) return true return chrome.permissions.request({ origins: [pattern] }) } Chrome shows that prompt only in response to a user gesture, which is exactly where it belongs: the moment someone pastes their OpenRouter or Ollama base URL.
One message union, one request helper
Four contexts talking to each other is where untyped extension code rots. A single discriminated union fixes it, because TypeScript then refuses a sendMessage the worker cannot answer:
export type ExtensionMessage = | { type: 'PING' } | { type: 'EXTRACT_PAGE' } | { type: 'GET_SELECTION' } | { type: 'OPEN_SIDE_PANEL'; tabId?: number } | { type: 'GET_SETTINGS' } | { type: 'SET_SETTINGS'; patch: Partial<Settings> } | { type: 'GET_LICENSE' } | { type: 'SAVE_LICENSE'; license: LicenseState } | { type: 'VERIFY_LICENSE' } | { type: 'CONSUME_CREDIT' } | { type: 'RESET_CREDITS' } | { type: 'CLEAR_HISTORY' } | { type: 'PENDING_SELECTION'; selection: string } export interface ExtensionMessageResponse { ok: boolean error?: string data?: unknown } Every reply is { ok, data | error }, and one helper unwraps it so no call site has to remember:
export async function sendToBackground<T>(message: ExtensionMessage): Promise<T> { const response = (await chrome.runtime.sendMessage(message)) as ExtensionMessageResponse | undefined if (!response) throw new Error('The background worker did not respond. Reload the extension.') if (!response.ok) throw new Error(response.error ?? 'Unknown extension error.') return response.data as T } Two things worth copying: the "worker did not respond" case is real (a suspended service worker, a reloaded extension) and deserves its own message rather than undefined is not an object; and chrome.runtime.sendMessage returns undefined rather than throwing when no receiver exists.
Streaming into a side panel
The panel renders tokens; the worker owns nothing about the stream. Two details cost me a day each.
Frames arrive split. SSE is delimited by a blank line, and a network chunk can end in the middle of a token. Keep a buffer, cut on \n\n, keep the remainder.
Providers send noise. Keep-alives that don't parse, \r\n, and [DONE].
const reader = response.body.getReader() const decoder = new TextDecoder() let buffer = '' while (true) { const { done, value } = await reader.read() if (done) break buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n') let boundary = buffer.indexOf('\n\n') while (boundary !== -1) { const event = buffer.slice(0, boundary) buffer = buffer.slice(boundary + 2) for (const line of event.split('\n')) { if (!line.startsWith('data:')) continue const data = line.slice(5).trim() if (data === '[DONE]') return try { const delta = JSON.parse(data).choices?.[0]?.delta?.content if (delta) yield delta } catch { /* keep-alive or provider-specific frame */ } } boundary = buffer.indexOf('\n\n') } } Stop is an AbortController passed into fetch, and the generator checks signal.aborted before each yield so a stopped answer cannot keep writing into a closed panel.
The other trap is React: appending to a string in state on every token re-renders the whole panel a few hundred times per answer. Buffer the incoming text in a ref and flush on animation frames. The stream looks the same and the CPU graph stops looking like a mountain range.
Page text without the creep
A content script is injected on every http(s) page, so it must do nothing until asked. Mine registers a handler and stops:
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { if (message.type !== 'EXTRACT_PAGE') return false sendResponse(extractPageContext()) return true }) Extraction is deliberately boring and predictable:
- find
article/mainwhen it exists, fall back tobody - drop
script,style,nav,footer,aside,form - skip anything CSS-hidden (
display: none,visibility: hidden) - keep block-level newlines so paragraphs don't fuse into one wall
- cut at a character budget (
14000by default, a setting)
The budget matters more than the algorithm. A whole page of comments is worse context than the article, and it costs tokens either way.
Licences and money
A paid extension needs three honest states, not two:
- demo — no key, the built-in offline engine answers, so the extension works on first install
- unverified — a key is present but no licence server is configured yet
- pro — the server answered: active, expired or revoked
The client never decides that a key is valid. It normalises it (PPAI-9K3M-7QP2-XR4T), sends the key plus a device id to POST /api/license/verify, and stores the expiry the server returns. Activation limits live server-side, so a key cannot be shared by copying a JSON blob.
Server side, the minimum that is actually correct: POST /api/checkout creates a Checkout Session; the webhook verifies the raw body signature, records the event id before fulfilling anything, mints the key once per session, and is safe to retry. That last part is the whole difference between a launch and an incident.
The offline engine earns its place beyond the demo: it is what lets a store reviewer test the extension without an API key. A reviewer who cannot get a first successful answer rejects the listing for being non-functional — and they are right to.
What store review actually rejects
Not "it uses AI". In my reading of the rejections that hit AI extensions: remote code, unexplained host permissions, a first run that does nothing, and a privacy policy that doesn't match the data flow. This structure avoids all four by construction — no remote code, runtime host access, an offline first run, and a PRIVACY.md written to publish nearly verbatim.
What I would do differently
- Start with the message union, not the UI. I wrote the panel first and spent a day retrofitting types into the worker.
- Budget the page text before choosing a model. Context size is a product decision, not a model setting.
- Build the licence server before the paywall. The demo/paywall boundary is much easier to design once the verify endpoint already exists.
If you want the finished version of all of this — side panel, streaming, extraction, credits, the Express + Stripe licence backend, and the store-submission guide — it is packaged as PagePilot AI, $29 (30% off with LAUNCH30 during launch): https://seoyyy.gumroad.com/l/chrome-ai-extension-starter/LAUNCH30
If you only take the three Vite configs, take those. They are the part that took longest to get right.

