@smarthivelabs-devs/next-ai-nexus
v1.0.0
Published
Next.js helpers for the SmartHive AI Nexus SDK
Readme
@smarthivelabs-devs/next-ai-nexus
Next.js helpers for the SmartHive AI Nexus. Provides secure server-side route handlers so your API key is never exposed to the browser, and an edge-safe client factory.
What this package is: A Next.js–specific layer on top of @smarthivelabs-devs/ai-nexus. It gives you a proxy handler (App Router and Pages Router) that forwards browser requests to the Nexus service, injecting the real API key on the server. Admin endpoints are always blocked regardless of configuration.
Requirements
- Next.js ≥ 14 (App Router or Pages Router)
@smarthivelabs-devs/ai-nexus≥ 1.0.0 (peer dependency)
Installation
npm install @smarthivelabs-devs/next-ai-nexus @smarthivelabs-devs/ai-nexus
# or
yarn add @smarthivelabs-devs/next-ai-nexus @smarthivelabs-devs/ai-nexusEnvironment 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_.
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 /api/nexus/v1/chat, /api/nexus/v1/embeddings, etc. without ever seeing the real API key.
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/ai-nexus';
export const nexus = new AiNexus({
apiKey: 'browser-client', // placeholder — real key injected server-side
baseUrl: '/api/nexus',
});Combined with react-ai-nexus:
// app/providers.tsx
import { AiNexusProvider } from '@smarthivelabs-devs/react-ai-nexus';
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/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/ai-nexus';
import type { ChatMessage } from '@smarthivelabs-devs/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
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.
TypeScript
All types are exported:
import type {
NexusRouteHandlerOptions,
NexusPagesHandlerOptions,
} from '@smarthivelabs-devs/next-ai-nexus';
// Core SDK types
import type { AiNexusClientOptions, ChatMessage } from '@smarthivelabs-devs/ai-nexus';License
MIT — © SmartHive Labs
