Skip to main content

Next.js SDK

@ainative/next-sdk (v1.0.1, real published npm package) gives Server Components and Route Handlers a server-side API client and cookie-based auth helpers. The route handler below was built into a real Next.js app and verified with next build.

Install

npm install @ainative/next-sdk

Next.js version constraint found during live testing

This package declares a peer dependency on next: ^13.0.0 || ^14.0.0. A fresh create-next-app@latest today scaffolds Next 16, which fails install with an ERESOLVE peer-dependency conflict. Scaffold with Next 14 (npx create-next-app@14) if you want this SDK working out of the box.

Server client in an API route — verified with a real build

The real exported route-protection helper is withAuth (App Router) / withAuthPages (Pages Router) — not a separate middleware subpath.

// app/api/chat/route.ts
import { withAuth, createServerClient } from '@ainative/next-sdk/server';

export const POST = withAuth(async (req, { apiKey }) => {
  const client = createServerClient({ apiKey });
  const body = await req.json();

  const response = await client.chat.completions.create({
    messages: body.messages,
  });

  return Response.json(response);
});
Verified: next build compiles this route cleanly against Next.js 14.2.35.

Server Component reading a session

// app/dashboard/page.tsx
import { getSession, createServerClient, getApiKey } from '@ainative/next-sdk/server';
import { redirect } from 'next/navigation';

export default async function DashboardPage() {
  const session = await getSession();
  if (!session) redirect('/login');

  const apiKey = await getApiKey();
  const client = createServerClient({ apiKey: apiKey! });
  const balance = await client.credits.balance();

  return <div>Welcome {session.email} — credits: {balance.remaining_credits}</div>;
}

Pages Router equivalent

// pages/api/chat.ts
import { withAuthPages, createServerClient } from '@ainative/next-sdk/server';

export default withAuthPages(async (req, res, { apiKey }) => {
  const client = createServerClient({ apiKey });
  const response = await client.chat.completions.create({
    messages: req.body.messages,
  });
  res.status(200).json(response);
});

Reference

  • npm package: npmjs.com/package/@ainative/next-sdk
  • Auth cookie defaults to ainative_token — override with cookieName in withAuth(handler, options).
  • Prefer client-side React hooks? React SDK — also re-exported from @ainative/next-sdk/client.
ZeroDB — part of AINative Studio