Skip to main content

Next.js SDK

npm i @ainative/nextjs-sdk

Supports both App Router and Pages Router.

Server Client

Create a server-side client for API routes:

// app/api/chat/route.ts (App Router)
import { createServerClient } from '@ainative/nextjs-sdk';

export async function POST(req: Request) {
const client = createServerClient();
const { messages } = await req.json();

const stream = await client.chat.completions.create({
model: 'meta-llama/llama-3.3-70b-instruct',
messages,
stream: true,
});

return new Response(stream);
}

Environment Variables

AINATIVE_API_KEY=your-api-key
AINATIVE_PROJECT_ID=your-project-id

The server client reads these automatically.

Auth Middleware (App Router)

Protect routes with AINative authentication:

// middleware.ts
import { withAuth } from '@ainative/nextjs-sdk';

export default withAuth({
protectedPaths: ['/dashboard', '/api/protected'],
loginPath: '/login',
});

export const config = {
matcher: ['/dashboard/:path*', '/api/protected/:path*'],
};

Auth Middleware (Pages Router)

// pages/api/protected.ts
import { withAuthPages } from '@ainative/nextjs-sdk';

export default withAuthPages(async (req, res) => {
const { user } = req;
res.json({ user });
});

Session Helpers

import { getSession, getApiKey } from '@ainative/nextjs-sdk';

// In a Server Component or API route
const session = await getSession();
const apiKey = await getApiKey();

Streaming Pattern

// app/api/chat/route.ts
import { createServerClient } from '@ainative/nextjs-sdk';

export async function POST(req: Request) {
const client = createServerClient();
const { messages } = await req.json();

const response = await client.chat.completions.create({
model: 'meta-llama/llama-3.3-70b-instruct',
messages,
stream: true,
});

// Return as streaming response
return new Response(response, {
headers: { 'Content-Type': 'text/event-stream' },
});
}

Next Steps

  • React SDK — Client-side hooks (useChat, useCredits)
  • Python SDK — Server-side Python integration