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
.
_10supabase functions new wasm-add
Create a new Cargo project for the Wasm module inside the function's directory:
_10cd supabase/functions/wasm-add_10cargo new --lib add-wasm
Add the following code to add-wasm/src/lib.rs
.
_10use wasm_bindgen::prelude::*;_10_10#[wasm_bindgen]_10pub fn add(a: u32, b: u32) -> u32 {_10 a + b_10}
Update the add-wasm/Cargo.toml
to include the wasm-bindgen
dependency.
_12[package]_12name = "add-wasm"_12version = "0.1.0"_12description = "A simple wasm module that adds two numbers"_12license = "MIT/Apache-2.0"_12edition = "2021"_12_12[lib]_12crate-type = ["cdylib"]_12_12[dependencies]_12wasm-bindgen = "0.2"
After that we can build the package, by running:
_10wasm-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.
Supabase Edge Functions currently use Deno 1.46. From Deno 2.1, importing Wasm modules will require even less boilerplate code.
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
.
You will need update Supabase CLI to 2.7.0 or higher for the static_files
support.
_10[functions.wasm-add]_10static_files = [ "./functions/wasm-add/add-wasm/pkg/*.wasm"]
Deploy the function by running:
_10supabase functions deploy wasm-add