Frontend - Backend Action Pairing
Learn how to react to a Backend only operation on the Frontend.
Some actions, although having UI implications, would need to be performed on a Backend secured environment. In order to "render UI from the Backend", it is possible to pair a Frontend only action with its Backend equivalent, so one execution follows the other.
Set up a backend action
Follow the Backend Actions guides and set up an action on the Backend.
For demonstration purposes, we'll assume the same action as shown in this guide:
const runtime = new CopilotRuntime({
// ... existing configuration
actions: ({properties, url}) => {
return [
{
name: "fetchUser",
description: "Fetches user name from the database for a given ID.",
parameters: [
{
name: "userId",
type: "string",
description: "The ID of the user to fetch data for.",
required: true,
},
],
handler: async ({userId}: {userId: string}) => {
// do something with the userId
// return the user data
return {
name: "Darth Doe",
};
},
},
]
}
});
// ... rest of your route definitionPair a frontend action
On the UI layer, define a "frontend" only action which will correspond to the Backend action. Notice how the expected parameters match what's returned from the Backend action handler
"use client" // only necessary if you are using Next.js with the App Router.
import { useCopilotAction } from "@copilotkit/react-core";
export function MyComponent() {
const [userName, setUserName] = useState<string>('stranger');
// Define Copilot action
useCopilotAction({
name: "displayUser", // Names of the actions match between Backend and Frontend
description: "Display the user name fetched from the backend",
pairedAction: "fetchUser", // Choose which backed action this is paired with
available: "frontend", // Optional :mark it as frontend only if the FE and BE action name matches
parameters: [
{
name: "name",
type: "string",
description: "The user name",
},
],
handler: async ({ name }) => {
setUserName(name);
},
});
return (
<h1>
hello {userName}
</ul>
);
}Specify "use client" (Next.js App Router)
This is only necessary if you are using Next.js with the App Router.
"use client"Like other React hooks such as useState and useEffect, this is a client-side hook.
If you're using Next.js with the App Router, you'll need to add the "use client" directive at the top of any file using this hook.
Test it out!
After adding the action, test it by asking the copilot to perform the task. Observe how it selects the correct task, executes it, and the UI action defined is reflecting the result.
Next Steps
useCopilotAction Reference
Refer to the documentation for the useCopilotAction hook.
Frontend Actions
Learn how to enable your Copilot to take actions in the frontend.
Actions + Generative UI
Learn how to render custom UI components alongside your actions, directly in the CopilotKit chat window.
Backend Actions
Enable backend services to trigger actions via copilot backend hooks.
