colossal-manchester-31772
08/25/2025, 6:54 AMtall-airline-16756
08/25/2025, 6:54 AMtall-airline-16756
08/25/2025, 6:55 AM"use client";
import { Room, RoomEvent, RpcInvocationData } from "livekit-client";
import { useEffect, useState } from "react";
export default function RPCExample() {
const [room] = useState(new Room());
const handleRPCMethod = async (rpcInvocation: RpcInvocationData): Promise<string> => {
console.log("RPC received from:", rpcInvocation.callerIdentity);
console.log("Payload:", rpcInvocation.payload);
// Just simulating some processing here
await new Promise((resolve) => setTimeout(resolve, 100));
return "RPC processed successfully!";
};
useEffect(() => {
const onConnectButtonClicked = async () => {
// You’ll want to replace these with your actual server URL and token fetching logic
const serverUrl = "wss://your-livekit-server-url";
const participantToken = "your-participant-token";
await room.connect(serverUrl, participantToken);
console.log("Connected to room:", room.name);
};
// Here, we’re connecting as soon as the component mounts
onConnectButtonClicked();
// Now, let’s register that RPC method
if (room && room.localParticipant) {
console.log("Registering RPC method: test.rpc");
room.localParticipant.registerRpcMethod("test.rpc", handleRPCMethod);
}
// Don’t forget to clean up by unregistering the method when the component unmounts
return () => {
if (room && room.localParticipant) {
console.log("Unregistering RPC method: test.rpc");
room.localParticipant.unregisterRpcMethod("test.rpc");
}
};
}, [room]);
return (
<div>
<h1>LiveKit RPC Example</h1>
<p>Room: {room.name || "Not connected"}</p>
</div>
);
}
Just a few things to keep in mind:
• Your RPC handler needs to be an async function that returns a Promise<string>.
• The handler gets an RpcInvocationData object with details like callerIdentity, payload, requestId, and responseTimeout.
• Make sure to use unregisterRpcMethod when cleaning up to keep things tidy and avoid memory leaks.
• Keep payloads under 15KiB and method names within 64 bytes to stay within limits.
And one last tip: for production, it’s best to fetch your token securely from your backend instead of hardcoding it here. If you have any questions or want to chat more about this, I’m here to help!
Sources: web/providers/GameProvider.tsx | Remote method calls (RPC) | LiveKit Docs | RPC | LiveKit Docs | Tool definition and use | LiveKit Docs