Running WebAssembly in Cloudflare Workers

Alex Reyes · · 12 views

WebAssembly opens up a new class of compute-intensive workloads for Workers. Learn how to compile Rust to Wasm, import the module, and call it from your Worker.

Why Wasm in Workers?

Workers have a 10 ms CPU time budget on the Free plan. For most web tasks this is plenty, but image processing, cryptography, or data compression can blow through it quickly. A hand-optimised Wasm module can execute the same logic 10–50× faster than equivalent JavaScript.

Compiling Rust to Wasm

# Install the Wasm target
rustup target add wasm32-unknown-unknown

# Build
cargo build --target wasm32-unknown-unknown --release

For Workers, prefer wasm-pack with --target bundler:

wasm-pack build --target bundler

Importing the Module

Wrangler handles Wasm imports natively. Reference the .wasm file and Workers will bundle it:

import init, { compress } from "./pkg/my_lib";
import wasm from "./pkg/my_lib_bg.wasm";

export default {
  async fetch(request: Request): Promise<Response> {
    await init(wasm);
    const input = new TextEncoder().encode(await request.text());
    const output = compress(input);
    return new Response(output);
  }
};

Limits

  • Wasm modules may not exceed 10 MB in compressed size (Workers Free)
  • Instantiation happens per-isolate, not per-request — store the result globally
  • SIMD is supported; threads are not (no SharedArrayBuffer)

Practical Example: SHA-256 Hashing

For pure hashing, the built-in SubtleCrypto is already implemented in native code and faster than any Wasm alternative. Use Wasm when the standard APIs do not cover your use case.