tl;dr

Steps

  1. Install wasm-bindgen-cli.
  2. Write your Rust library crate using the wasm-bindgen crate.
  3. Write a glue code with JavaScript.
  4. Deploy to Firebase.
  5. Happy!

Step 1: Install wasm-bindgen-cli.

$ cargo install -f wasm-bindgen-cli

Step 2: Write your Rust library crate using the wasm-bindgen crate.

For example, I create a library crate named greeter.

use wasm_bindgen::prelude::*;

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

You should add a twist to Cargo.toml file to build your crate.

[package]
name = "greeter"
version = "0.1.0"
authors = ["Sadaie Matsudaira <sadaie@matsuri-hi.me>"]

# ADD THIS TWO LINES
[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"

Then, you should build your codes.

$ cargo build --target wasm32-unknown-unknown --release
$ wasm-bindgen target/wasm32-unknown-unknown/release/greeter.wasm --out-dir . --nodejs --no-typescript

If you want to build the crate for Firebase Functions, you should add the option --nodejs to wasm-bindgen command. But --no-typescript is optional.

Then you can see the files listed below in the crate's root directory.

$ ls greeter*
greeter_bg.js greeter_bg.wasm greeter.js

Step 3: Write a glue code with JavaScript.

Copy the greeter_bg.js, greeter_bg.wasm and greeter.js files, then let's write Functions's code to deploy.

const functions = require('firebase-functions');
const greeter = require('./greeter');

exports.greet = functions.https.onRequest((request, response) => {
    response.send(greeter.greet("sadaie"));
})

Step 4: Deploy to Firebase.

Since Firebase Functions's default Node.js version is 6, WebAssembly is not available by default.
Therefore you should add engines setting to setting.json file.

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "engines": {"node": "8"},
  "scripts": {
    "serve": "firebase serve --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "dependencies": {
    "firebase-admin": "~6.0.0",
    "firebase-functions": "^2.1.0"
  },
  "private": true
}
$ firebase deploy --only functions

Step 5: Happy!

$ curl https://YOUR-FIREBASE-PROJECT.cloudfunctions.net/greet; echo
Hello, sadaie

That's fine😎