# WXT Browser Extension Architecture Patterns

## Executive Summary

This document provides comprehensive guidance on browser extension architecture patterns using the WXT framework, with emphasis on Manifest V3 migration strategies, cross-browser compatibility, state management, and messaging patterns. Based on 2025 industry best practices and production-proven implementations, this guide equips development teams with actionable patterns for building robust, maintainable, and performant browser extensions.

### Key Findings

- **Manifest V3 Migration**: WXT abstracts MV3 complexity through automatic manifest generation and service worker patterns
- **File-Based Architecture**: Entrypoint-driven development eliminates manual configuration and reduces errors
- **Context-Aware Content Scripts**: Built-in invalidation tracking prevents orphaned script execution
- **Unified Storage API**: Type-safe storage abstraction works across all browser storage types
- **Module System**: Reusable code patterns via WXT modules reduce duplication across extensions

### Strategic Recommendations

1. **Adopt file-based entrypoint organization** - Leverage WXT's automatic manifest generation
2. **Implement context-aware content scripts** - Use WXT's context API for lifecycle management
3. **Use type-safe messaging patterns** - Define message contracts for reliability
4. **Leverage storage abstraction** - Use WXT's storage API for cross-browser compatibility
5. **Create WXT modules for shared logic** - Maximize code reuse across entrypoints and projects

---

## Current State Analysis

### Extension Architecture Evolution

#### Traditional Extension Development (Pre-2025)

**Challenges**:
- Manual manifest.json management prone to errors
- Complex build configurations
- Browser-specific API differences
- No hot reload for content/background scripts
- Difficult testing setup

**Example Traditional Structure**:
```
extension/
├── manifest.json          # Manual configuration
├── background.js          # Plain JavaScript
├── content.js            # Injected script
├── popup.html            # UI page
└── assets/               # Static files
```

#### Modern WXT Architecture (2025)

**Improvements**:
- Automatic manifest generation from entrypoints
- TypeScript-first with type safety
- Vite-powered build system with HMR
- Unified browser API wrapper
- Integrated testing infrastructure
- Module system for code reuse

**WXT Structure**:
```
extension/
├── entrypoints/          # Auto-detected entrypoints
│   ├── background.ts     # Service worker (MV3)
│   ├── content/
│   │   ├── index.ts     # Main content script
│   │   └── overlay.ts   # Additional content script
│   ├── popup/
│   │   ├── index.html   # Popup page
│   │   ├── main.tsx     # React/Vue entry
│   │   └── App.tsx      # UI component
│   └── options.html     # Options page
├── components/          # Shared UI components
├── utils/              # Shared utilities
├── modules/            # Local WXT modules
├── public/             # Static assets
├── wxt.config.ts       # Build configuration
└── package.json        # Dependencies
```

### Manifest V3 Architecture Changes

#### Key Differences from Manifest V2

| Aspect | Manifest V2 | Manifest V3 |
|--------|-------------|-------------|
| Background | Persistent background page | Service worker (event-driven) |
| Remote Code | Allowed with CSP | Completely forbidden |
| Host Permissions | Broad permissions | Granular, user-controlled |
| Cross-Origin Requests | Via XHR | Must declare in host_permissions |
| Web Accessible Resources | Simple array | Object with resource mapping |
| Content Security Policy | Single string | Object structure |
| Action API | browserAction/pageAction | Single action API |

#### WXT's MV3 Abstraction

WXT automatically handles MV3 migration:

```typescript
// WXT automatically generates appropriate manifest
// Developer writes same code for MV2 and MV3

export default defineBackground(() => {
  // WXT adapts this to service worker in MV3
  // and background page in MV2
  console.log('Background initialized');
});
```

**Generated Manifest (MV3)**:
```json
{
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js",
    "type": "module"
  }
}
```

**Generated Manifest (MV2)**:
```json
{
  "manifest_version": 2,
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  }
}
```

---

## Best Practices

### 1. Entrypoint Patterns

#### Background Script (Service Worker)

**Basic Pattern**:
```typescript
// entrypoints/background.ts
export default defineBackground(() => {
  console.log('Extension loaded');

  // Event listeners (service worker stays dormant until event)
  browser.runtime.onInstalled.addListener(handleInstall);
  browser.runtime.onMessage.addListener(handleMessage);
  browser.tabs.onUpdated.addListener(handleTabUpdate);
});

function handleInstall(details: browser.runtime.OnInstalledDetailsType) {
  if (details.reason === 'install') {
    // First install
    browser.tabs.create({ url: '/welcome.html' });
  } else if (details.reason === 'update') {
    // Extension updated
    console.log('Updated from', details.previousVersion);
  }
}

function handleMessage(
  message: any,
  sender: browser.runtime.MessageSender,
  sendResponse: (response?: any) => void
) {
  // Handle async operations
  handleMessageAsync(message, sender).then(sendResponse);
  return true; // Keep channel open for async response
}

async function handleMessageAsync(
  message: any,
  sender: browser.runtime.MessageSender
) {
  // Validate sender
  if (sender.id !== browser.runtime.id) {
    throw new Error('Invalid sender');
  }

  // Route messages
  switch (message.type) {
    case 'GET_DATA':
      return await fetchData(message.payload);
    case 'UPDATE_SETTINGS':
      return await updateSettings(message.payload);
    default:
      throw new Error(`Unknown message type: ${message.type}`);
  }
}

function handleTabUpdate(
  tabId: number,
  changeInfo: browser.tabs.OnUpdatedChangeInfoType,
  tab: browser.tabs.Tab
) {
  if (changeInfo.status === 'complete' && tab.url) {
    // Tab finished loading
    console.log('Tab loaded:', tab.url);
  }
}
```

**Service Worker Best Practices**:
```typescript
// Service workers are event-driven and ephemeral
// Avoid global state - use storage instead

// ❌ Bad: Global state lost when service worker terminates
let cachedData: any;

export default defineBackground(() => {
  browser.runtime.onMessage.addListener(async (message) => {
    if (message.type === 'GET_CACHED') {
      return cachedData; // May be undefined!
    }
  });
});

// ✅ Good: Use storage for persistence
import { storage } from 'wxt/storage';

const cache = storage.defineItem<any>('local:cache');

export default defineBackground(() => {
  browser.runtime.onMessage.addListener(async (message) => {
    if (message.type === 'GET_CACHED') {
      return await cache.getValue();
    }
  });
});
```

#### Content Script Patterns

**Basic Content Script**:
```typescript
// entrypoints/content.ts
export default defineContentScript({
  matches: ['*://*.example.com/*'],
  runAt: 'document_end',

  main(ctx) {
    // Context-aware execution
    console.log('Content script running');

    // Use context for cleanup
    ctx.addEventListener(document, 'click', handleClick);

    // Context-aware timers
    ctx.setInterval(() => {
      if (ctx.isInvalid) {
        console.log('Context invalidated, stopping');
        return;
      }
      checkForUpdates();
    }, 5000);
  },
});

function handleClick(event: MouseEvent) {
  const target = event.target as HTMLElement;
  if (target.matches('.special-button')) {
    console.log('Special button clicked');
  }
}

function checkForUpdates() {
  // Check page for changes
}
```

**Multiple Content Scripts Pattern**:
```typescript
// entrypoints/content/main.ts - Core functionality
export default defineContentScript({
  matches: ['*://*.example.com/*'],
  runAt: 'document_end',
  main() {
    console.log('Main content script');
    // Core extension logic
  },
});

// entrypoints/content/overlay.ts - UI overlay
export default defineContentScript({
  matches: ['*://*.example.com/*'],
  runAt: 'document_idle',
  main() {
    console.log('Overlay content script');
    createOverlay();
  },
});

// entrypoints/content/injector.ts - Page script injection
export default defineContentScript({
  matches: ['*://*.example.com/*'],
  runAt: 'document_start',
  world: 'MAIN', // Inject into page context
  main() {
    // Code runs in page context, not extension context
    window.myExtensionAPI = {
      version: '1.0.0',
    };
  },
});
```

**Content Script with UI Injection**:
```typescript
// entrypoints/content/ui.ts
import { createShadowRootUi } from 'wxt/client';

export default defineContentScript({
  matches: ['*://*.example.com/*'],

  async main(ctx) {
    const ui = await createShadowRootUi(ctx, {
      name: 'extension-overlay',
      position: 'inline',
      anchor: 'body',
      append: 'first',
      onMount: (container) => {
        // React example
        const root = ReactDOM.createRoot(container);
        root.render(<OverlayApp />);
        return root;
      },
      onRemove: (root) => {
        root?.unmount();
      },
    });

    ui.mount();
  },
});
```

#### Popup and Options Pages

**Popup with Framework (React)**:
```tsx
// entrypoints/popup/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Extension Popup</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="./main.tsx"></script>
  </body>
</html>

// entrypoints/popup/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { PopupApp } from './PopupApp';
import './popup.css';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <PopupApp />
  </React.StrictMode>
);

// entrypoints/popup/PopupApp.tsx
import { useState, useEffect } from 'react';
import { storage } from 'wxt/storage';

export function PopupApp() {
  const [settings, setSettings] = useState({ theme: 'light' });

  useEffect(() => {
    // Load settings on mount
    storage.getItem('local:settings').then(setSettings);
  }, []);

  const updateTheme = async (theme: string) => {
    const newSettings = { ...settings, theme };
    setSettings(newSettings);
    await storage.setItem('local:settings', newSettings);
  };

  return (
    <div className="popup">
      <h1>Extension Settings</h1>
      <button onClick={() => updateTheme('dark')}>Dark Theme</button>
      <button onClick={() => updateTheme('light')}>Light Theme</button>
    </div>
  );
}
```

**Options Page (Vue)**:
```vue
<!-- entrypoints/options/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Extension Options</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.ts"></script>
  </body>
</html>

<!-- entrypoints/options/main.ts -->
import { createApp } from 'vue';
import OptionsApp from './OptionsApp.vue';
import './options.css';

createApp(OptionsApp).mount('#app');

<!-- entrypoints/options/OptionsApp.vue -->
<template>
  <div class="options">
    <h1>Extension Options</h1>
    <form @submit.prevent="saveSettings">
      <label>
        API Key:
        <input v-model="settings.apiKey" type="password" />
      </label>
      <label>
        Enable Notifications:
        <input v-model="settings.notifications" type="checkbox" />
      </label>
      <button type="submit">Save Settings</button>
    </form>
    <p v-if="saved">Settings saved!</p>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { storage } from 'wxt/storage';

interface Settings {
  apiKey: string;
  notifications: boolean;
}

const settings = ref<Settings>({
  apiKey: '',
  notifications: true,
});
const saved = ref(false);

onMounted(async () => {
  const stored = await storage.getItem<Settings>('local:settings');
  if (stored) settings.value = stored;
});

async function saveSettings() {
  await storage.setItem('local:settings', settings.value);
  saved.value = true;
  setTimeout(() => saved.value = false, 2000);
}
</script>
```

### 2. Messaging Patterns

#### Type-Safe Messaging Architecture

**Message Type Definitions**:
```typescript
// utils/messages.ts
export interface MessageMap {
  // Format: 'MESSAGE_TYPE': { request: RequestType; response: ResponseType }
  'GET_USER_DATA': {
    request: { userId: string };
    response: { name: string; email: string };
  };
  'UPDATE_SETTINGS': {
    request: { settings: UserSettings };
    response: { success: boolean };
  };
  'SEARCH': {
    request: { query: string };
    response: { results: SearchResult[] };
  };
  'PING': {
    request: void;
    response: 'PONG';
  };
}

export type MessageType = keyof MessageMap;

export interface Message<T extends MessageType = MessageType> {
  type: T;
  payload: MessageMap[T]['request'];
  requestId?: string;
}

export interface MessageResponse<T extends MessageType = MessageType> {
  success: boolean;
  data?: MessageMap[T]['response'];
  error?: string;
  requestId?: string;
}
```

**Message Sender (Content Script)**:
```typescript
// utils/messaging.ts
export async function sendMessage<T extends MessageType>(
  type: T,
  payload: MessageMap[T]['request']
): Promise<MessageMap[T]['response']> {
  const message: Message<T> = {
    type,
    payload,
    requestId: crypto.randomUUID(),
  };

  try {
    const response = await browser.runtime.sendMessage(message);

    if (!response.success) {
      throw new Error(response.error || 'Message failed');
    }

    return response.data;
  } catch (error) {
    console.error('Message error:', error);
    throw error;
  }
}

// Usage in content script
const userData = await sendMessage('GET_USER_DATA', { userId: '123' });
console.log(userData.name, userData.email); // Type-safe!
```

**Message Receiver (Background Script)**:
```typescript
// entrypoints/background.ts
import type { Message, MessageResponse, MessageType } from '@/utils/messages';

export default defineBackground(() => {
  browser.runtime.onMessage.addListener(handleMessage);
});

function handleMessage(
  message: Message,
  sender: browser.runtime.MessageSender,
  sendResponse: (response: MessageResponse) => void
) {
  // Validate sender
  if (sender.id !== browser.runtime.id) {
    sendResponse({
      success: false,
      error: 'Invalid sender',
      requestId: message.requestId,
    });
    return false;
  }

  // Handle async
  handleMessageAsync(message, sender)
    .then((data) => {
      sendResponse({
        success: true,
        data,
        requestId: message.requestId,
      });
    })
    .catch((error) => {
      sendResponse({
        success: false,
        error: error.message,
        requestId: message.requestId,
      });
    });

  return true; // Keep channel open
}

async function handleMessageAsync(
  message: Message,
  sender: browser.runtime.MessageSender
) {
  switch (message.type) {
    case 'GET_USER_DATA':
      return await getUserData(message.payload);

    case 'UPDATE_SETTINGS':
      return await updateSettings(message.payload);

    case 'SEARCH':
      return await performSearch(message.payload);

    case 'PING':
      return 'PONG';

    default:
      throw new Error(`Unknown message type: ${message.type}`);
  }
}

async function getUserData(payload: { userId: string }) {
  // Fetch user data
  return {
    name: 'John Doe',
    email: 'john@example.com',
  };
}

async function updateSettings(payload: { settings: any }) {
  await storage.setItem('local:settings', payload.settings);
  return { success: true };
}

async function performSearch(payload: { query: string }) {
  // Perform search
  return { results: [] };
}
```

#### Content Script ↔ Background Communication

**Bi-directional Communication**:
```typescript
// Content script sends to background
const response = await browser.runtime.sendMessage({
  type: 'GET_DATA',
  payload: { id: '123' },
});

// Background sends to specific tab
await browser.tabs.sendMessage(tabId, {
  type: 'UPDATE_UI',
  payload: { data: newData },
});

// Background sends to all tabs
const tabs = await browser.tabs.query({});
for (const tab of tabs) {
  if (tab.id) {
    await browser.tabs.sendMessage(tab.id, {
      type: 'REFRESH',
    });
  }
}
```

**Long-Lived Connections**:
```typescript
// Content script establishes connection
const port = browser.runtime.connect({ name: 'content-connection' });

port.onMessage.addListener((message) => {
  console.log('Received from background:', message);
});

port.postMessage({ type: 'HELLO' });

// Cleanup
port.onDisconnect.addListener(() => {
  console.log('Connection closed');
});

// Background handles connection
browser.runtime.onConnect.addListener((port) => {
  if (port.name === 'content-connection') {
    port.onMessage.addListener((message) => {
      console.log('Received from content:', message);

      // Send response
      port.postMessage({ type: 'RESPONSE', data: 'processed' });
    });

    port.onDisconnect.addListener(() => {
      console.log('Content script disconnected');
    });
  }
});
```

### 3. Storage Patterns

#### WXT Storage API

**Basic Storage Operations**:
```typescript
import { storage } from 'wxt/storage';

// Define typed storage item
interface UserPreferences {
  theme: 'light' | 'dark';
  language: string;
  notifications: boolean;
}

const preferences = storage.defineItem<UserPreferences>('local:preferences', {
  fallback: {
    theme: 'light',
    language: 'en',
    notifications: true,
  },
});

// Get value
const prefs = await preferences.getValue();
console.log(prefs.theme);

// Set value
await preferences.setValue({
  theme: 'dark',
  language: 'es',
  notifications: false,
});

// Remove value
await preferences.removeValue();

// Watch for changes
preferences.watch((newValue, oldValue) => {
  console.log('Preferences changed:', { old: oldValue, new: newValue });
});
```

**Storage Scopes**:
```typescript
// Local storage (browser profile specific)
const localData = storage.defineItem('local:userData');

// Sync storage (synchronized across devices)
const syncSettings = storage.defineItem('sync:settings');

// Session storage (temporary, cleared on browser close)
const sessionState = storage.defineItem('session:currentState');

// Managed storage (read-only, set by administrator)
const managedConfig = storage.defineItem('managed:enterpriseConfig');
```

**Complex Storage Patterns**:
```typescript
// Cache with expiration
interface CachedData<T> {
  data: T;
  timestamp: number;
  expiresIn: number;
}

class StorageCache<T> {
  private item: WxtStorageItem<CachedData<T>>;

  constructor(key: string, expiresIn: number) {
    this.item = storage.defineItem<CachedData<T>>(`local:cache:${key}`);
    this.expiresIn = expiresIn;
  }

  async get(): Promise<T | null> {
    const cached = await this.item.getValue();
    if (!cached) return null;

    const age = Date.now() - cached.timestamp;
    if (age > cached.expiresIn) {
      await this.item.removeValue();
      return null;
    }

    return cached.data;
  }

  async set(data: T): Promise<void> {
    await this.item.setValue({
      data,
      timestamp: Date.now(),
      expiresIn: this.expiresIn,
    });
  }

  async clear(): Promise<void> {
    await this.item.removeValue();
  }
}

// Usage
const userCache = new StorageCache<UserData>('user', 5 * 60 * 1000); // 5 min

const userData = await userCache.get();
if (!userData) {
  const fresh = await fetchUserData();
  await userCache.set(fresh);
}
```

#### State Persistence Patterns

**Pinia Integration (Vue)**:
```typescript
// stores/settings.ts
import { defineStore } from 'pinia';
import { storage } from 'wxt/storage';

const storageItem = storage.defineItem<Settings>('local:settings', {
  fallback: {
    theme: 'light',
    language: 'en',
  },
});

export const useSettingsStore = defineStore('settings', {
  state: () => ({
    theme: 'light' as 'light' | 'dark',
    language: 'en',
    loading: false,
  }),

  actions: {
    async load() {
      this.loading = true;
      try {
        const stored = await storageItem.getValue();
        this.$patch(stored);
      } finally {
        this.loading = false;
      }
    },

    async save() {
      await storageItem.setValue({
        theme: this.theme,
        language: this.language,
      });
    },

    async setTheme(theme: 'light' | 'dark') {
      this.theme = theme;
      await this.save();
    },

    async setLanguage(language: string) {
      this.language = language;
      await this.save();
    },
  },
});

// Auto-persist on changes
storageItem.watch((newValue) => {
  const store = useSettingsStore();
  if (newValue) store.$patch(newValue);
});
```

**Zustand Integration (React)**:
```typescript
// stores/settings.ts
import create from 'zustand';
import { storage } from 'wxt/storage';

interface SettingsState {
  theme: 'light' | 'dark';
  language: string;
  setTheme: (theme: 'light' | 'dark') => Promise<void>;
  setLanguage: (language: string) => Promise<void>;
  load: () => Promise<void>;
}

const storageItem = storage.defineItem<{
  theme: 'light' | 'dark';
  language: string;
}>('local:settings', {
  fallback: {
    theme: 'light',
    language: 'en',
  },
});

export const useSettings = create<SettingsState>((set, get) => ({
  theme: 'light',
  language: 'en',

  setTheme: async (theme) => {
    set({ theme });
    await storageItem.setValue(get());
  },

  setLanguage: async (language) => {
    set({ language });
    await storageItem.setValue(get());
  },

  load: async () => {
    const stored = await storageItem.getValue();
    set(stored);
  },
}));

// Load on initialization
useSettings.getState().load();

// Watch for external changes
storageItem.watch((newValue) => {
  if (newValue) {
    useSettings.setState(newValue);
  }
});
```

### 4. Module System Patterns

#### Creating Reusable Modules

**Analytics Module**:
```typescript
// modules/analytics/index.ts
import { defineWxtModule } from 'wxt/modules';

export interface AnalyticsOptions {
  enabled: boolean;
  apiKey?: string;
  endpoint?: string;
}

export default defineWxtModule<AnalyticsOptions>({
  name: 'analytics',
  configKey: 'analytics',

  setup(wxt, options) {
    if (!options.enabled) return;

    // Add analytics script to background
    wxt.hooks.hook('build:manifestGenerated', (wxt, manifest) => {
      // Ensure permissions
      if (!manifest.permissions) manifest.permissions = [];
      if (!manifest.permissions.includes('storage')) {
        manifest.permissions.push('storage');
      }
    });

    // Generate runtime helpers
    wxt.hooks.hook('prepare:types', (wxt, entries) => {
      entries.push({
        path: wxt.config.outDir + '/analytics.d.ts',
        text: `
          export interface AnalyticsEvent {
            name: string;
            properties?: Record<string, any>;
          }

          export function trackEvent(event: AnalyticsEvent): Promise<void>;
          export function trackPageView(page: string): Promise<void>;
        `,
      });
    });

    // Add runtime implementation
    wxt.hooks.hook('build:publicAssets', async (wxt, assets) => {
      assets.push({
        path: 'analytics-runtime.js',
        contents: `
          export async function trackEvent(event) {
            if (!${options.enabled}) return;

            console.log('Track event:', event);

            // Send to analytics endpoint
            if (${JSON.stringify(options.endpoint)}) {
              await fetch(${JSON.stringify(options.endpoint)}, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  ...event,
                  timestamp: Date.now(),
                }),
              });
            }
          }

          export async function trackPageView(page) {
            await trackEvent({ name: 'page_view', properties: { page } });
          }
        `,
      });
    });
  },
});
```

**Usage**:
```typescript
// wxt.config.ts
export default defineConfig({
  modules: ['./modules/analytics'],
  analytics: {
    enabled: true,
    apiKey: 'your-api-key',
    endpoint: 'https://analytics.example.com/events',
  },
});

// In any entrypoint
import { trackEvent, trackPageView } from '#analytics-runtime';

await trackEvent({
  name: 'button_clicked',
  properties: { buttonId: 'submit' },
});

await trackPageView('/popup');
```

**Icons Module Example** (Simplified):
```typescript
// modules/auto-icons/index.ts
import { defineWxtModule } from 'wxt/modules';
import sharp from 'sharp';

export interface IconsOptions {
  source: string;
  sizes: number[];
}

export default defineWxtModule<IconsOptions>({
  name: 'auto-icons',
  configKey: 'icons',

  setup(wxt, options) {
    wxt.hooks.hook('build:publicAssets', async (wxt, assets) => {
      const sourceImage = path.resolve(wxt.config.root, options.source);

      // Generate icons for all sizes
      for (const size of options.sizes) {
        const buffer = await sharp(sourceImage)
          .resize(size, size)
          .png()
          .toBuffer();

        assets.push({
          path: `icon-${size}.png`,
          contents: buffer,
        });
      }
    });

    wxt.hooks.hook('build:manifestGenerated', (wxt, manifest) => {
      // Add icons to manifest
      manifest.icons = {};
      for (const size of options.sizes) {
        manifest.icons[size] = `icon-${size}.png`;
      }
    });
  },
});
```

### 5. Cross-Browser Compatibility Patterns

#### Browser-Specific Code

**Runtime Detection**:
```typescript
// utils/browser-detection.ts
export function getBrowserInfo() {
  const ua = navigator.userAgent;

  if (ua.includes('Chrome')) return { name: 'chrome', isChrome: true };
  if (ua.includes('Firefox')) return { name: 'firefox', isFirefox: true };
  if (ua.includes('Safari')) return { name: 'safari', isSafari: true };
  if (ua.includes('Edg')) return { name: 'edge', isEdge: true };

  return { name: 'unknown', isUnknown: true };
}

// Build-time detection
export const BROWSER = import.meta.env.BROWSER;
export const IS_CHROME = BROWSER === 'chrome';
export const IS_FIREFOX = BROWSER === 'firefox';
export const IS_SAFARI = BROWSER === 'safari';
export const IS_EDGE = BROWSER === 'edge';
```

**Conditional Logic**:
```typescript
import { IS_FIREFOX, IS_CHROME } from '@/utils/browser-detection';

export default defineBackground(() => {
  if (IS_FIREFOX) {
    // Firefox-specific initialization
    setupFirefoxFeatures();
  } else if (IS_CHROME) {
    // Chrome-specific initialization
    setupChromeFeatures();
  }

  // Common initialization
  setupCommonFeatures();
});

function setupFirefoxFeatures() {
  // Use Firefox-specific APIs
  if (browser.runtime.getBrowserInfo) {
    browser.runtime.getBrowserInfo().then(info => {
      console.log('Firefox version:', info.version);
    });
  }
}

function setupChromeFeatures() {
  // Use Chrome-specific APIs
  if (browser.sidePanel) {
    browser.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  }
}
```

**API Feature Detection**:
```typescript
// utils/feature-detection.ts
export function supportsAPI(apiPath: string): boolean {
  const parts = apiPath.split('.');
  let obj: any = browser;

  for (const part of parts) {
    if (!obj || !(part in obj)) return false;
    obj = obj[part];
  }

  return typeof obj !== 'undefined';
}

// Usage
if (supportsAPI('sidePanel.setPanelBehavior')) {
  // Use side panel API
  browser.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
}

if (supportsAPI('declarativeNetRequest')) {
  // Use declarativeNetRequest
  browser.declarativeNetRequest.updateDynamicRules({
    addRules: [/* rules */],
    removeRuleIds: [/* ids */],
  });
}
```

#### Manifest Customization per Browser

```typescript
// wxt.config.ts
export default defineConfig({
  manifest: ({ browser }) => {
    const base = {
      name: 'My Extension',
      version: '1.0.0',
      permissions: ['storage', 'tabs'],
    };

    if (browser === 'firefox') {
      return {
        ...base,
        browser_specific_settings: {
          gecko: {
            id: 'extension@example.com',
            strict_min_version: '109.0',
          },
        },
      };
    }

    if (browser === 'chrome') {
      return {
        ...base,
        minimum_chrome_version: '109',
      };
    }

    return base;
  },
});
```

### 6. Content Script Lifecycle Management

#### Context Invalidation Handling

**Why Context Invalidation Matters**:
When an extension updates or reloads, old content scripts become "orphaned" - they continue running but can't communicate with the background script. WXT's context API prevents bugs from orphaned scripts.

**Context-Aware Pattern**:
```typescript
export default defineContentScript({
  matches: ['*://*.example.com/*'],

  main(ctx) {
    // Check validity before operations
    function safeOperation() {
      if (ctx.isInvalid) {
        console.warn('Context invalidated, skipping operation');
        return;
      }

      // Perform operation
      performOperation();
    }

    // Context-aware event listeners (auto-cleanup)
    ctx.addEventListener(document, 'click', (event) => {
      if (ctx.isInvalid) return;
      handleClick(event);
    });

    // Context-aware intervals (auto-cleanup)
    ctx.setInterval(() => {
      if (ctx.isInvalid) return;
      checkForChanges();
    }, 5000);

    // Context-aware timeouts (auto-cleanup)
    ctx.setTimeout(() => {
      if (ctx.isInvalid) return;
      delayedAction();
    }, 1000);

    // Manual cleanup on invalidation
    ctx.onInvalidated(() => {
      console.log('Context invalidated, cleaning up');
      cleanup();
    });
  },
});

function performOperation() {
  console.log('Performing operation');
}

function handleClick(event: MouseEvent) {
  console.log('Click handled');
}

function checkForChanges() {
  console.log('Checking for changes');
}

function delayedAction() {
  console.log('Delayed action executed');
}

function cleanup() {
  console.log('Cleanup complete');
}
```

#### SPA Navigation Handling

**Problem**: Content scripts run once on page load but SPAs navigate without full page reloads.

**Solution**: Use WXT's location change detection:
```typescript
export default defineContentScript({
  matches: ['*://*.example.com/*'],

  main(ctx) {
    // Initial page load
    handlePage(location.href);

    // Watch for SPA navigation
    ctx.addEventListener(window, 'wxt:locationchange', (event) => {
      const { oldUrl, newUrl } = (event as CustomEvent).detail;
      console.log('Navigation:', oldUrl, '→', newUrl);
      handlePage(newUrl);
    });
  },
});

function handlePage(url: string) {
  const path = new URL(url).pathname;

  if (path.startsWith('/profile')) {
    injectProfileFeatures();
  } else if (path.startsWith('/settings')) {
    injectSettingsFeatures();
  }
}
```

### 7. Security Patterns

#### Input Validation

```typescript
// utils/validation.ts
export function validateMessage(message: any): message is Message {
  return (
    typeof message === 'object' &&
    message !== null &&
    typeof message.type === 'string' &&
    'payload' in message
  );
}

export function validateSender(sender: browser.runtime.MessageSender): boolean {
  // Must be from our extension
  if (sender.id !== browser.runtime.id) {
    console.warn('Message from unknown extension:', sender.id);
    return false;
  }

  // Optional: Validate tab/frame
  if (sender.tab && sender.frameId !== undefined) {
    // Additional tab/frame validation
  }

  return true;
}

// Usage in background
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (!validateMessage(message)) {
    console.error('Invalid message format');
    return false;
  }

  if (!validateSender(sender)) {
    console.error('Invalid sender');
    return false;
  }

  // Process message
  handleMessage(message, sender).then(sendResponse);
  return true;
});
```

#### Safe DOM Manipulation

```typescript
// Content script - safe DOM operations
export default defineContentScript({
  matches: ['*://*.example.com/*'],

  main(ctx) {
    // Create element safely
    const overlay = document.createElement('div');
    overlay.className = 'extension-overlay';
    overlay.textContent = 'Safe text content';

    // Never use innerHTML with untrusted data
    // ❌ overlay.innerHTML = userContent;

    // ✅ Use textContent or sanitize
    overlay.textContent = userContent;

    // Or use DOMPurify for rich content
    import('dompurify').then(({ default: DOMPurify }) => {
      overlay.innerHTML = DOMPurify.sanitize(userContent);
    });

    document.body.appendChild(overlay);
  },
});
```

#### Secure API Calls

```typescript
// Background script - secure external requests
async function fetchExternalData(url: string) {
  // Validate URL
  if (!isAllowedOrigin(url)) {
    throw new Error('Origin not allowed');
  }

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      // Don't send credentials to third-party APIs
      credentials: 'omit',
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('Fetch error:', error);
    throw error;
  }
}

function isAllowedOrigin(url: string): boolean {
  const allowed = [
    'https://api.example.com',
    'https://data.example.com',
  ];

  const origin = new URL(url).origin;
  return allowed.includes(origin);
}
```

---

## Industry Trends

### 1. Service Worker Architecture (MV3)

**Shift from Persistent Background Pages**:
- MV3 service workers are event-driven and ephemeral
- Must handle being terminated and restarted
- State must be persisted in storage
- WXT abstracts this complexity

### 2. Enhanced Privacy & Security

**Trends**:
- Granular permissions with host_permissions
- User-controlled site access
- No remote code execution
- Stricter CSP requirements

**Impact on Development**:
- All code must be bundled
- Cannot use eval() or inline scripts
- Must declare all external API endpoints

### 3. Cross-Browser Standardization

**WebExtensions API**:
- Increasing compatibility across browsers
- Firefox, Chrome, Edge converging on standards
- Safari catching up with MV3 support

**WXT's Role**:
- Abstracts browser differences
- Single codebase for all browsers
- Automatic manifest adaptation

### 4. Modern Build Tools

**Vite Ecosystem Growth**:
- Faster builds and HMR
- Better tree-shaking
- Native ESM support
- Rich plugin ecosystem

**WXT Advantage**:
- Built on Vite from the start
- Leverages latest tooling improvements
- No legacy build system constraints

### 5. TypeScript Adoption

**Industry Standard**:
- 99% of new extensions use TypeScript
- Better IDE support
- Fewer runtime errors
- Self-documenting code

**WXT Integration**:
- TypeScript-first framework
- Full type safety for browser APIs
- Auto-generated type definitions

---

## Gap Analysis

### Current Limitations

1. **Service Worker Debugging**
   - Challenge: Service workers harder to debug than persistent background pages
   - Mitigation: Use Chrome DevTools service worker panel, extensive logging
   - WXT Impact: Provides better error messages and dev tools integration

2. **Storage Limitations**
   - browser.storage.local: 5-10 MB limit (varies by browser)
   - browser.storage.sync: 100 KB limit
   - Solution: Use IndexedDB for large data sets

3. **Content Script Performance**
   - Large bundles slow page load
   - Solution: Code splitting, lazy loading, WXT's bundle optimization

4. **Cross-Origin Requests**
   - Must declare all hosts in host_permissions
   - Cannot make arbitrary external requests
   - User must approve host permissions

### Architectural Considerations

**For Buzztrail Extension**:

Suitable Patterns:
✅ File-based entrypoints (reduces configuration)
✅ Type-safe messaging (improves reliability)
✅ Storage abstraction (cross-browser compatibility)
✅ Module system (code reuse)
✅ Context-aware content scripts (prevents bugs)

Implementation Considerations:
⚠️ Plan for service worker ephemeral nature
⚠️ Minimize content script bundle size
⚠️ Implement proper error handling for extension reloads
⚠️ Design storage schema for scalability

---

## Recommendations

### Immediate Implementation

1. **Adopt File-Based Architecture**
   - Organize entrypoints in `/entrypoints` directory
   - Let WXT generate manifest automatically
   - Use inline configuration for entrypoint-specific settings

2. **Implement Type-Safe Messaging**
   - Define MessageMap interface
   - Create typed sendMessage helper
   - Validate all messages in background script

3. **Use WXT Storage API**
   - Replace direct browser.storage calls
   - Implement type-safe storage items
   - Use watch() for reactive updates

4. **Leverage Context API**
   - Use ctx parameter in content scripts
   - Implement context invalidation checks
   - Use ctx.addEventListener for auto-cleanup

### Short-Term Enhancements

5. **Create Custom Modules**
   - Extract common patterns into modules
   - Share code across entrypoints
   - Build module library for reuse

6. **Optimize Bundle Size**
   - Implement code splitting
   - Lazy load heavy dependencies
   - Use WXT's bundle analysis

7. **Enhance Security**
   - Validate all messages
   - Sanitize user input
   - Implement CSP best practices

### Long-Term Optimization

8. **Advanced Patterns**
   - Implement sophisticated state management
   - Build comprehensive testing suite
   - Create developer documentation

9. **Performance Monitoring**
   - Track extension performance metrics
   - Monitor bundle sizes over time
   - Optimize based on real usage data

10. **Community Contribution**
    - Share patterns and modules
    - Contribute to WXT ecosystem
    - Document lessons learned

---

## References

### Official Documentation
- WXT Documentation: https://wxt.dev/
- Chrome Extensions: https://developer.chrome.com/docs/extensions/
- Firefox Extensions: https://extensionworkshop.com/
- Safari Extensions: https://developer.apple.com/safari/extensions/

### Key Articles
- "The 2025 State of Browser Extension Frameworks": https://redreamality.com/blog/the-2025-state-of-browser-extension-frameworks-a-comparative-analysis-of-plasmo-wxt-and-crxjs/
- "Developing web extensions with the WXT library": https://blog.logrocket.com/developing-web-extensions-wxt-library/
- "Building AI-Powered Browser Extensions With WXT": https://marmelab.com/blog/2025/04/15/browser-extension-form-ai-wxt.html

### Manifest V3 Resources
- MV3 Migration Guide: https://developer.chrome.com/docs/extensions/develop/migrate
- Firefox MV3 Guide: https://extensionworkshop.com/documentation/develop/manifest-v3-migration-guide/
- MV3 Checklist: https://developer.chrome.com/docs/extensions/develop/migrate/checklist

### Testing Resources
- Vitest: https://vitest.dev/
- @webext-core/fake-browser: https://github.com/webext-core/fake-browser
- Playwright: https://playwright.dev/

### State Management
- Pinia: https://pinia.vuejs.org/
- Zustand: https://github.com/pmndrs/zustand
- pinia-plugin-webext-storage: https://github.com/ohmree/pinia-plugin-webext-storage

---

**Document Version**: 1.0
**Last Updated**: September 30, 2025
**Author**: Research Team - Issue #26
**Status**: Active - Reflects 2025 industry standards