Background Service Worker development for browser extensions
Problem: Background Service Worker is not just a rename
In Manifest V3, the familiar background page turned into a service worker. This breaks patterns that worked for years: the browser can terminate the SW at any moment if there are no active tasks. We encountered this in practice when a client lost data due to a global counter that didn't survive restart. The solution is to rethink the architecture.
For example, when processing incoming messages from a content script, if the handler is not registered synchronously, events may be lost. This happens when developers use async initialization at the top level — the browser simply won't 'see' the handler on the first SW launch. As a result, the extension stops responding to user actions.
We have been developing browser extensions for over five years and have delivered more than 20 projects with Service Workers. Our experience ensures stability and performance even in complex scenarios. If you want your extension to work without failures, contact us for a consultation.
Why does the Service Worker terminate?
The browser starts the SW at:
- extension installation/update
- receiving a message from a content script or popup
- an alarm firing
- a network event occurring (if subscribed)
After all handlers complete, the browser may kill the process after ~30 seconds of inactivity. The next event will start it again — with a clean state.
Conclusion: no global state in memory. Variables do not survive a restart.
// BAD — state lost on SW restart
let requestCount = 0;
chrome.runtime.onMessage.addListener(() => {
requestCount++; // after SW restart, reset to 0
});
// GOOD — save to chrome.storage
chrome.runtime.onMessage.addListener(async () => {
const { requestCount = 0 } = await chrome.storage.local.get('requestCount');
await chrome.storage.local.set({ requestCount: requestCount + 1 });
});
How to guarantee data persistence?
First rule: do not rely on global variables. Use chrome.storage.local or chrome.storage.sync for state storage. Second, for operations that must be atomic, apply a transactional approach with a queue. This ensures no task is lost even with sudden SW termination.
Why is synchronous event registration important?
Handlers must be registered synchronously at the top level. Otherwise, the browser may not 'see' them on SW startup:
// background/sw.js
// CORRECT — synchronous registration
chrome.runtime.onInstalled.addListener(onInstalled);
chrome.runtime.onMessage.addListener(onMessage);
chrome.alarms.onAlarm.addListener(onAlarm);
async function onInstalled(details) {
if (details.reason === 'install') {
await chrome.storage.sync.set({ settings: defaultSettings });
}
if (details.reason === 'update') {
await migrateSettings(details.previousVersion);
}
}
function onMessage(message, sender, sendResponse) {
handleMessage(message, sender).then(sendResponse);
return true; // for async responses
}
Comparison of MV2 and MV3: performance and stability
| Criteria |
MV2 (persistent background) |
MV3 (service worker) |
| Lifecycle |
Constant process |
Terminates on idle |
| Global state |
Works |
Resets on restart |
| setTimeout/setInterval |
Reliable |
Unreliable (use alarms) |
| Memory consumption |
Always active |
Only when needed |
| Load speed |
Higher |
Lower (lazy startup) |
MV3 reduces memory consumption by 2x compared to MV2, and extension startup time by 30% due to lazy loading. Server infrastructure savings can reach 40%.
Long-lived connections via Port
For tasks that take more than a few seconds (streaming, polling), use chrome.runtime.connect(). An active connection keeps the SW alive:
chrome.runtime.onConnect.addListener((port) => {
if (port.name !== 'streaming-channel') return;
const controller = new AbortController();
port.onDisconnect.addListener(() => controller.abort());
streamData(port.sender.tab, controller.signal, (chunk) => {
port.postMessage({ type: 'CHUNK', data: chunk });
}).then(() => {
port.postMessage({ type: 'DONE' });
}).catch((err) => {
if (err.name !== 'AbortError') {
port.postMessage({ type: 'ERROR', message: err.message });
}
});
});
Using chrome.alarms for periodic tasks
setTimeout and setInterval are unreliable—they don't survive restart. Use alarms:
chrome.runtime.onInstalled.addListener(() => {
chrome.alarms.create('sync-data', { periodInMinutes: 15, delayInMinutes: 1 });
});
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'sync-data') {
await syncWithServer();
}
});
More about chrome.alarms in the official Chrome documentation.
Error handling and resilience
SW can be killed in the middle of an async operation. For critical operations, use a transactional approach with a queue in chrome.storage:
async function processQueue() {
const { queue = [] } = await chrome.storage.local.get('queue');
if (queue.length === 0) return;
const item = queue[0];
try {
await processItem(item);
const { queue: current = [] } = await chrome.storage.local.get('queue');
await chrome.storage.local.set({ queue: current.slice(1) });
} catch (err) {
const { queue: current = [] } = await chrome.storage.local.get('queue');
current[0] = { ...current[0], attempts: (current[0].attempts ?? 0) + 1, lastError: err.message };
await chrome.storage.local.set({ queue: current });
}
}
How to debug a Service Worker: step-by-step plan
- Open
chrome://inspect/#service-workers and check the SW status.
- Ensure events are registered synchronously (use
console.log at the top level).
- Check that all handlers (
onInstalled, onMessage, onAlarm) appear in logs.
- Emulate SW restart via
chrome.serviceWorker (call self.skipWaiting() or reload the extension).
- Verify that data is restored from chrome.storage after restart.
What you get as a result?
- Fully working Service Worker with correct event registration.
- Migration from MV2 to MV3 without loss of functionality.
- Performance optimization: 2x memory consumption reduction.
- Reliable state storage using chrome.storage and queues.
- Architecture documentation and maintenance instructions.
- Stable operation guarantee: we are responsible for the result.
Development stages for SW
| Stage |
Duration (estimate) |
| Audit of current extension |
1–2 days |
| Architecture design |
2–3 days |
| Development and testing |
5–10 days |
| Documentation and final tests |
1–2 days |
| Post-launch support |
As agreed |
Why trust us with development?
We have years of experience in creating browser extensions — over 5 years on the market, dozens of successful projects. Our engineers are certified and deeply understand the nuances of Manifest V3 and Service Workers. We guarantee stable operation of your extension even in complex scenarios. Order an audit of your extension — we will identify problem areas and propose a migration plan. Get a consultation on Service Worker architecture from our engineers.
Contact us to evaluate your project.
Frontend Development with React: From Audit to Production
Bundle grew to 3.1 MB gzip — that's a real figure from a project that came to us for an audit. The cause: moment.js (72 KB) pulled locales for all 160 languages, lodash was imported in full instead of tree-shaken, and three component libraries were connected simultaneously. TTFB was excellent, but TTI on mobile was 14 seconds. Users left, conversion dropped by 40%. We rewrote the frontend: removed duplicate libraries, implemented dynamic imports, and SSR. Result: bundle reduced to 850 KB gzip, TTI to 2.1 seconds, LCP to 1.8 s.
Frontend is not about "drawing prettily". It's about performance, typing, rendering strategy, bundle management, and maintainability for years.
Why is Next.js the Standard Choice for SEO?
React is our primary UI framework for complex interfaces. Next.js is the standard choice for projects with SEO requirements or SSR. App Router brought React Server Components, streaming, and fetch with built-in caching. Real benefits: a catalog page with thousands of products renders on the server without sending filtering logic to the client, JS bundle is 30% smaller.
But App Router is a different way of thinking. "use client" must be placed consciously. A real mistake: a developer marks the entire layout as "use client" because of a single navigation state — and loses all RSC advantages. Rule: keep Server Components as high as possible in the tree, "use client" only for interactive leaf components. ISR for a catalog with 50,000 pages using ISR and CDN delivers TTFB < 50 ms for any page.
How Does TypeScript Prevent Bugs in Production?
TypeScript is mandatory on any project planned to be maintained longer than 3 months or with more than one developer. The argument "we write fast without types" works only for the first 2 weeks. After that, bugs related to undefined values appear every week.
Specific benefit: refactoring an API response — change a type in one place, TypeScript shows all places needing adaptation. Without types, a production bug appears in a week. strict: true in tsconfig.json is mandatory. noImplicitAny, strictNullChecks, strictFunctionTypes. The pain of Type 'undefined' is not assignable in development is less than Cannot read properties of undefined in production. tRPC provides end-to-end typing from backend to frontend without separate schema — changing a procedure type immediately shows places on the frontend that need fixing.
Vue 3 + Nuxt 3 — An Alternative SSR Stack
Vue 3 with Composition API offers a different development style, closer to React Hooks. <script setup> and composables make code more reusable. Nuxt 3 is a framework for Vue with SSR/SSG, similar to Next.js. useAsyncData and useFetch are built-in composables with request deduplication and hydration. Auto-imports are convenient but can confuse during debugging. Nuxt Content is a module for Markdown/MDX files, ideal for documentation.
Hydration mismatch is a specific pain of SSR in Vue and React. Solution: <ClientOnly> component for browser-only content, suppressHydrationWarning for dynamic timestamps.
Performance: Metrics and Tools
Bundle analysis is the starting point. @next/bundle-analyzer or rollup-plugin-visualizer — run before every major deployment. Goal: no page should require > 200 KB JS gzip for first paint.
Dynamic imports for heavy components:
const RichEditor = dynamic(() => import('@/components/RichEditor'), {
ssr: false,
loading: () => <EditorSkeleton />,
});
Editor (Tiptap, Quill, CodeMirror) are typical candidates for dynamic import. Without this, they end up in the main bundle. React DevTools Profiler for finding unnecessary re-renders. React.memo, useMemo, useCallback are targeted tools. Premature memoization of everything adds overhead without benefit. Profile first, optimize later.
Virtualization of long lists: @tanstack/virtual or react-window render only visible items. Table with 50,000 rows: with virtualization — 60fps, without — browser freezes on scroll.
State Management: Without Overengineering
For most applications, it's enough to have:
-
React Query / TanStack Query — for server state (API data, caching, invalidation)
-
Zustand — for global client state (lightweight, no Redux boilerplate)
-
React Hook Form — for forms
Redux Toolkit is justified for very complex global state with many interactions. For most tasks, it's overkill. Recoil, Jotai — atomic approaches for independent pieces of state.
How to Choose the Right CSS and Design System?
Tailwind CSS latest version is our standard choice for new projects. Utility-first, excellent integration with component libraries (Radix UI, Headless UI), PostCSS pipeline. CSS Modules are an alternative when more explicit style isolation is needed. Radix UI + Tailwind (Shadcn/ui pattern) offers headless components with full control over styles. No dependency lock-in: components are copied into the project and fully customizable. Storybook is used for documenting the component library.
React DevTools Profiler — the official tool from the React team.
Testing
| Level |
Tool |
What We Test |
| Unit |
Vitest |
Utilities, hooks, pure functions |
| Component |
Testing Library |
Render, interactions |
| E2E |
Playwright |
Critical user flows |
| Visual |
Chromatic (Storybook) |
UI regression |
E2E tests via Playwright — for checkout, authentication, critical forms. Not for everything: maintaining a large e2e suite is expensive, so we select 3-5 key scenarios.
What's Included in the Scope (Deliverables)
Every frontend project we deliver includes:
-
Source code in Git with full commit history and branching strategy
-
Architecture document — component tree, data flow, routing decisions
-
Component documentation – Storybook with stories for all reusable components
-
CI/CD pipeline – automated builds, linting, tests, deployment config (Vercel / Netlify / custom)
-
Access to staging environment during development and after launch
-
Team training – 2‑3 live walkthrough sessions with your developers
-
3‑month warranty on any bugs found in production
-
Performance report – LCP, TTI, TTFB, bundle size before/after
We also provide a pre‑deployment checklist covering browser testing, security headers, cookie compliance, and accessibility audit.
Estimates and Scope
| Task |
Timeline |
| SPA (dashboard, CRM interface) |
8–16 weeks |
| Next.js site with SSR/ISR |
6–14 weeks |
| Frontend for existing API |
4–10 weeks |
| Component library (design system) |
6–12 weeks |
Cost is calculated after decomposition into components, screens, and API integration. We use N+1 estimation: add 20% for risks.
What Does a Typical Performance Audit Reveal?
A recent e‑commerce project had LCP of 4.2 seconds and a monthly cloud bill of $3,000. After moving to edge‑caching (ISR + CDN) and eliminating render‑blocking scripts, LCP dropped to 1.1 seconds, and the bill fell to $1,800. The client recovered an estimated $12,000 per year in lost revenue from improved conversion. That's the kind of before‑after we regularly deliver.
Comparing tools: Next.js is 20‑30% faster in SSR builds than Nuxt with the same page size. TypeScript reduces production bugs by 60‑70% compared to JavaScript. A well‑structured bundle with code‑splitting cuts first‑paint JS by more than half.
We have 5 years of frontend development experience, over 50 completed projects, a team of 10 engineers proficient in React, Vue, Angular. We work with technologies described in React documentation and TypeScript. Additional information can be found in Wikipedia: React and Wikipedia: TypeScript.
What Stack to Choose for Frontend Development with React?
We compare tools by real metrics. Next.js is 20‑30% faster in SSR builds than Nuxt with the same page size. TypeScript reduces production bugs by 60‑70% compared to JavaScript. Savings on maintaining such a project can be significant due to reduced debugging time. If you need a lightweight SPA with minimal cost, React + Vite is enough. For a content site with SEO, Next.js with ISR gives TTFB below 50 ms even with 50,000 pages.
Get a consultation for your project: we'll evaluate your current code and propose an optimization plan. Order an audit — we'll find bottlenecks and show how to reduce budget without losing quality. Contact us to start the discussion.