BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Deploying Rust-Generated WASM on Cloudflare Serverless Workers

Deploying Rust-Generated WASM on Cloudflare Serverless Workers

This item in japanese

Bookmarks

Recently open-sourced by Cloudflare, Wrangler is a set of CLI tools to build, preview, and publish Cloudflare Workers written in Rust and compiled to WebAssembly.

Wrangler aims to provide an end-to-end experience for developers to be able to write their serverless functions in Rust and deploy and run them on Cloudflare Workers after translating them into WebAssembly. The WebAssembly compilation step is hidden behind Wrangler CLI.

To experiment with Wrangler, you can install it using cargo executing cargo install wrangler. The general structure of a project generated by Wrangler includes a src directory where Rust code is stored, a worker directory containing a worker.js from where Rust-generated code can be pulled in, and a couple of metadata files. Wrangler has three main commands: build, preview, and publish. The build command will compile all Rust code to WebAssembly, while the preview command will allow you to run your function on Cloudflare infrastructure. At the moment, though, it is not possible to preview a function locally, but, at least, previewing a function on Cloudflare infrastructure does not require a Cloudflare account.

Your Rust code is written as usual: you can bring in any external dependencies specifying it in your Cargo.toml file and you use wasm_bindgen to improve the communication between wasm and JS by enabling the use of strings, objects, classes and so on. For example, you could have this simple Rust file:

use wasm_bindgen::prelude::*;

extern "C" {
    fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) -> String{
    &format!("Hello, {}!", name);
}

This code can be imported and executed in the worker.js file using the following syntax:

const { greet } = wasm_bindgen;
await wasm_bindgen(wasm)
const output = greet('Worker')

Cloudflare plans to add more commands to Wrangler, including support for linting, testing, benchmarking, and size profiling.

Cloudflare Workers are serverless functions written in JavaScript that can be run in any of Cloudflare’s edge locations that are scattered across the world. According to Cloudflare, thanks to the proximity of their edge locations to end users, Workers improve performance by reducing network latency. Cloudflare Workers use the V8 JavaScript engine to run your code, but they do not use Node.js, instead relying on their own implementation of a number of APIs to improve efficiency and safety.

Rate this Article

Adoption
Style

BT