CognitiveX Docs

Build a chat app with iCog

A minimal Next.js example that streams responses from api.cognitivx.io.

This guide walks through a minimal chat UI backed by iCog's /api/chat endpoint. We use the SDK and Server-Sent Events for streaming.

Setup

pnpm create next-app@latest my-icog-chat
cd my-icog-chat
pnpm add @cognitivx/sdk

Server route

// app/api/chat/route.ts
import { CognitiveX } from "@cognitivx/sdk";

export async function POST(req: Request) {
  const { message } = await req.json();
  const cogx = new CognitiveX({ apiKey: process.env.COGNITIVX_API_KEY! });
  const stream = await cogx.chat.stream({ message });
  return new Response(stream, {
    headers: { "content-type": "text/event-stream" },
  });
}

Client

"use client";
import { useState } from "react";

export default function Chat() {
  const [reply, setReply] = useState("");
  const ask = async (msg: string) => {
    setReply("");
    const r = await fetch("/api/chat", { method: "POST", body: JSON.stringify({ message: msg }) });
    const reader = r.body!.getReader();
    const decoder = new TextDecoder();
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      setReply((r) => r + decoder.decode(value));
    }
  };
  return <button onClick={() => ask("Hello, iCog")}>Ask · {reply}</button>;
}

That's it — every call accumulates into the same user's memory.