Build Browser-Only Tools with WebAssembly

Most “free online tools” work by uploading a file to a server, processing it, and sending a download back. That is simple to build, and it is a poor fit for anything private, large, or frequent: you pay for bandwidth and CPU, you become a custodian of other people’s documents, and the tool stops working when the network does.

The other design is to do the work in the browser. The server only ships HTML, JavaScript and a WebAssembly module. The file never leaves the device. This is now practical for image compression, PDF merge and split, QR codes, unit conversion, JSON formatting, and, with limits, audio and video.

This guide covers why that architecture is worth it, which libraries to use for images and PDFs, how Web Workers and memory limits shape the design, and where ffmpeg.wasm fits.

Why client-side processing helps

Privacy. A contract scan, a passport photo, a payroll PDF or a customer export should not transit a machine you happen to run. If the network tab shows no upload and the tool still works with the Ethernet cable pulled, the privacy claim is checkable, not decorative.

Cost and reliability. You are not paying for a worker that transcodes every file, and a traffic spike does not take down a conversion queue. The origin can be a static site — the same static export plus nginx pattern used for a front end that has no Node process.

Limits that belong to the user. A 40 MB video is expensive to receive and store on a server. In the browser, the user already has the file. The new limits are different (memory, tab lifetime, mobile CPU), and they have to be designed for, but they are not your hosting invoice.

The trade-off is honest: a low-end phone will be slower than a well-provisioned server, a first visit may download a large .wasm file, and some formats are still painful in WASM. The rest of this post is about staying on the right side of that trade-off.

Start with the platform, not with WASM

If you only need JPEG, PNG or WebP, the browser already knows how:

async function canvasToBlob(
  source: ImageBitmap,
  type: 'image/jpeg' | 'image/png' | 'image/webp',
  quality = 0.8,
): Promise<Blob> {
  const canvas = new OffscreenCanvas(source.width, source.height);
  const ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('2D context unavailable');
  ctx.drawImage(source, 0, 0);
  return canvas.convertToBlob({ type, quality });
}

const bitmap = await createImageBitmap(file);
const blob = await canvasToBlob(bitmap, 'image/jpeg', 0.8);
bitmap.close(); // release decoded pixels promptly

createImageBitmap plus OffscreenCanvas can run in a worker, so the main thread stays free for the UI. For “compress this JPEG to under 200 KB”, a short binary search on quality is usually enough:

async function compressToMaxBytes(bitmap: ImageBitmap, maxBytes: number) {
  let lo = 0.05, hi = 0.95, best: Blob | null = null;
  for (let i = 0; i < 7; i++) {
    const quality = (lo + hi) / 2;
    const blob = await canvasToBlob(bitmap, 'image/jpeg', quality);
    if (blob.size <= maxBytes) {
      best = blob;
      lo = quality;
    } else {
      hi = quality;
    }
  }
  return best;
}

Reach for WebAssembly when the platform cannot do the job: AVIF or JPEG XL encode, careful MozJPEG / OxiPNG compression, HEIC decode on browsers that will not, PDF page surgery, or audio and video in formats the WebCodecs API does not handle.

Images: Squoosh codecs via jSquash

Google’s Squoosh app compiled several production codecs (MozJPEG, libwebp, libavif, libjxl, OxiPNG) to WebAssembly. jSquash packages those codecs as ESM modules that run in the window or in a worker, without depending on the Squoosh UI.

import { decode } from '@jsquash/jpeg';
import { encode } from '@jsquash/webp';

export async function jpegToWebp(input: ArrayBuffer, quality = 75) {
  const imageData = await decode(input);
  return encode(imageData, { quality });
}

A sensible production setup:

  • Try the browser first (createImageBitmap, canvas.convertToBlob) for JPEG, PNG and WebP.
  • Load @jsquash/jpeg, @jsquash/webp, @jsquash/avif, @jsquash/jxl or @jsquash/oxipng only when that format is needed, so the first paint does not download every codec.
  • Run encode/decode in a Web Worker. AVIF encode in particular can take a long time on a single thread; a speed setting that favours throughput is often the difference between a usable tool and a frozen tab.
  • Multithreaded codec builds need SharedArrayBuffer, which in turn needs cross-origin isolation: Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp (or credentialless where that is enough). Those headers will break third-party iframes that are not CORP-compatible. If you cannot set them, stay on the single-threaded builds.

HEIC from iPhones is a common extra: decode with a libheif-based package, then re-encode with canvas or jSquash. Do not assume Safari’s behaviour is universal.

PDFs: pdf-lib for structure, a renderer for pixels

pdf-lib (and maintained forks such as @cantoo/pdf-lib) edits the structure of a PDF: merge, split, rotate, reorder, add a page or a watermark. It copies page objects. It does not re-render them, which is why a merge is fast and does not reduce quality.

import { PDFDocument } from 'pdf-lib';

export async function mergePdfs(files: ArrayBuffer[]) {
  const out = await PDFDocument.create();
  for (const bytes of files) {
    const src = await PDFDocument.load(bytes);
    const pages = await out.copyPages(src, src.getPageIndices());
    for (const page of pages) out.addPage(page);
  }
  return out.save();
}

export async function splitPdf(bytes: ArrayBuffer, keep: number[]) {
  const src = await PDFDocument.load(bytes);
  const out = await PDFDocument.create();
  const pages = await out.copyPages(src, keep);
  for (const page of pages) out.addPage(page);
  return out.save();
}

Compression is a different problem. A lossless rewrite with object streams helps a little. For a scanned document, the size is in the embedded images, and the usual approach is:

  1. Rasterise each page with PDF.js (or another renderer) at a chosen scale.
  2. Encode the bitmap as JPEG or WebP at a chosen quality.
  3. Build a new PDF that embeds those images.

That path does lose quality, which is the point of a “reduce PDF to 200 KB” tool. Do it in a worker, and be careful with PDF.js’s default render path: if it depends on requestAnimationFrame, a background tab can pause mid-job. Using a print-intent (or otherwise rAF-free) render path avoids that.

Keep the two libraries in their lanes: pdf-lib for “move these pages about”, a renderer for “turn this page into pixels”.

Audio and video: ffmpeg.wasm, with limits

@ffmpeg/ffmpeg (0.12+) runs a large part of FFmpeg in WebAssembly. The API is new FFmpeg(), then load(), writeFile(), exec() and readFile(). A typical pattern is to host the core files yourself and load them as blob URLs, so the worker is not broken by a bundler rewriting its imports:

import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile, toBlobURL } from '@ffmpeg/util';

const ffmpeg = new FFmpeg();

export async function loadFfmpeg() {
  const base = '/ffmpeg'; // serve official core files from your origin
  await ffmpeg.load({
    coreURL: await toBlobURL(`${base}/ffmpeg-core.js`, 'text/javascript'),
    wasmURL: await toBlobURL(`${base}/ffmpeg-core.wasm`, 'application/wasm'),
  });
}

export async function transcodeToMp4(file: File) {
  await ffmpeg.writeFile('input', await fetchFile(file));
  await ffmpeg.exec([
    '-i', 'input',
    '-c:v', 'libx264',
    '-preset', 'superfast',
    '-c:a', 'aac',
    'output.mp4',
  ]);
  const data = await ffmpeg.readFile('output.mp4');
  await ffmpeg.deleteFile('input');
  await ffmpeg.deleteFile('output.mp4');
  return data;
}

Facts to design around, rather than discover in production:

  • The core is large (tens of megabytes). Load it on first use, not on first paint, and let the browser cache it.
  • The multithreaded core needs SharedArrayBuffer and the same COOP/COEP headers as multithreaded image codecs. If you cannot send those headers, use the single-threaded core. It is slower; it is also the one that will actually run on a ordinary page.
  • This is not a film-grade transcode farm. Short clips, audio extraction, and “MOV that a phone produced → a generally playable MP4” are the jobs it is good at. Long 4K files will exhaust memory or patience, especially on mobile.
  • If the browser already has WebCodecs for the container you need, prefer that and keep ffmpeg.wasm as a fallback for awkward formats (AVI, some WMVs, odd audio containers).

Workers, memory and the tab

WASM does not cancel the rule that a page has a memory ceiling. Many modules are still compiled to 32-bit wasm, which caps linear memory in the 2–4 GB range in theory and much lower in practice on phones. A decoded 12-megapixel RGBA bitmap is about 48 MB by itself; holding the original, a few intermediate frames and an encoder buffer at once is how a “simple” compressor runs out of memory.

Practical rules:

  • Do the heavy work in a Web Worker (or a small pool). Keep one AVIF encode or one ffmpeg job at a time unless you have measured otherwise.
  • Transfer ArrayBuffers with postMessage(buf, [buf]) so the worker does not copy them.
  • Close ImageBitmaps, revoke object URLs, and delete ffmpeg virtual files when a job ends. Do not keep the last ten results in memory “for undo” unless they are small.
  • Show progress. A 20-second encode with a silent UI looks like a crash.
  • If a job might run long, warn the user that switching away or putting the phone to sleep can pause or kill the tab.

A small worker wrapper:

// compress.worker.ts
import { decode } from '@jsquash/jpeg';
import { encode } from '@jsquash/webp';

self.onmessage = async (event: MessageEvent<{ buffer: ArrayBuffer; quality: number }>) => {
  const { buffer, quality } = event.data;
  const image = await decode(buffer);
  const output = await encode(image, { quality });
  const outBuffer = output.buffer as ArrayBuffer;
  self.postMessage({ output: outBuffer }, [outBuffer]);
};
const worker = new Worker(new URL('./compress.worker.ts', import.meta.url), { type: 'module' });

export function compressInWorker(buffer: ArrayBuffer, quality: number) {
  return new Promise<ArrayBuffer>((resolve, reject) => {
    worker.onmessage = (event: MessageEvent<{ output: ArrayBuffer }>) => resolve(event.data.output);
    worker.onerror = () => reject(new Error('Compression worker failed'));
    worker.postMessage({ buffer, quality }, [buffer]);
  });
}

Putting a tool on the web

The app shell can be a static page: a file picker, a progress label, a download button, and a short privacy note that the file is not uploaded. Lazy-load the codec or ffmpeg package when the user picks a file. Serve the .wasm files with a long cache header and the correct Content-Type (application/wasm). If you need multithreaded cores, add the isolation headers at nginx or at Cloudflare, and test any embeds you still rely on.

For a working set of free, in-browser image, PDF, QR, unit and JSON tools built on this model, try MediaTools Suite. The same approach scales from a single “compress image” page to a small suite, as long as each tool loads only the code it needs.

The same privacy argument applies to mobile: the free Android apps on this site keep all data on the phone and most ship without the internet permission at all.

Client-side WASM will not replace every backend. It will replace a surprising number of file-conversion endpoints, and it will do so with a simpler security story. If you are building a tool like this and want help with the front end, get in touch.

Muhammad Jawad Iqbal Khan

A full-stack web, mobile and automation developer. Hire me

Need help building a web tool?

I can help you design and build browser-based tools, including client-side processing with WebAssembly.