@smarthivelabs-devs/next-ai-nexus
v2.3.7
Published
Next.js helpers for the SmartHive AI Nexus SDK
Readme
@smarthivelabs-devs/next-ai-nexus
The Next.js entry point for AI Nexus. Install only this package in a Next app — it includes @smarthivelabs-devs/react-ai-nexus and @smarthivelabs-devs/ai-nexus, plus Next-only helpers (withAiNexus, route proxy, edge client).
Use @smarthivelabs-devs/react-ai-nexus alone only for non-Next React apps (Vite, CRA, Remix).
Automatic vision model provisioning
import { withAiNexus } from "@smarthivelabs-devs/next-ai-nexus";
const nextConfig = {};
export default withAiNexus(nextConfig, {
vision: { models: ["face", "object", "pose", "hand"] },
});The checksummed model and MediaPipe runtime assets are installed into /public/ai-nexus-models/0.10.35 during the Next.js build. The React SDK uses /ai-nexus-models/0.10.35 automatically. Set autoInstall: false only when deployment infrastructure provisions and verifies those assets separately.
What this package is: The full Next.js surface — React hooks/realtime/vision (via react-ai-nexus), the shared client (via ai-nexus), plus a secure proxy handler and build-time model provisioning. Admin endpoints are always blocked regardless of configuration.
Requirements
- Next.js ≥ 14 (App Router or Pages Router)
- The shared AI Nexus client and React SDK are included and re-exported automatically
- LiveKit / MediaPipe peers when using browser realtime vision
Installation
# Next.js apps — one package only
npm install @smarthivelabs-devs/next-ai-nexus
npm install livekit-client @mediapipe/tasks-vision # only if using realtime / vision
# or
yarn add @smarthivelabs-devs/next-ai-nexus livekit-client @mediapipe/tasks-visionDo not also install @smarthivelabs-devs/react-ai-nexus or @smarthivelabs-devs/ai-nexus in a Next app.
| Import from | Use for |
|---|---|
| @smarthivelabs-devs/next-ai-nexus | withAiNexus, route proxy, edge client, server AiNexus |
| @smarthivelabs-devs/next-ai-nexus/client | React hooks, providers, realtime, vision (Client Components) |
| App type | Install |
|---|---|
| Next.js | @smarthivelabs-devs/next-ai-nexus |
| React (Vite/CRA/Remix) | @smarthivelabs-devs/react-ai-nexus |
| Node backend only | @smarthivelabs-devs/ai-nexus |
Environment Setup
# Required — your API key. Keep this server-only (no NEXT_PUBLIC_ prefix).
AI_NEXUS_API_KEY=nexus_live_xxxxxxxxxxxxxxxxxxxx
# Optional — only needed if you're self-hosting or using a staging instance
# Default: https://api.smarthivelabs.dev
AI_NEXUS_BASE_URL=https://api.smarthivelabs.devAI_NEXUS_API_KEY must remain on the server. Never prefix it with NEXT_PUBLIC_.
Complete private realtime setup
1. Provision models in next.config.ts
import type { NextConfig } from "next";
import { withAiNexus } from "@smarthivelabs-devs/next-ai-nexus";
const config: NextConfig = {};
export default withAiNexus(config, {
vision: {
models: ["face", "object", "pose", "hand"],
},
});Builds fail immediately when a model cannot be downloaded or its checksum is invalid.
2. Add a protected App Router proxy
// app/api/nexus/[...path]/route.ts
import { createNexusRouteHandler } from "@smarthivelabs-devs/next-ai-nexus";
import { auth } from "@/auth";
export const runtime = "nodejs";
export const { GET, POST, PUT, PATCH, DELETE } = createNexusRouteHandler({
apiKey: process.env.AI_NEXUS_API_KEY!,
...(process.env.AI_NEXUS_BASE_URL
? { baseUrl: process.env.AI_NEXUS_BASE_URL }
: {}),
authenticate: async () => {
const session = await auth();
return session ? null : Response.json({ message: "Unauthorized" }, { status: 401 });
},
});Use project authentication and application authorization here. A logged-in user should only be able to create, resume, control, record, or inspect sessions that belong to that user or tenant.
3. Create the browser client and provider
// app/providers.tsx
"use client";
import {
AiNexus,
AiNexusProvider,
} from "@smarthivelabs-devs/next-ai-nexus/client";
const nexus = new AiNexus({
apiKey: "browser-proxy",
baseUrl: "/api/nexus",
});
export function Providers({ children }: { children: React.ReactNode }) {
return <AiNexusProvider client={nexus}>{children}</AiNexusProvider>;
}4. Start an interview session
"use client";
import { usePrivateAgentSession } from "@smarthivelabs-devs/next-ai-nexus/client";
export function InterviewRoom() {
const realtime = usePrivateAgentSession({
agentId: "interviewer-v1",
behavior: "interviewer",
vision: { preset: "interview" },
});
return (
<section>
<p>Connection: {realtime.readiness.signaling}</p>
<p>Media: {realtime.readiness.media}</p>
<p>Agent: {realtime.readiness.agent}</p>
<p>Vision: {realtime.readiness.vision}</p>
<button onClick={() => void realtime.start()}>Start interview</button>
<button onClick={() => void realtime.controller.control("interrupt")}>Stop AI speech</button>
<button onClick={() => void realtime.end()}>End interview</button>
</section>
);
}This connects LiveKit, publishes microphone/camera tracks, analyzes the existing local camera track, sends compact structured visual context, and automatically performs reliable replay after reconnecting.
Hybrid: trusted backend mints the session
When interview ownership and script metadata live in your Express (or other) API, mint the Nexus session there and join from the browser with RealtimeRoomSession:
import { RealtimeRoomSession } from "@smarthivelabs-devs/next-ai-nexus/client";
// 1) POST /api/interviews/:id/realtime-session → { livekit_url, livekit_token, resume_token }
// 2) Connect — mic, agent TTS playback, and optional vision are handled by the SDK:
const controller = new RealtimeRoomSession();
await controller.connect(livekitUrl, livekitToken, {
vision: {
config: { preset: "interview" },
metrics: { enabled: true, profile: "interview" },
},
});No livekit-client imports are required in application code for ordinary person-to-agent sessions. Keep AI_NEXUS_API_KEY on the trusted backend (or behind createNexusRouteHandler for browser-created sessions).
App Router — createNexusRouteHandler
Create a catch-all API route that securely proxies all Nexus requests. The handler:
- Injects the server-side API key on every request
- Blocks all admin paths automatically (
/admin/,/providers,/api-keys/generate, etc.) - Streams responses through (SSE, binary audio, etc.)
- Supports optional per-request authentication
Basic setup
// app/api/nexus/[...path]/route.ts
import { createNexusRouteHandler } from '@smarthivelabs-devs/next-ai-nexus';
export const { GET, POST, PUT, PATCH, DELETE } = createNexusRouteHandler({
apiKey: process.env.AI_NEXUS_API_KEY!,
});That's it. Your frontend can now call any Nexus endpoint through /api/nexus/:
| Endpoint | Capability |
|---|---|
| POST /api/nexus/v1/chat | Chat completions (streaming supported) |
| POST /api/nexus/v1/embeddings | Vector embeddings |
| POST /api/nexus/v1/audio/transcribe | Speech-to-text |
| POST /api/nexus/v1/audio/speak | Text-to-speech |
| POST /api/nexus/v1/images/generate | Image generation |
| POST /api/nexus/v1/videos/generate | Video generation |
| POST /api/nexus/v1/agents/run | AI agent execution |
| POST /api/nexus/v1/translate | Text translation (DeepL etc.) |
| POST /api/nexus/v1/video-understanding | Video analysis (Twelve Labs) |
| POST /api/nexus/v1/moderate | Content moderation |
| GET /api/nexus/v1/models | List model profiles |
The real API key is never sent to the browser.
With path whitelist
Restrict which endpoints the browser is allowed to call:
// app/api/nexus/[...path]/route.ts
export const { GET, POST, PUT, PATCH, DELETE } = createNexusRouteHandler({
apiKey: process.env.AI_NEXUS_API_KEY!,
allowedPaths: [
'/v1/chat',
'/v1/embeddings',
'/v1/agents/run',
'/v1/realtime/sessions',
],
// Any path not in this list → 403 Forbidden
});With user authentication
Require the user to be logged in before proxying requests (works with any auth library — NextAuth, Clerk, custom JWT, etc.):
// app/api/nexus/[...path]/route.ts
import { getServerSession } from 'next-auth';
import { createNexusRouteHandler } from '@smarthivelabs-devs/next-ai-nexus';
export const { GET, POST, PUT, PATCH, DELETE } = createNexusRouteHandler({
apiKey: process.env.AI_NEXUS_API_KEY!,
allowedPaths: ['/v1/chat', '/v1/embeddings'],
// Return a Response to reject the request, return null to allow it
authenticate: async (request) => {
const session = await getServerSession();
if (!session) {
return new Response(
JSON.stringify({ message: 'Unauthorized' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } },
);
}
return null; // allow
},
});Custom base URL (staging, self-hosted)
export const { GET, POST, PUT, PATCH, DELETE } = createNexusRouteHandler({
apiKey: process.env.AI_NEXUS_API_KEY!,
baseUrl: process.env.AI_NEXUS_BASE_URL ?? 'https://api.smarthivelabs.dev',
});Frontend usage after setup
With the proxy in place, configure your AiNexus client to point at it:
// lib/nexus.ts — safe to import in browser code
import { AiNexus } from '@smarthivelabs-devs/next-ai-nexus';
export const nexus = new AiNexus({
apiKey: 'browser-client', // placeholder — real key injected server-side
baseUrl: '/api/nexus',
});Provider (same package):
// app/providers.tsx
import { AiNexusProvider } from '@smarthivelabs-devs/next-ai-nexus/client';
import { nexus } from '@/lib/nexus';
export function Providers({ children }: { children: React.ReactNode }) {
return <AiNexusProvider client={nexus}>{children}</AiNexusProvider>;
}Pages Router — createNexusPageHandler
For projects using the /pages/api/ directory:
// pages/api/nexus/[...path].ts
import { createNexusPageHandler } from '@smarthivelabs-devs/next-ai-nexus';
export default createNexusPageHandler({
apiKey: process.env.AI_NEXUS_API_KEY!,
allowedPaths: ['/v1/chat', '/v1/embeddings'],
methods: ['GET', 'POST'], // optional — default allows all methods
});
// Important: disable Next.js body parser so binary and streaming responses work
export const config = { api: { bodyParser: false } };Edge Runtime — createEdgeClient
For use inside Edge API routes or middleware. The core AiNexus client already works in the Edge Runtime (it uses only fetch), but createEdgeClient makes the intent explicit and is safe to use without Node.js built-ins.
// app/api/summarise/route.ts
import { createEdgeClient } from '@smarthivelabs-devs/next-ai-nexus';
export const runtime = 'edge';
export async function POST(req: Request) {
const nexus = createEdgeClient({
apiKey: process.env.AI_NEXUS_API_KEY!,
});
const { text } = await req.json() as { text: string };
const result = await nexus.chat.create({
model: 'gpt-4o-mini',
messages: [
{ role: 'system', content: 'Summarise the following text in 2 sentences.' },
{ role: 'user', content: text },
],
max_tokens: 256,
});
return Response.json({ summary: result.choices[0]?.message.content });
}// app/api/embed/route.ts — Edge embeddings
import { createEdgeClient } from '@smarthivelabs-devs/next-ai-nexus';
export const runtime = 'edge';
export async function POST(req: Request) {
const nexus = createEdgeClient({ apiKey: process.env.AI_NEXUS_API_KEY! });
const { input } = await req.json() as { input: string[] };
const result = await nexus.embeddings.create({
model: 'text-embedding-3-small',
input,
});
return Response.json({ embeddings: result.data.map(d => d.embedding) });
}Server Component usage
Call Nexus APIs directly inside React Server Components — no proxy needed:
// app/dashboard/page.tsx
import { AiNexus } from '@smarthivelabs-devs/next-ai-nexus';
const nexus = new AiNexus({ apiKey: process.env.AI_NEXUS_API_KEY! });
export default async function DashboardPage() {
const [models, health] = await Promise.all([
nexus.models.list(),
nexus.health.check(),
]);
return (
<main>
<p>Service status: {health.status}</p>
<ul>
{models.map(m => (
<li key={m.id}>{m.name} — {m.capabilities.join(', ')}</li>
))}
</ul>
</main>
);
}Server Action usage
// app/actions/chat.ts
'use server';
import { AiNexus } from '@smarthivelabs-devs/next-ai-nexus';
import type { ChatMessage } from '@smarthivelabs-devs/next-ai-nexus';
const nexus = new AiNexus({ apiKey: process.env.AI_NEXUS_API_KEY! });
export async function sendMessage(messages: ChatMessage[]) {
const res = await nexus.chat.create({
model: 'claude-sonnet-4-6',
messages,
});
return res.choices[0]?.message.content ?? '';
}Options Reference
withAiNexus
| Option | Type | Default | Description |
|---|---|---|---|
| vision.models | ("face" \| "object" \| "pose" \| "hand")[] | [] | Models installed into the public build output |
| vision.autoInstall | boolean | true | Download and checksum models during config evaluation |
| vision.outputDirectory | string | public/ai-nexus-models/0.10.35 | Model and WASM output directory |
When autoInstall is false, provision the same versioned assets before next build; otherwise browser vision reports reduced capability.
NexusRouteHandlerOptions
interface NexusRouteHandlerOptions {
// Required — server-side API key, never sent to the browser
apiKey: string;
// Optional — AI Nexus base URL
// Default: https://api.smarthivelabs.dev
baseUrl?: string;
// Optional — array of path prefixes the browser is allowed to call
// Example: ['/v1/chat', '/v1/embeddings']
// When omitted, all non-admin paths are allowed
allowedPaths?: string[];
// Optional — return a Response to block the request, return null to allow
// Use this to check session auth, rate limits, etc.
authenticate?: (request: Request) => Promise<Response | null> | Response | null;
// Optional — extra options forwarded to the AiNexus client (timeout, maxRetries, etc.)
clientOptions?: Partial<AiNexusClientOptions>;
}NexusPagesHandlerOptions
Extends NexusRouteHandlerOptions with one extra field for Pages Router:
interface NexusPagesHandlerOptions extends NexusRouteHandlerOptions {
// Optional — HTTP methods allowed through the proxy
// Default: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
methods?: string[];
}Security: blocked admin paths
The proxy handler always blocks these paths regardless of allowedPaths:
/admin/— all admin routes/providers— provider CRUD/api-keys/generate— API key generation/model-profiles/create|update|delete/agents/create|update|delete/projects/create|update|delete
A request to any of these paths returns 403 Forbidden immediately.
Realtime endpoints still require application-level ownership checks. Authenticating a request does not by itself prevent one authenticated account from operating another account's sessionId or resume token.
Deployment notes
- Cache
public/ai-nexus-modelsin CI when possible; checksum verification makes reuse deterministic. - Keep model files as static application assets instead of routing them through the Nexus proxy.
- Serve
.wasmfiles withapplication/wasmwhere your hosting platform permits explicit MIME configuration. - Browser camera and microphone APIs require HTTPS outside localhost.
- Never expose
AI_NEXUS_API_KEYthroughNEXT_PUBLIC_*, client components, build metadata, logs, or error responses. useRealtimeMeetingrequires a separately deployed multi-participant worker. Use private topology for ordinary person-to-agent sessions.
TypeScript
All types are exported:
import type {
NexusRouteHandlerOptions,
NexusPagesHandlerOptions,
AiNexusNextOptions,
} from '@smarthivelabs-devs/next-ai-nexus';
// Shared client types are re-exported by this package.
import type { AiNexusClientOptions, ChatMessage } from '@smarthivelabs-devs/next-ai-nexus';License
MIT — © SmartHive Labs
