Edge Functions

Using Wasm modules

How to use WebAssembly in Edge Functions.


Edge Functions supports running WebAssembly (Wasm) modules. WebAssembly is useful if you want to optimize code that's slower to run in JavaScript or require low-level manipulation.

It also gives you the option to port existing libraries written in other languages to be used with JavaScript. For example, MagickWasm, which does image manipulation and transforms, is a port of an existing C library to WebAssembly.

Writing a Wasm module

You can use different languages and SDKs to write Wasm modules. For this tutorial, we will write a simple Wasm module in Rust that adds two numbers.

Follow this guide on writing Wasm modules in Rust to setup your dev environment.

Create a new Edge Function called wasm-add.


_10
supabase functions new wasm-add

Create a new Cargo project for the Wasm module inside the function's directory:


_10
cd supabase/functions/wasm-add
_10
cargo new --lib add-wasm

Add the following code to add-wasm/src/lib.rs.


_10
use wasm_bindgen::prelude::*;
_10
_10
#[wasm_bindgen]
_10
pub fn add(a: u32, b: u32) -> u32 {
_10
a + b
_10
}

View source

Update the add-wasm/Cargo.toml to include the wasm-bindgen dependency.


_12
[package]
_12
name = "add-wasm"
_12
version = "0.1.0"
_12
description = "A simple wasm module that adds two numbers"
_12
license = "MIT/Apache-2.0"
_12
edition = "2021"
_12
_12
[lib]
_12
crate-type = ["cdylib"]
_12
_12
[dependencies]
_12
wasm-bindgen = "0.2"

View source

After that we can build the package, by running:


_10
wasm-pack build --target deno

This will produce a Wasm binary file inside add-wasm/pkg directory.

Calling the Wasm module from the Edge Function

Now let's update the Edge Function to call add from the Wasm module.

index.ts

_16
const wasmBuffer = await Deno.readFile(
_16
new URL("./add-wasm/pkg/add_wasm_bg.wasm", import.meta.url),
_16
);
_16
_16
const { instance } = await WebAssembly.instantiate(
_16
wasmBuffer,
_16
);
_16
const { add } = instance.exports;
_16
_16
Deno.serve(async (req) => {
_16
const { a, b } = await req.json();
_16
return new Response(
_16
JSON.stringify({ result: add(a, b) }),
_16
{ headers: { "Content-Type": "application/json" } },
_16
);
_16
});

View source

Bundle and deploy the Edge Function

Before deploying the Edge Function, we need to ensure it bundles the Wasm module with it. We can do this by defining it in the static_files for the function in superbase/config.toml.


_10
[functions.wasm-add]
_10
static_files = [ "./functions/wasm-add/add-wasm/pkg/*.wasm"]

Deploy the function by running:


_10
supabase functions deploy wasm-add