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.
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
.
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:
- Create Rust crate:
cargo new fibonacci --lib
fibonacci/
- Add two things to your
Cargo.toml
:
[dependencies]
wasm-bindgen = "0.2"
[lib]
crate-type = ["cdylib"]
- Add your Rust library code
- Compile Rust into WebAssembly:
wasm-pack build --target web --out-dir ../src/app/pkg
Note: this was executed from within the Rust crate.
- 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",
},
},
];
- 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
- Render the component in your Next.js app.
To learn more about Next.js, Rust, and WebAssembly take a look at the following resources:
- My blog post on the topic - thinkjrs.dev
- The Rust book
- Rust By Example
- wasm-bindgen
- Next.js Documentation - learn about Next.js features and API.
- Learn Next.js - an interactive Next.js tutorial.
- WebAssembly
- @mpadge's deeper dive - Next.js & WebAssembly
You can check out the Next.js GitHub repository - your feedback and contributions are welcome!
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.