Sign In
Frontend & Clients

Next.js

The Rivet Next.js client allows you to connect to and interact with actors in Next.js applications.

Basic Usage

Installation

Install the RivetKit React package:

npm install @rivetkit/actor @rivetkit/react

Setup RivetKit client

Follow the Next.js backend integration guide to set up your Next.js backend with Rivet.

Create a RivetKit client to connect to your actor:

src/lib/rivet-client.ts
"use client";
import { createClient, createRivetKit } from "@rivetkit/next-js/client";
import type { registry } from "@/rivet/registry";

const client = createClient<typeof registry>(`${window.location.href}api`, {
	transport: "sse",
});

export const { useActor } = createRivetKit(client);

It's important to use SSE (Server-Sent Events) for real-time updates in Next.js.

Connect to Actor

Connect to actors and listen for real-time updates:

src/components/Counter.tsx
"use client";
import { useActor } from "@/lib/rivet-client";
import { useState } from "react";


export function Counter() {
	const counter = useActor({
		name: "counter",
		key: ["test"], // Use a unique key for the actor instance
	});
	const [count, setCount] = useState(0);

	counter.on("countChanged", (newCount) => {
		setCount(newCount);
	});

	const increment = () => {
		counter.increment();
	};

	return (
		<div>
			<p>Count: {count}</p>
			<button onClick={increment}>Increment</button>
		</div>
	);
}
Make sure to import the Counter component in your page or layout.

API Reference

It's the same as the React client API reference, since the RivetKit React package is used in both Next.js and React applications.

Suggest changes to this page