Skip to main content

Next.js Integration

This guide covers integrating the Agent SDK into a Next.js application using the App Router.

1. Install the package

npm install @kapaai/agent-core @kapaai/agent-react

2. Create the session Route Handler

Create a Route Handler that proxies session creation. The API key stays server-side.

app/api/session/route.ts
import { NextResponse } from 'next/server';

export async function POST() {
const apiKey = process.env.KAPA_API_KEY;
const projectId = process.env.KAPA_PROJECT_ID;

if (!apiKey || !projectId) {
return NextResponse.json(
{ error: 'Missing KAPA_API_KEY or KAPA_PROJECT_ID' },
{ status: 500 },
);
}

const res = await fetch(
`https://api.kapa.ai/agent/v1/projects/${projectId}/agent/sessions/`,
{
method: 'POST',
headers: { 'X-API-Key': apiKey },
},
);

if (!res.ok) {
return NextResponse.json(
{ error: `Kapa API error: ${res.status}` },
{ status: res.status },
);
}

return NextResponse.json(await res.json());
}

Add the env vars to .env.local:

KAPA_API_KEY=your-api-key
KAPA_PROJECT_ID=your-project-id

3. Create the chat page

The agent chat must be a client component since it uses React hooks.

app/page.tsx
'use client';

import {
AgentProvider,
AgentChat,
} from '@kapaai/agent-react';
import { useCallback } from 'react';

export default function Page() {
const getSessionToken = useCallback(async () => {
const res = await fetch('/api/session', { method: 'POST' });
if (!res.ok) throw new Error('Session failed');
return res.json();
}, []);

return (
<AgentProvider
getSessionToken={getSessionToken}
projectId={process.env.NEXT_PUBLIC_PROJECT_ID!}
integrationId={process.env.NEXT_PUBLIC_INTEGRATION_ID!}
>
<div style={{ height: '100vh' }}>
<AgentChat
branding={{
title: 'AI Assistant',
}}
/>
</div>
</AgentProvider>
);
}

Add the public env vars to .env.local:

NEXT_PUBLIC_PROJECT_ID=your-project-id
NEXT_PUBLIC_INTEGRATION_ID=your-integration-id