Skip to content

thinkjrs/nextjs-wasm-bindgen

Repository files navigation

This is a Next.js project bootstrapped with create-next-app which uses a Rust function compiled into a WebAssembly module to calculate Fibonacci numbers.

Getting Started

First, run the development server:

npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev

Open http://localhost:3000 with your browser to see the result.

You can examine how this project defines, loads and uses the WebAssembly module within src/components/Fibonacci.tsx.

Basic outline

Using wasm-bindgen with wasm-pack we have a simple and maintanable way to pull in functions we write in Rust into our Next.js apps using the app router.

Here's the basic gist:

  1. Create Rust crate: cargo new fibonacci --lib
  • fibonacci/
  1. Add two things to your Cargo.toml:
[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]
  1. Add your Rust library code
  2. Compile Rust into WebAssembly: wasm-pack build --target web --out-dir ../src/app/pkg

    Note: this was executed from within the Rust crate.

  3. Update Next.js eslint configuration:
const eslintConfig = [
  ...compat.extends("next/core-web-vitals", "next/typescript"),
  // WASM-specific rule adjustments
  {
    files: ["src/app/pkg/fibonacci.js"],
    rules: {
      "@typescript-eslint/no-unused-vars": "off",
    },
  },
];
  1. Add Next.js component using the Rust WebAssembly function, must be a client component with the "use client" directive.
  • Import the WebAssembly init function and types
  • Define the WebAssembly object
  • Initialize the function
  • Call the function
  1. Render the component in your Next.js app.

Learn More

To learn more about Next.js, Rust, and WebAssembly take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

Deploying

This app is deployed on Vercel. You can do the same by forking the repo and connecting that in your Vercel account.

Check out the Next.js deployment documentation for more details on how to do that.

About

A bare-bones Rust (WebAssembly) + Next.js example

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published