Skip to Content
DocsFrameworksWith Next.js

Integrate Kastrax in your Next.js project ✅

There are two main ways to integrate Kastrax with your Next.js application: as a separate backend service or directly integrated into your Next.js app.

1. Separate Backend Integration ✅

Best for larger projects where you want to:

  • Scale your AI backend independently
  • Keep clear separation of concerns
  • Have more deployment flexibility

Create Kastrax Backend

Create a new Kastrax project using our CLI:

npx create-kastrax@latest

For detailed setup instructions, see our installation guide.

Install KastraxClient

npm install @kastrax/client-js@latest

Use KastraxClient

Create a client instance and use it in your Next.js application:

lib/kastrax.ts
import { KastraxClient } from '@kastrax/client-js'; // Initialize the client export const kastraxClient = new KastraxClient({ baseUrl: process.env.NEXT_PUBLIC_KASTRAX_API_URL || 'http://localhost:4111', });

Example usage in your React component:

app/components/SimpleWeather.tsx
'use client' import { kastraxClient } from '@/lib/kastrax' export function SimpleWeather() { async function handleSubmit(formData: FormData) { const city = formData.get('city') const agent = kastraxClient.getAgent('weatherAgent') try { const response = await agent.generate({ messages: [{ role: 'user', content: `What's the weather like in ${city}?` }], }) // Handle the response console.log(response.text) } catch (error) { console.error('Error:', error) } } return ( <form action={handleSubmit}> <input name="city" placeholder="Enter city name" /> <button type="submit">Get Weather</button> </form> ) }

Deployment

When you’re ready to deploy, you can use any of our platform-specific deployers (Vercel, Netlify, Cloudflare) or deploy to any Node.js hosting platform. Check our deployment guide for detailed instructions.

2. Direct Integration ✅

Better for smaller projects or prototypes. This approach bundles Kastrax directly with your Next.js application.

Initialize Kastrax in your Next.js Root

First, navigate to your Next.js project root and initialize Kastrax:

cd your-nextjs-app

Then run the initialization command:

npx kastrax@latest init

This will set up Kastrax in your Next.js project. For more details about init and other configuration options, see our kastrax init reference.

Configure Next.js

Add to your next.config.js:

next.config.js
/** @type {import('next').NextConfig} */ const nextConfig = { serverExternalPackages: ["@kastrax/*"], // ... your other Next.js config } module.exports = nextConfig

Server Actions Example

app/actions.ts
'use server' import { kastrax } from '@/kastrax' export async function getWeatherInfo(city: string) { const agent = kastrax.getAgent('weatherAgent') const result = await agent.generate(`What's the weather like in ${city}?`) return result }

Use it in your component:

app/components/Weather.tsx
'use client' import { getWeatherInfo } from '../actions' export function Weather() { async function handleSubmit(formData: FormData) { const city = formData.get('city') as string const result = await getWeatherInfo(city) // Handle the result console.log(result) } return ( <form action={handleSubmit}> <input name="city" placeholder="Enter city name" /> <button type="submit">Get Weather</button> </form> ) }

API Routes Example

app/api/chat/route.ts
import { kastrax } from '@/kastrax' import { NextResponse } from 'next/server' export async function POST(req: Request) { const { city } = await req.json() const agent = kastrax.getAgent('weatherAgent') const result = await agent.stream(`What's the weather like in ${city}?`) return result.toDataStreamResponse() }

Deployment

When using direct integration, your Kastrax instance will be deployed alongside your Next.js application. Ensure you:

  • Set up environment variables for your LLM API keys in your deployment platform
  • Implement proper error handling for production use
  • Monitor your AI agent’s performance and costs

Observability ✅

Kastrax provides built-in observability features to help you monitor, debug, and optimize your AI operations. This includes:

  • Tracing of AI operations and their performance
  • Logging of prompts, completions, and errors
  • Integration with observability platforms like Langfuse and LangSmith

For detailed setup instructions and configuration options specific to Next.js local development, see our Next.js Observability Configuration Guide.

Last updated on