Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Web: TypeScript and React (Next.js)

These are the steps to set up and run a simple TypeScript Web app that calls into a shared core.

Note

This walk-through assumes you have already set up the shared library and codegen as described in Shared core and types.

Info

There are many frameworks available for writing Web applications with JavaScript/TypeScript. We've chosen React with Next.js for this walk-through because it is simple and popular. However, a similar setup would work for other frameworks.

The shared crate holds app.rs and ffi.rs. The codegen command makes TypeScript types from app.rs, and boltffi pack wasm makes a WASM package and JS bindings from ffi.rs. The React web app uses both.

Create a Next.js App

For this walk-through, we'll use the pnpm package manager for no reason other than we like it the most!

Let's create a simple Next.js app for TypeScript, using pnpx (from pnpm). Run this from the root of the repo, next to shared, and call the app web-nextjs, because that's the directory shared/boltffi.toml writes the Wasm package into.

pnpx create-next-app@latest web-nextjs --app --src-dir --yes
cd web-nextjs

The --app and --src-dir flags pick the App Router and put the code in a src/ directory, which is where the files below go. --yes accepts the defaults for everything else.

Install BoltFFI

When we build our app, we also want to compile the Rust core to WebAssembly so that it can be referenced from our code.

To do this, we'll use BoltFFI, which you can install like this:

cargo install boltffi_cli --version '=0.32.1' --locked
brew install binaryen # provides wasm-opt

The crate is boltffi_cli; it installs the boltffi binary used below.

Binaryen must be version 123 or newer: BoltFFI passes --enable-bulk-memory-opt to wasm-opt, which older releases don't understand. Check with wasm-opt --version; distribution packages are often well behind, so prefer a release from GitHub if your package manager ships something older.

Generate the Shared Types

To generate the shared types for TypeScript, we use the codegen CLI we prepared earlier. Run it from the web-nextjs directory, so the types land in web-nextjs/generated/types:

cargo run --package shared --bin codegen \
    --features codegen,facet_typegen \
    -- --language typescript \
       --output-dir generated/types

Add the dependencies

Now add the Wasm package, the generated types and the BoltFFI runtime to the dependencies in package.json:

{
  "dependencies": {
    "@boltffi/runtime": "0.32.1",
    "shared": "link:generated/pkg",
    "shared_types": "file:generated/types"
  }
}

The Wasm package does not exist yet. A link: dependency is a symbolic link, so pnpm can install it before BoltFFI writes the package. pnpm does not install the dependencies of a linked package, so the app lists @boltffi/runtime itself. The app also needs @types/node in its devDependencies (create-next-app adds it).

Install the dependencies:

pnpm install

Compile our Rust shared library

Now that we have boltffi installed, we can build our shared library to WebAssembly for the browser. BoltFFI runs from the shared directory, and writes the package to web-nextjs/generated/pkg. It type-checks the TypeScript bindings that it generates against @boltffi/runtime and @types/node in the node_modules of web-nextjs. Thus you must install the dependencies before you run it:

cd ../shared
boltffi pack wasm
cd ../web-nextjs

Type generation compiles the generated types package to JavaScript, and the exports map in its package.json lists the modules that you can import. Next.js can use the package with no change to next.config.ts.

The Wasm package contains TypeScript sources alongside its compiled JavaScript, and they don't pass Next.js's type check. We only use the compiled files, so add generated/pkg to the exclude list in tsconfig.json:

{
  "exclude": ["node_modules", "generated/pkg/**/*.ts"]
}

Create some UI

Counter example

A simple app that increments, decrements and resets a counter.

Wrap the core to handle effects

First, let's add some boilerplate code to wrap our core and handle the effects that it produces. For this example, we only need to support the Render effect, which triggers a render of the UI.

Note

This code that wraps the core only needs to be written once. It only grows when we need to support additional effects.

Create src/app/core.ts and make it look like the following. This code sends our (UI-generated) events to the core, and handles any effects that the core asks for. In this example, we aren't calling any HTTP APIs or handling any side effects other than rendering the UI, so we just handle this render effect by updating the component's view hook with the core's ViewModel.

Notice that we have to serialize and deserialize the data that we pass between the core and the shell. This is because the core is running in a separate WebAssembly instance, and so we can't just pass the data directly.

import type { Dispatch, SetStateAction } from "react";
import { CoreFfi } from "shared";
import * as sharedWasm from "shared";
import type { Effect, Event } from "shared_types/app";
import {
  serializeEvent,
  matchEffect,
  Request,
  ViewModel,
} from "shared_types/app";
import { BincodeDeserializer, BincodeSerializer } from "shared_types/bincode";

const wasmInitialized = (
  sharedWasm as unknown as { initialized: Promise<void> }
).initialized;

export class CoreWrapper {
  core: CoreFfi | null = null;
  initializing: Promise<void> | null = null;
  setState: Dispatch<SetStateAction<ViewModel>>;

  constructor(setState: Dispatch<SetStateAction<ViewModel>>) {
    // Don't initialize CoreFfi here - wait for WASM to be loaded
    this.setState = setState;
  }

  initialize(shouldLoad: boolean): Promise<void> {
    if (this.core) {
      return Promise.resolve();
    }

    if (!this.initializing) {
      const load = shouldLoad ? wasmInitialized : Promise.resolve();

      this.initializing = load
        .then(() => {
          this.core = CoreFfi.new();
          this.setState(this.view());
        })
        .catch((error) => {
          this.initializing = null;
          console.error("Failed to initialize wasm core:", error);
        });
    }

    return this.initializing;
  }

  view(): ViewModel {
    if (!this.core) {
      throw new Error("Core not initialized. Call initialize() first.");
    }
    return deserializeView(this.core.view());
  }

  update(event: Event) {
    if (!this.core) {
      throw new Error("Core not initialized. Call initialize() first.");
    }
    const serializer = new BincodeSerializer();
    serializeEvent(event, serializer);

    const effects = this.core.update(serializer.getBytes());

    const requests = deserializeRequests(effects);
    for (const { effect } of requests) {
      this.processEffect(effect);
    }
  }

  private processEffect(effect: Effect) {
    matchEffect(effect, {
      Render: () => this.setState(this.view()),
    });
  }
}

function deserializeRequests(bytes: Uint8Array | number[]): Request[] {
  const deserializer = new BincodeDeserializer(asBytes(bytes));
  const len = deserializer.deserializeLen();
  const requests: Request[] = [];
  for (let i = 0; i < len; i++) {
    const request = Request.deserialize(deserializer);
    requests.push(request);
  }
  return requests;
}

function deserializeView(bytes: Uint8Array | number[]): ViewModel {
  return ViewModel.deserialize(new BincodeDeserializer(asBytes(bytes)));
}

function asBytes(bytes: Uint8Array | number[]): Uint8Array {
  return bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
}

Why CoreWrapper?

This loop is what the Core class generated in shared_types/app runs for you. Ours is called CoreWrapper so it doesn't get mixed up with that one. To see the counter use the generated Core instead, see Getting started.

Tip

That matchEffect call, above, is where you would handle any other effects that your core might ask for. For example, if your core needs to make an HTTP request, you would handle that here. With the generated Core, each effect gets a method on an EffectHandler instead. See Adding a capability for this counter with HTTP and Server-Sent Events added.

Create a component to render the UI

Edit src/app/page.tsx to look like the following. This code loads the WebAssembly core and sends it an initial event. Notice that we pass the setState hook to the update function so that we can update the state in response to a render effect from the core.

"use client";

import type { NextPage } from "next";
import { useEffect, useRef, useState } from "react";

import {
  ViewModel,
  eventReset,
  eventIncrement,
  eventDecrement,
} from "shared_types/app";

import { CoreWrapper } from "./core";

const Home: NextPage = () => {
  const [view, setView] = useState(new ViewModel(""));
  const core = useRef(new CoreWrapper(setView));

  useEffect(() => {
    void core.current.initialize(true);
  }, []);

  return (
    <main>
      <section className="box container has-text-centered m-5">
        <p className="is-size-5">{view.count}</p>
        <div className="buttons section is-centered">
          <button
            className="button is-primary is-danger"
            onClick={() => core.current.update(eventReset())}
          >
            {"Reset"}
          </button>
          <button
            className="button is-primary is-success"
            onClick={() => core.current.update(eventIncrement())}
          >
            {"Increment"}
          </button>
          <button
            className="button is-primary is-warning"
            onClick={() => core.current.update(eventDecrement())}
          >
            {"Decrement"}
          </button>
        </div>
      </section>
    </main>
  );
};

export default Home;

Now all we need is some CSS. First add the Bulma package, and then import it in layout.tsx.

pnpm add bulma
import "bulma/css/bulma.min.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Crux Simple Counter Example",
  description: "Rust Core, TypeScript Shell (NextJS)",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  );
}

Build and serve our app

We can build our app, and serve it for the browser, in one simple step.

pnpm dev

Success

Your app should look like this:

counter app