---
title: "WebAssembly"
---

> Documentation Index
> Fetch the complete documentation index at: https://workerd.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# WebAssembly

A Worker can import a `.wasm` file. As in Wrangler, the import gives the
compiled module, not the bytes.

```js
import addModule from "./add.wasm";

const { exports } = new WebAssembly.Instance(addModule);

export default {
  fetch() {
    return new Response(String(exports.add(2, 3)));
  },
};
```

workerd bundles `main` with esbuild. It keeps each imported `.wasm` file as
a separate module beside the bundle. A file that is not valid WebAssembly
stops workerd at startup with a `CompileError`. WebAssembly works in a
cluster like any other module.

## Example

The WebAssembly example is a Durable Object written in
Rust with [workers-rs](https://github.com/cloudflare/workers-rs).

```toml title="Cargo.toml"
[package]
name = "counter-demo-rs"
version = "0.1.0"
edition = "2021"

# This table keeps the example outside the engine workspace.
[workspace]

[lib]
crate-type = ["cdylib"]

[dependencies]
worker = "0.9.0"
serde_json = "1"
```

```rust title="src/lib.rs"
use worker::*;

#[durable_object(fetch)]
pub struct Counter {
    state: State,
}

impl DurableObject for Counter {
    fn new(state: State, _env: Env) -> Self {
        Self { state }
    }

    async fn fetch(&self, req: Request) -> Result<Response> {
        let n: u64 = self.state.storage().get("n").await.ok().flatten().unwrap_or(0);
        let n = n + 1;
        self.state.storage().put("n", &n).await?;
        let path = req.path();
        let name = path.strip_prefix("/c/").unwrap_or("");
        Response::from_json(&serde_json::json!({ "name": name, "n": n, "lang": "rust" }))
    }
}

#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
    let path = req.path();
    if let Some(name) = path.strip_prefix("/c/").filter(|name| !name.is_empty()) {
        let namespace = env.durable_object("COUNTER")?;
        let stub = namespace.id_from_name(name)?.get_stub()?;
        return stub.fetch_with_request(req).await;
    }
    let status = if path == "/" { 200 } else { 404 };
    Ok(
        Response::ok("workerd rust demo. Try: curl http://localhost:8787/c/hello\n")?
            .with_status(status),
    )
}
```

```jsonc title="wrangler.jsonc"
{
  "name": "counter-demo-rs",
  "main": "build/index.js",
  "no_bundle": true,
  "compatibility_date": "2026-01-01",
  "durable_objects": {
    "bindings": [{ "name": "COUNTER", "class_name": "Counter" }]
  },
  "exports": {
    "Counter": { "type": "durable-object", "storage": "sqlite" }
  }
}
```

Build and run it:

```sh
rustup target add wasm32-unknown-unknown
cargo install worker-build@0.9.0
(cd wasm && worker-build --release)
npx workerd serve ./wasm/wrangler.jsonc
curl http://localhost:8787/c/hello
```

`worker-build` writes `build/index.js` and `build/index_bg.wasm`. The
JavaScript imports the wasm file with a source phase import
(`import source`). esbuild cannot bundle it, so the configuration sets
`no_bundle: true`. A `worker-build` release refuses a `worker` crate of an
older minor version, so keep the two on the same minor version.

## Prebuilt Workers

With `no_bundle: true`, workerd skips esbuild and loads `main` as it is. It
also loads each file below `main`'s directory that matches the default
Wrangler module rules:

- `.js` and `.mjs` as ES modules
- `.cjs` as CommonJS
- `.wasm` as WebAssembly
- `.txt`, `.html`, and `.sql` as text
- `.bin` as data

A module name is the path from that directory. For example, with
`main: "./dist/shim.mjs"`, the import `"./lib/add.wasm"` loads
`dist/lib/add.wasm`.

The scan skips `node_modules` and every name that starts with a dot. It
does not follow a symbolic link to a directory. It also loads files that
no module imports, so put `main` in a separate build directory.

workerd refuses the Wrangler `rules`, `base_dir`, and
`find_additional_modules` fields. It does not resolve an import with a
`?module` suffix.

## Dynamic Workers

To give wasm to a [Dynamic Worker](https://workerd.dev/docs/services/dynamic-workers/), put
`{ wasm: bytes }` or a `WebAssembly.Module` in the `modules` map. Get the
`WebAssembly.Module` from an import: workerd does not compile wasm bytes
at runtime. The loaded Worker imports a compiled module. workerd refuses
bare bytes.

```js
const worker = env.LOADER.load({
  compatibilityDate: "2026-01-01",
  mainModule: "main.js",
  modules: {
    "main.js": `import m from "./add.wasm"; ...`,
    "add.wasm": { wasm: wasmBytes },
  },
});
```

Source: https://workerd.dev/docs/wasm/index.mdx
