How-to
1 min read

Using WebAssembly (Wasm) at the Edge

Learn how to use WebAssembly (Wasm) to enable low-level languages to run on Vercel Edge Functions and Vercel Edge Middleware.
Table of Contents

WebAssembly, or Wasm, is a portable, low-level, assembly-like language that can be used as a compilation target for languages like C, Go, and Rust. Wasm was built to run more efficiently on the web and to run alongside JavaScript, so runs in most JavaScript virtual machines.

With Vercel, this means that you can now use Wasm within Edge Functions or Edge Middleware, taking advantage of the speed of delivery in a multitude of languages.

Pre-compiled WebAssembly can be imported with the ?module suffix. This will provide an array of the Wasm data that can be instantiated using WebAssembly.instantiate().

You can use Wasm in your production deployment or locally, using vercel dev.

  1. You should already have an existing C, Go, and Rust project. This should be compiled it to WebAssembly to create a binary .wasm file. Once you have this .wasm, you can use it in your Edge Function or Middleware

  2. Import the file into your existing project using:

    api/wasm.ts
    import wasmModule from './my-file.wasm?module';
  3. Instantiate it:

    api/wasm.ts
    export const config = {
      runtime: 'edge',
    };
     
    export default async function handler() {
      const { exports } = (await WebAssembly.instantiate(wasmModule)) as any;
      const result = exports.xor(0xb4c9a91f, 0xf0c0ffee);
      return new Response(result);
    }

This walkthrough uses the WASM XOR Edge API Route example.

Last updated on April 26, 2024