Building a Browser Extension with WXT
Build a cross-browser extension with WXT and TypeScript. Create a popup, sync settings with content scripts, run Chrome and Firefox builds, and package for stores.
WXT is an open-source, MIT-licensed framework that bundles browser extensions with Vite, generates manifest.json from the files in your entrypoints/ directory, and builds Chrome, Firefox, Edge and Safari versions from one codebase.
If you have built an extension by hand, you know the routine: edit manifest.json, click reload on chrome://extensions, refresh the tab, and then repeat the whole thing for Firefox with a slightly different manifest. WXT replaces that loop with a Vite-style workflow.
In this guide you build a small “Link Highlighter” extension in plain TypeScript. It has a popup toggle, a content script that outlines every link, and a stored setting that updates open tabs immediately. You then run it in dev mode in Chrome and Firefox and package it for each store, including the Firefox sources ZIP and the Safari app wrapper.
Key Takeaways
- A WXT project has no hand-written
manifest.json. WXT builds it from your entrypoint files plus themanifestkey inwxt.config.ts. - By default, WXT builds Manifest V3 for Chrome and other Chromium browsers and Manifest V2 for Firefox and Safari. The
--mv2and--mv3flags override that. storage.defineItembinds a prefixed key such aslocal:highlightLinksto a type and a fallback value. Itswatchmethod fires in every extension context whenever that key changes.wxt zip -b firefoxproduces two archives: the extension, and a sources ZIP that Mozilla reviewers use to rebuild and compare your add-on.- WXT builds a Safari target but does not publish it. You wrap the output in a native app with Xcode’s
xcrun safari-web-extension-packager.
What Is WXT and What Does It Replace?
WXT is a build framework for web extensions. It treats each file in entrypoints/ as part of the extension and writes the manifest for you. Code goes through Vite, HTML pages get hot module replacement in dev mode, and one -b flag switches the target browser. This walkthrough uses WXT 0.21.5 from npm. WXT is still pre-1.0, so check the upgrade guide before you bump versions.
The manifest is generated. Global fields such as name and permissions go under the manifest key in wxt.config.ts. Entrypoint options live in the entrypoint file. The final file lands in .output/{target}/manifest.json. If the manifest fields themselves are new to you, read Chrome Extensions for Beginners and Chrome Extension Manifest V3 Explained first.
Create the WXT Project
To create a WXT project, scaffold it with the init command and pick the vanilla template:
npx wxt@latest init link-highlighter --template vanilla
cd link-highlighter
npm install
The installation guide also lists pnpm dlx wxt@latest init and bunx wxt@latest init. The scaffolded postinstall script runs wxt prepare, which generates the TypeScript types and auto-import declarations. Vue, React and Svelte templates are also available if you want a UI framework.
Delete the starter entrypoints/background.ts and entrypoints/content.ts. This extension needs no background script, because the popup and the content script talk to each other through storage.
Entrypoints and Naming Rules
WXT works out what each entrypoint does from its filename. The table shows the three this project uses:
| Source path | Generated as |
|---|---|
entrypoints/popup/index.html (or popup.html) | Toolbar action popup |
entrypoints/background.ts | Background script (service worker in MV3) |
entrypoints/content/index.ts, content.ts or {name}.content.ts | Content script |
The entrypoints guide sets three rules:
- No loose helper files in
entrypoints/. WXT treats every file there as an entrypoint, so put shared code inutils/or inside an entrypoint’s own directory. - Runtime code goes inside
main. WXT imports background and content script files in Node.js at build time to read their options, so any code that touches the DOM or extension APIs must sit insidemain. - Entrypoints are at most one directory deep.
Here is the “runtime code goes inside main” rule in practice:
// Wrong: runs at build time in Node, where `document` doesn't exist
const links = document.querySelectorAll('a');
export default defineContentScript({
matches: ['*://*.wikipedia.org/*'],
main() {
// Right: runs only in the page
const links = document.querySelectorAll('a');
},
});
Build the Popup Toggle
The popup is an HTML entrypoint. Its <title> sets the action title, and <meta name="manifest.*"> tags set other popup manifest options. Replace the files in entrypoints/popup/ with these:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Link Highlighter</title>
</head>
<body>
<label><input type="checkbox" id="toggle" /> Highlight links</label>
<script type="module" src="./main.ts"></script>
</body>
</html>
// entrypoints/popup/main.ts
import { highlightLinks } from '@/utils/settings';
async function init() {
const toggle = document.querySelector<HTMLInputElement>('#toggle')!;
toggle.checked = await highlightLinks.getValue();
toggle.addEventListener('change', () => highlightLinks.setValue(toggle.checked));
}
init();
The Link Highlighter popup reads the current value when it opens and writes on every change. It never messages the tab. The content script listens to storage instead.
Highlight Links with a Content Script
Use the directory form, entrypoints/content/, so the stylesheet can sit next to the script. A loose CSS file in entrypoints/ would become its own entrypoint. Importing CSS in a content script adds the file to that script’s css array in the manifest.
/* entrypoints/content/style.css */
html.wxt-link-highlight a {
outline: 2px solid #f59e0b;
background-color: rgba(245, 158, 11, 0.15);
}
Toggling a single class on <html> is simpler than looping over anchors. It also covers links the page adds after load, because the selector matches them automatically. The matches pattern below limits the script to Wikipedia. Widen it only when you have to, because broad host patterns trigger stronger permission warnings at install time.
// entrypoints/content/index.ts
import './style.css';
import { highlightLinks } from '@/utils/settings';
export default defineContentScript({
matches: ['*://*.wikipedia.org/*'],
async main(ctx) {
const apply = (on: boolean) =>
document.documentElement.classList.toggle('wxt-link-highlight', on);
apply(await highlightLinks.getValue());
const unwatch = highlightLinks.watch((on) => apply(on));
ctx.onInvalidated(unwatch);
},
});
Store the Setting with storage.defineItem
storage.defineItem ties a prefixed key to a type and a fallback value. Its watch callback receives the new value whenever the key changes, no matter which part of the extension wrote it. Put the item in utils/ so both entrypoints can import it:
// utils/settings.ts
import { storage } from '#imports';
export const highlightLinks = storage.defineItem<boolean>('local:highlightLinks', {
fallback: false,
});
The WXT storage API requires an area prefix (local:, session:, sync: or managed:). With fallback set, getValue returns false instead of null when nothing has been saved yet. Import storage from #imports. In v0.20 the older wxt/storage path became wxt/utils/storage, which #imports re-exports. Then add the permission:
// wxt.config.ts
import { defineConfig } from 'wxt';
export default defineConfig({
manifest: {
name: 'Link Highlighter',
permissions: ['storage'],
},
});
In the content script, one apply function handles both the initial read and every watch event, so switching highlighting off and back on works without a page reload. Passing unwatch to ctx.onInvalidated removes the listener when the extension is reloaded or updated. WXT’s own UI helpers clean up the same way. If you need extension APIs directly, import browser from wxt/browser. It re-exports the browser’s native global.
Run Dev Mode in Chrome and Firefox
wxt starts dev mode for Chrome and wxt -b firefox starts it for Firefox. Both rebuild when you save:
npm run dev # wxt
npm run dev:firefox # wxt -b firefox
Since v0.21, web-ext is an optional peer dependency, and WXT opens a browser with the extension loaded only when web-ext is installed. Projects created with wxt init, like this one, include it in package.json, so the browser opens automatically. If you remove it, load the dev output from .output/ manually. Dev builds go to a separate directory with a -dev suffix. Popup changes hot-reload, content script edits re-register just that script, and background edits reload the whole extension. The manifest docs explain why dev builds add the tabs and scripting permissions: they support reloading, and they don’t appear in production builds.
How Do You Package a WXT Extension for Each Store?
WXT writes production builds to .output/chrome-mv3 and .output/firefox-mv2. The target-browsers guide documents the per-browser manifest defaults.
| Target | Build | Package |
|---|---|---|
| Chrome / Edge | wxt build | wxt zip |
| Firefox | wxt build -b firefox | wxt zip -b firefox |
| Safari | wxt build -b safari | xcrun safari-web-extension-packager |
Upload the wxt zip output to the Chrome Web Store. The publishing guide notes that Edge Add-ons accepts the same ZIP.
Firefox Add-ons and the Sources ZIP
wxt zip -b firefox writes {name}-{packageVersion}-firefox.zip and {name}-{packageVersion}-sources.zip. Mozilla requires the sources archive for bundled code so reviewers can rebuild your add-on and compare the result with your upload. Include a README with the install command and npm run zip:firefox. Then unzip the sources, rebuild, and confirm the output matches, because .env files can change chunk hashes. The Firefox build is a standard WebExtension, which is also what Firefox-based browsers load (see 6 Firefox Forks Worth Trying in 2026).
Safari
WXT does not package or publish Safari extensions. Run wxt build -b safari (MV2 by default), then run xcrun safari-web-extension-packager .output/safari-mv2 to generate the native app wrapper that Safari requires. You build, sign and submit that app through Xcode yourself.
Next Steps
With WXT, a cross-browser extension comes down to a few file conventions. Entrypoint filenames define the manifest, storage items with watch keep the popup and content scripts in sync, and -b selects the browser for every command. Run npm run zip:firefox on this project, rebuild from the generated sources archive, and confirm the output matches before your first Add-ons submission.
FAQs
Does WXT still use webextension-polyfill?
No. WXT v0.20 removed webextension-polyfill, and the browser object from wxt/browser now re-exports the browser's native browser or chrome global, with types based on @types/chrome. To keep the polyfill, install webextension-polyfill and @wxt-dev/webextension-polyfill, then add '@wxt-dev/webextension-polyfill' to the modules array in wxt.config.ts.
Can the main function in a WXT background script be async?
No. The main function passed to defineBackground cannot be async, because a Manifest V3 service worker must register its extension listeners synchronously when it starts. Register listeners first, then handle async work with .then chains or inside the listener callbacks. Content script main functions have no such limit and can be async, which is why the Link Highlighter content script awaits its storage read.
Why does a WXT dev build include a background script when the project has none?
WXT adds a minimal background script to dev builds when a project defines no background entrypoint, because dev mode needs it to reload the extension when files are saved. Production output from wxt build contains no background script in that case, so an extension built without a background entrypoint ships to the stores without one.
Can WXT submit an extension to the browser stores automatically?
Yes, for the Chrome Web Store, Edge Add-ons and Firefox Add-ons. Run wxt submit init once to save store credentials to a .env.submit file, then pass the ZIPs from wxt zip and wxt zip -b firefox to wxt submit, with the sources archive under --firefox-sources-zip. You have to upload to each store by hand the first time. Safari is not supported.
Gain Debugging Superpowers
Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.
Star on GitHub12k