Express.js is a popular Node.js web framework. RivetKit integrates seamlessly with Express using middleware mounting.
View Example on GitHub
Check out the complete example
Installation
Install Express alongside RivetKit:
npm install express
npm install -D @types/express
Basic Setup
Create Your Registry
Set up your Rivet Actor:
// registry.ts
import { actor, setup } from "@rivetkit/actor";
export const counter = actor({
state: { count: 0 },
actions: {
increment: (c, amount: number = 1) => {
c.state.count += amount;
c.broadcast("countChanged", c.state.count);
return c.state.count;
},
getCount: (c) => c.state.count,
},
});
export const registry = setup({
use: { counter },
});
Integrate with Express
Mount RivetKit into your Express application:
// server.ts
import { registry } from "./registry";
import express from "express";
// Start RivetKit
const { client, handler } = registry.createServer();
// Setup Express app
const app = express();
// Enable JSON parsing
app.use(express.json());
// Mount RivetKit handler
app.use("/registry", handler);
// Add your API routes
app.post("/increment/:name", async (req, res) => {
const name = req.params.name;
const { amount = 1 } = req.body;
try {
const counter = client.counter.getOrCreate([name]);
const newCount = await counter.increment(amount);
res.json({ success: true, count: newCount });
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.get("/count/:name", async (req, res) => {
const name = req.params.name;
try {
const counter = client.counter.getOrCreate([name]);
const count = await counter.getCount();
res.json({ name, count });
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
app.listen(8080, () => {
console.log("Server running at http://localhost:8080");
});