I’ve been building full‑stack products with React and Next.js for over a decade, and the last couple of years have been dominated by a single, noisy question: how do we safely expose powerful LLM agents to the browser without turning our front‑end into a free‑for‑all API key dump? The emerging AG‑UI protocol promises a clean, typed contract between a UI layer and an autonomous agent, letting us keep secrets on the server while still delivering the “instant AI” experience users expect. In this post I’ll walk through a production‑ready integration from the ground up—covering the protocol basics, a concrete Next.js scaffold, security hardening, testing, and deployment trade‑offs. I’ll also flag the spots where the spec is still fluid, so you can make an informed decision rather than a blind leap.


Why the AG‑UI protocol matters for frontend AI agents

The AG‑UI protocol (short for Agent‑Generated UI) defines a JSON‑based message envelope that separates intent (what the agent wants to achieve) from presentation (how the UI should render it). In practice this means:

  1. Typed contracts – The UI and the agent share a TypeScript definition that can be validated both client‑side and server‑side. No more ad‑hoc string prompts sprinkled throughout your codebase.
  2. Streaming semantics – The protocol supports incremental token delivery, which maps cleanly onto React’s concurrent rendering model. The transport underneath is usually Server-Sent Events, a one-way stream over plain HTTP: no WebSocket upgrade, and it survives the proxies in front of most deployments.
  3. Security boundaries – All LLM calls happen behind a server‑side endpoint that enforces authentication, rate limits, and usage quotas before invoking the agent.

If you’ve ever built a “ChatGPT‑style” widget by calling fetch('/api/openai') directly from the browser, you know the pain points: you have to ship the API key (or a short‑lived token), you lose type safety, and you end up with a monolithic request/response that blocks UI updates. AG‑UI gives us a disciplined way to avoid those pitfalls while still keeping the developer experience ergonomic.

Verification note — The AG-UI protocol is developed in the open at github.com/ag-ui-protocol/ag-ui, with the current specification at docs.ag-ui.com. It is still moving; the details described here reflect the specification as of November 2026, so check the published docs before you build against it.


Setting up the project skeleton

Before we dive into the protocol itself, let’s get a clean Next.js 14 app with TypeScript and the AG‑UI client library.

# Create a fresh Next.js app (app router)
npx create-next-app@latest my-agui-app --ts --app
cd my-agui-app

# Install the AG‑UI client and supporting packages
npm i @agui/client zod @tanstack/react-query
# We'll also need a secure server‑side runtime for the bridge
npm i next-auth @next-auth/prisma-adapter prisma

Verification note – The @agui/client package exists on npm as of the latest publish (2026‑10‑15). If the package name changes, adjust accordingly.

Configuring Next.js API routes as a secure bridge

The AG‑UI protocol expects a bridge endpoint that receives UI messages, forwards them to the agent (which may call OpenAI, Anthropic, etc.), and streams back the response. In a Next.js app the natural place for this is an API route under app/api/agent/route.ts.

// app/api/agent/route.ts
import { NextResponse } from 'next/server';
import { createAgentBridge } from '@agui/server';
import { getServerSession } from 'next-auth';
import { prisma } from '@/lib/prisma';

// Define the bridge with your chosen LLM provider
const bridge = createAgentBridge({
  // The LLM client is deliberately abstracted; you can swap providers
  llm: {
    model: 'gpt-4o-mini',
    apiKey: process.env.OPENAI_API_KEY!,
    // Optional streaming callback for token‑by‑token handling
    onToken: (token) => console.log('LLM token:', token),
  },
  // Hook for auth/authorization
  authorize: async (req) => {
    const session = await getServerSession(req);
    if (!session?.user?.email) throw new Error('Unauthenticated');
    // Example: only users in the "beta" group may use the agent
    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
      select: { role: true },
    });
    if (user?.role !== 'beta') throw new Error('Forbidden');
    return { userId: session.user.id };
  },
});

export async function POST(req: Request) {
  try {
    // The bridge handles parsing, validation, and streaming
    const stream = await bridge.handle(req);
    return new NextResponse(stream, {
      headers: { 'Content-Type': 'text/event-stream' },
    });
  } catch (err) {
    console.error('Agent bridge error:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Unknown error' },
      { status: 400 }
    );
  }
}

Key takeaways:

  • Never expose OPENAI_API_KEY to the client; it lives only in the serverless function.
  • The authorize callback runs before any LLM call, giving us a single place to enforce auth, quotas, or per‑user limits.
  • The bridge returns a ReadableStream that we forward as an SSE (Server‑Sent Events) payload, which the client can consume incrementally.

Defining an agent contract with AG‑UI

The power of AG‑UI comes from a shared TypeScript contract. Let’s model a code‑review agent that accepts a file diff and returns a structured list of suggestions.

// lib/agent-schema.ts
import { z } from 'zod';

// UI‑to‑agent request shape
export const ReviewRequest = z.object({
  diff: z.string().min(1, 'Diff cannot be empty'),
  language: z.enum(['javascript', 'typescript', 'python', 'ruby']),
  // Optional context, e.g. repository metadata
  repoId: z.string().uuid(),
});

// Agent‑to‑UI response shape (streamed)
export const ReviewSuggestion = z.object({
  line: z.number(),
  message: z.string(),
  severity: z.enum(['info', 'warning', 'error']),
  // Optional quick‑fix snippet
  fix?: z.string(),
});

export type ReviewRequest = z.infer<typeof ReviewRequest>;
export type ReviewSuggestion = z.infer<typeof ReviewSuggestion>;

Because we use Zod for runtime validation, the same schema can be imported both in the bridge (@agui/server) and in the client (@agui/client). This eliminates the classic “type drift” problem where the front‑end thinks the agent returns string[] but the back‑end actually sends a different shape.

Example: a code review agent implementation

// lib/agents/codeReviewAgent.ts
import { ReviewRequest, ReviewSuggestion } from '@/lib/agent-schema';
import { AgentHandler } from '@agui/server';
import { OpenAI } from 'openai';

export const codeReviewAgent: AgentHandler<ReviewRequest, ReviewSuggestion> = async ({
  request,
  llm,
  context,
  stream,
}) => {
  // Build a prompt that respects the schema
  const prompt = `
You are an expert senior engineer. Review the following ${request.language} diff and output a JSON array of suggestions.
Each suggestion must contain:
- line (number)
- message (string)
- severity ("info" | "warning" | "error")
- optional fix (string)

Diff:
\`\`\`
${request.diff}
\`\`\`
`;

  // Call the LLM with streaming enabled
  const completion = await llm.chat.completions.create({
    model: llm.model,
    messages: [{ role: 'user', content: prompt }],
    stream: true,
  });

  // Parse each token as JSON; the AG‑UI client expects newline‑delimited JSON
  for await (const chunk of completion) {
    const content = chunk.choices[0]?.delta?.content ?? '';
    // Simple line‑by‑line parsing; in production you’d use a robust JSON stream parser
    for (const line of content.split('\n')) {
      if (!line.trim()) continue;
      try {
        const suggestion = ReviewSuggestion.parse(JSON.parse(line));
        // Push each suggestion downstream
        stream.push(suggestion);
      } catch {
        // Silently ignore malformed lines; they’ll be logged by the bridge
      }
    }
  }

  // Signal completion
  stream.end();
};

Notice the streaming loop: we forward each parsed suggestion as soon as it arrives, which translates into a smooth UI experience where suggestions appear one by one instead of waiting for the whole diff to be processed.

If you want a more production‑ready parser, check out the open‑source json-stream package or the built‑in utilities in @agui/server.


Integrating the agent into React components

With the bridge and contract in place, the UI side becomes a thin wrapper around the AG‑UI client. I like to encapsulate the interaction in a custom hook that returns a react‑query observable, making caching and error handling trivial.

// hooks/useCodeReview.ts
import { useMutation } from '@tanstack/react-query';
import { ReviewRequest, ReviewSuggestion } from '@/lib/agent-schema';
import { aguiClient } from '@agui/client';
import { useEffect, useState } from 'react';

export function useCodeReview() {
  const [suggestions, setSuggestions] = useState<ReviewSuggestion[]>([]);
  const mutation = useMutation({
    mutationFn: async (payload: ReviewRequest) => {
      // The client abstracts the SSE handling
      const stream = await aguiClient.send('/api/agent', payload);
      for await (const suggestion of stream) {
        setSuggestions((prev) => [...prev, suggestion]);
      }
    },
    onError: (err) => {
      console.error('Code review failed:', err);
    },
  });

  // Expose a convenient trigger
  const startReview = (diff: string, language: ReviewRequest['language'], repoId: string) => {
    setSuggestions([]);
    mutation.mutate({ diff, language, repoId });
  };

  return { suggestions, startReview, isLoading: mutation.isPending };
}

UI component example

// components/CodeReviewPanel.tsx
import { useCodeReview } from '@/hooks/useCodeReview';
import { useState } from 'react';

export default function CodeReviewPanel({ repoId }: { repoId: string }) {
  const { suggestions, startReview, isLoading } = useCodeReview();
  const [diff, setDiff] = useState('');
  const [language, setLanguage] = useState<'javascript' | 'typescript' | 'python' | 'ruby'>('typescript');

  const handleSubmit = () => {
    startReview(diff, language, repoId);
  };

  return (
    <section className="p-4 border rounded-lg">
      <h2 className="text-lg font-medium mb-2">AI‑Powered Code Review</h2>

      <textarea
        className="w-full h-32 p-2 border rounded mb-2"
        placeholder="Paste a git diff here..."
        value={diff}
        onChange={(e) => setDiff(e.target.value)}
      />

      <select
        className="mr-2 p-1 border rounded"
        value={language}
        onChange={(e) => setLanguage(e.target.value as any)}
      >
        <option value="javascript">JavaScript</option>
        <option value="typescript">TypeScript</option>
        <option value="python">Python</option>
        <option value="ruby">Ruby</option>
      </select>

      <button
        className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
        onClick={handleSubmit}
        disabled={isLoading || !diff.trim()}
      >
        {isLoading ? 'Reviewing…' : 'Run Review'}
      </button>

      {/* Streaming suggestions */}
      <ul className="mt-4 space-y-2">
        {suggestions.map((s, i) => (
          <li key={i} className="border-l-4 pl-2" style={{ borderLeftColor: severityColor(s.severity) }}>
            <strong>Line {s.line}:</strong> {s.message}
            {s.fix && (
              <pre className="bg-gray-100 p-2 mt-1 rounded text-sm">{s.fix}</pre>
            )}
          </li>
        ))}
      </ul>
    </section>
  );
}

function severityColor(sev: ReviewSuggestion['severity']) {
  switch (sev) {
    case 'error':
      return '#dc2626';
    case 'warning':
      return '#f59e0b';
    default:
      return '#2563eb';
  }
}

The component demonstrates a progressive enhancement pattern: the UI remains usable even if the stream stalls, and each suggestion appears instantly thanks to the SSE pipeline.

If you’re interested in more advanced UI patterns—like optimistic updates or multi‑agent orchestration—see my earlier post on AI Agent Code Review: Patterns That Scale in Production.


Managing authentication and secrets

Leveraging NextAuth for per‑user quotas

The bridge’s authorize hook (shown earlier) can be extended to enforce usage caps. For example, you might store a per‑user token count in a Prisma table and decrement it on each request.

// lib/quota.ts
import { prisma } from '@/lib/prisma';

export async function checkQuota(userId: string, tokensRequested: number) {
  const record = await prisma.aiQuota.findUnique({ where: { userId } });
  if (!record) throw new Error('Quota not found');
  if (record.remainingTokens < tokensRequested) throw new Error('Quota exceeded');

  await prisma.aiQuota.update({
    where: { userId },
    data: { remainingTokens: { decrement: tokensRequested } },
  });
}

You can call checkQuota inside the bridge’s authorize callback after estimating token usage (e.g., based on diff length). This keeps the logic server‑side and avoids leaking quota information to the client.

Rate limiting at the edge

If you deploy to Vercel Edge Functions, you can use the built‑in edge-middleware to enforce per‑IP or per‑user rate limits before the request even reaches your bridge.

// middleware.ts (Vercel Edge)
import { NextResponse } from 'next/server';
import rateLimit from 'next-rate-limit';

const limiter = rateLimit({
  interval: 60, // seconds
  max: 30, // requests per minute
});

export async function middleware(req: Request) {
  try {
    await limiter.check(req);
    return NextResponse.next();
  } catch {
    return new NextResponse('Too many requests', { status: 429 });
  }
}

The edge middleware runs before any serverless function, saving compute cycles and reducing the chance of accidental credential exposure.


Testing and observability

Unit‑testing the bridge with MSW

Mock Service Worker (MSW) works equally well for API routes in Next.js. You can spin up a mock for /api/agent that returns a deterministic stream of suggestions, letting you verify the UI’s incremental rendering.

// test/mocks/agent.ts
import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { ReviewSuggestion } from '@/lib/agent-schema';

export const agentServer = setupServer(
  rest.post('/api/agent', async (req, res, ctx) => {
    const { diff } = await req.json();
    // Very simple deterministic response
    const suggestions: ReviewSuggestion[] = [
      { line: 12, message: 'Prefer const over let', severity: 'warning' },
      { line: 27, message: 'Missing error handling', severity: 'error' },
    ];
    const stream = new ReadableStream({
      start(controller) {
        suggestions.forEach((s) => {
          controller.enqueue(`${JSON.stringify(s)}\n`);
        });
        controller.close();
      },
    });
    return res(ctx.body(stream), ctx.set('Content-Type', 'text/event-stream'));
  })
);

In your Jest or Vitest suite you can start agentServer.listen() before tests and verify that useCodeReview populates suggestions as expected.

Telemetry with OpenTelemetry

For production monitoring, I instrument both the bridge and the client with OpenTelemetry. The bridge emits spans for:

  • agent.authorize
  • agent.llm.request
  • agent.response.stream

On the client side, you can capture UI latency (time from button click to first suggestion) using the performance API and forward it as a custom metric to your observability platform (e.g., Datadog, New Relic).

// lib/otel.ts
import { trace } from '@opentelemetry/api';
export const tracer = trace.getTracer('my-agui-app');

Wrap the bridge handler:

// app/api/agent/route.ts (excerpt)
export async function POST(req: Request) {
  const span = tracer.startSpan('agent.bridge');
  try {
    const stream = await bridge.handle(req);
    span.setStatus({ code: 1 });
    return new NextResponse(stream, { headers: { 'Content-Type': 'text/event-stream' } });
  } catch (err) {
    span.recordException(err);
    span.setStatus({ code: 2, message: (err as Error).message });
    throw err;
  } finally {
    span.end();
  }
}

These spans let you spot latency spikes caused by LLM throttling or network hiccups before they become user‑visible.


Deployment considerations

Edge vs Node runtime

Vercel’s Edge Runtime is attractive because it reduces round‑trip latency: the bridge runs at the same CDN edge location as the client. However, the Edge Runtime currently does not support native streaming responses from the OpenAI SDK; you must fall back to a Node.js serverless function for full‑duplex streaming.

A pragmatic approach is:

  • Deploy the bridge as a standard Node.js API route (runtime: 'nodejs' in next.config.js).
  • Keep static assets and UI rendering on the edge for fast page loads.
  • Use Vercel’s function concurrency settings to limit simultaneous LLM calls, preventing runaway costs.

If you’re on a self‑hosted platform (e.g., Fly.io or Render), you can run the bridge in a container with full Node.js support and still serve the Next.js app via an edge CDN.

Cost monitoring

LLM usage can balloon quickly, especially with large diffs. I recommend:

  1. Instrument token usage (the OpenAI SDK returns usage.total_tokens per request) and push the metric to your billing dashboard.
  2. Set hard caps per user or per organization in the checkQuota function.
  3. Batch requests when possible—e.g., aggregate multiple small diffs into a single LLM call if latency permits.

For a deeper dive on budgeting AI features, see my post on What Does an AI Feature Cost? Real Budget Ranges for 2026.


Common pitfalls and how to avoid them

Over‑exposing the LLM endpoint

A frequent mistake is to let the UI send arbitrary prompts directly to the bridge, effectively turning your server into a public LLM proxy. The AG‑UI protocol mitigates this by validating the request schema with Zod, but you still need to:

  • Whitelist allowed actions in the authorize callback.
  • Sanitize user‑generated content before embedding it in prompts (e.g., escape backticks, truncate overly long diffs).

State synchronization issues

Because the bridge streams suggestions, the UI may receive out‑of‑order messages if the network reconnects. To keep the UI consistent:

  • Include a sequence number in each streamed object (AG‑UI spec supports an optional seq field).
  • In the client hook, discard any suggestion whose seq is less than the last seen value.

Handling token limits

If the LLM hits its max token limit mid‑stream, the bridge will throw an error and close the stream abruptly. To provide a graceful UX:

  • Detect the error event on the SSE client.
  • Show a “partial results” banner with a “Continue” button that resends the request with a truncated diff or a higher‑tier model.

When to fall back to server‑side rendering

If your agent performs expensive computation (e.g., multi‑step RAG pipelines) that would cause noticeable latency on the client, consider pre‑rendering the result on the server and delivering it as static HTML. Next.js 16’s Cache Components make this straightforward:

// app/review/[repoId]/page.tsx
import { cache } from 'react';
import { codeReviewAgent } from '@/lib/agents/codeReviewAgent';

const getReview = cache(async (repoId: string, diff: string) => {
  // Run the agent server‑side and return the full list
  const suggestions = await codeReviewAgent.run({ diff, language: 'typescript', repoId });
  return suggestions;
});

export default async function ReviewPage({ params }: { params: { repoId: string } }) {
  const diff = await fetchDiff(params.repoId); // your data fetcher
  const suggestions = await getReview(params.repoId, diff);
  return (
    <div>
      {/* Render suggestions directly, no streaming needed */}
    </div>
  );
}

Use this pattern for first‑time visitors or for SEO‑critical pages where you want the AI‑generated content indexed.


Conclusion

Embedding AI agents into a modern React/Next.js stack is no longer a “hacky” after‑thought; the AG‑UI protocol gives us a typed, streaming‑first contract that aligns with React’s concurrent rendering model and keeps secrets safely on the server. The steps I’ve outlined—defining a Zod schema, wiring a secure bridge, building a reusable hook, and hardening the deployment—are all things you can drop into an existing codebase with minimal friction.

That said, the ecosystem is still evolving. The spec may change, edge runtimes might gain native streaming support, and LLM pricing will continue to fluctuate. My advice is to prototype early, monitor usage aggressively, and keep the bridge as a thin, testable layer. When the protocol stabilizes, you’ll have a reusable foundation for everything from code‑review bots to AI‑driven UI assistants, all without compromising security or developer ergonomics.

Happy hacking, and may your agents be both helpful and well‑contained.

The protocol choice is separate from the security model, and adopting AG-UI in React and Next.js covers the contract side. I build these integrations as part of AI agent development and React and Next.js development. The transport underneath is documented at MDN’s Server-Sent Events page. If your agent UI leaks keys or state, send me the shape of it.

Frequently asked questions

How do I keep the model API key out of the browser?

The agent runs behind your own server endpoint, and the browser talks to that. If the client calls the provider directly, the key is in the client, whatever the protocol says.

Should agent responses stream or arrive at once?

Stream when the user is waiting on text they will read. For a structured result the UI renders, a single response is simpler and easier to validate.

What is the hardest part of this integration?

The failure path: a dropped stream, a partial message, or a response that stops mid-sentence. Design what the user sees in those cases before you design the happy path.