Running BiRefNet background removal in a Web Worker (and the CSP bug that almost bit us)
Most online background removers make you upload your photo to a server, wait in a queue, and then either cap the export resolution or slap a watermark on it unless you pay for credits. When I built the background remove
Most online background removers make you upload your photo to a server, wait in a queue, and then either cap the export resolution or slap a watermark on it unless you pay for credits.
When I built the background remover for Imagier, I wanted the whole pipeline to stay on the user's device. No uploads, no rate limits, and full PNG output right out of the box.
Running a modern segmentation model like BiRefNet in the browser with ONNX Runtime Web is surprisingly doable now, but a few production details tripped us up along the way. Here is what actually worked.
1. Keep everything inside a dedicated Web Worker
Inference and image decoding will freeze the main thread if you are not careful. Moving the model session, createImageBitmap, and final PNG encoding into a dedicated worker keeps the UI responsive so you can still show progress updates and let the user cancel or tweak the preview backdrop.
We also check the image dimensions and file size before passing anything to the model:
if (!SUPPORTED_IMAGE_TYPES.has(data.file.type) || data.file.size > MAX_IMAGE_BYTES) {
throw new Error('Choose a PNG, JPEG, or WebP image smaller than 40 MB.');
}
image = await createImageBitmap(data.file, { imageOrientation: 'from-image' });
if (image.width * image.height > MAX_ASSET_PIXELS) {
throw new Error('Choose an image with no more than 32 million pixels.');
}
Passing { imageOrientation: 'from-image' } to createImageBitmap is easy to forget, and without it portrait phone photos come back rotated 90 degrees.
2. The stale worker CSP bug (and a 1-line pre-flight check)
This one was subtle. A worker script is served with its own HTTP response headers, including its own Content Security Policy. If you ship a cached worker file with an immutable cache header, a returning visitor can load an older worker whose CSP blocks wasm-unsafe-eval, even after you fix the headers on your main HTML document.
If you do not catch that up front, the app downloads a large segmentation model first and only blows up at the very end when ONNX Runtime tries to compile WebAssembly.
The fix is tiny. Before fetching the model weights, compile an empty 8-byte WebAssembly module:
try {
await WebAssembly.compile(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]));
} catch {
throw new Error(
'Background removal could not start WebAssembly. Reload this page to get the latest processing worker, then try again.'
);
}
Those 8 bytes (\0asm plus version 1) take a fraction of a millisecond to validate. If the browser or worker CSP blocks Wasm, the user gets a clear message immediately instead of waiting on a model download for nothing.
3. Compositing the alpha mask with OffscreenCanvas
Once BiRefNet returns a grayscale segmentation mask, you do not need to loop over every pixel in JavaScript to apply transparency at the original resolution. OffscreenCanvas handles it on the GPU with destination-in:
const maskCanvas = new OffscreenCanvas(mask.width, mask.height);
const maskCtx = maskCanvas.getContext('2d');
const result = new OffscreenCanvas(image.width, image.height);
const ctx = result.getContext('2d');
maskCtx.putImageData(mask, 0, 0);
ctx.drawImage(image, 0, 0);
ctx.globalCompositeOperation = 'destination-in';
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(maskCanvas, 0, 0, image.width, image.height);
const blob = await result.convertToBlob({ type: 'image/png' });
Because imageSmoothingQuality is set to 'high', scaling the predicted mask back up to the full input dimensions produces clean edges without writing custom bilinear interpolation by hand. Always remember to call image.close() in a finally block so large bitmaps do not leak GPU memory across repeated runs.
Try it locally
If you want to inspect the worker behavior or test it on a sample image without uploading anything, you can try it live at imagier.app/background-remover. If you also need to tighten the transparent padding around the cutout afterward, there is a companion transparent pixel trimmer that runs with the same local-only setup.
If you have shipped ONNX Runtime Web in production, I am curious how you handle model caching and cold-start times on slower laptops.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.