How to create an edge function using WebAssembly on the Azion Edge platform

Learn about the required process to create an edge function that uses a WebAssembly originated function.

  1. On Azion Console, on the upper-left corner, select Edge Functions in the Edge Libraries section.
  2. Click Add a Function.
  3. Choose a name for your function.
  4. Under Language, select JavaScript.
  5. Copy and paste the following sample code to the code block:
async function handleRequest(request) {
// You can either retrieve your .wasm file through fetch, for instance :
// let wasmResponse = await fetch("http://somedomain/yourfile.wasm")
// or embed the binary in the code, as shown below.
const wasmCode = new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 1, 127, 1, 127, 3, 2, 1, 0, 7, 13, 1, 9, 105, 110, 99, 114, 101,
109, 101, 110, 116, 0, 0, 10, 9, 1, 7, 0, 32, 0, 65, 1, 106, 11,
]);
const wasmModule = new WebAssembly.Module(wasmCode);
const wasmInstance = new WebAssembly.Instance(wasmModule);
const increment = wasmInstance.exports.increment;
let value = 0;
if (request.headers.has("value")) {
let number = request.headers.get("value");
if (!isNaN(number)) {
value = parseInt(number);
}
}
let incremented = increment(value);
return new Response(
"incrementing " + value + " we have " + incremented
);
}
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});

The const wasmCode is the binary representation of the following WAT code:

(module
(type (;0;) (func (param i32) (result i32)))
(func (;0;) (type 0) (param i32) (result i32)
local.get 0
i32.const 1
i32.add)
(export “increment” (func 0)))

Note: WAT is the textual representation of the wasm binary format, used to enable WebAssembly to be read and edited by humans.

  1. Click the Save button.

Now, the function is ready to be instantiated in an edge application. Check how to instantiate and execute the functions in your edge application and try it out.

The expected output of the recently created function is similar to:

incrementing 0 we have 1

Contributors