Skip to main content

AI Kit Next.js

Server-side Next.js utilities for building AI-powered apps — streaming API routes, Server-Sent Events (SSE) helpers, and request/response utilities for both the App Router and Pages Router.

npm install @ainative/ai-kit-nextjs

Requires: Next.js 13/14/15 and React 18/19.

note

This SDK is in alpha (0.1.0-alpha.x). The API may change before 1.0.

Streaming route (App Router)

createStreamingRoute wraps a handler and returns an App Router route handler that streams AI completions to the client as SSE.

// app/api/chat/route.ts
import { createStreamingRoute } from '@ainative/ai-kit-nextjs';

export const POST = createStreamingRoute(async ({ request, stream }) => {
const { messages } = await request.json();
// stream tokens back to the client via the provided stream controller
await stream.fromCompletion({
apiUrl: 'https://api.ainative.studio/api/v1/chat/completions',
apiKey: process.env.AINATIVE_API_KEY!,
model: 'gpt-oss-120b',
messages,
});
});

createStreamingRoute(handler, config?) returns (request: NextRequest, context?) => Promise<Response>.

API route (Pages Router)

createAPIRoute produces a classic Pages Router handler ((req, res) => Promise<void>):

// pages/api/chat.ts
import { createAPIRoute } from '@ainative/ai-kit-nextjs';

export default createAPIRoute(async (req, res) => {
// ...handle the request, write JSON or stream via the SSE helpers below
});

SSE + response helpers

ExportPurpose
createSSEStream()Create an SSE stream you can write events to
sendSSEMessage(controller, msg)Push an SSEMessage through a stream controller
formatSSE(msg)Serialize a message to the SSE wire format
parseRequestBody(req, opts?)Parse/validate a request body (RequestParseOptions)
createSuccessResponse(data, opts?)Build a standard success Response
createErrorResponse(error, opts?)Build a standard error Response

Event types are enumerated by SSEEventType (TokenEvent, UsageEvent, MetadataEvent, ErrorEvent).

Middleware

CORS and related middleware live under the ./middleware subpath:

import { /* CORS helpers */ } from '@ainative/ai-kit-nextjs/middleware';

Configure allowed origins/methods with CORSConfig.

See also