ai engineering#AI Integration#Next.js#Web Development

Integrating AI into Web Apps: Architecture, Streaming & Production Best Practices

RB
Rajput BhavinArchitect
Founder, Rajput Bhavin Engineering
24 August 2026•10 min read

Quick Answer: Production AI Web Integration#

⚡ Quick Answer / Executive Summary
Integrating AI models (OpenAI GPT-4o, Claude 3.7, Google Gemini 2.5, Groq) into web applications requires a secure BFF (Backend-For-Frontend) architecture. Developers must never expose API keys on the client, implement Server-Sent Events (SSE) or WebSockets for token streaming, enforce Redis-backed token bucket rate-limiting, and validate all LLM inputs and outputs using strict TypeScript schemas.

4 Critical Architectural Pitfalls in AI Web Apps#

Most naive AI integrations suffer from critical vulnerabilities and performance bottlenecks:

  1. ✓Client-Side API Key Leaks: Calling OpenAI or Anthropic APIs directly from React useEffect hooks, exposing API keys in public browser network tabs.
  2. ✓Blocking HTTP Requests: Waiting 10+ seconds for the model to finish generating the entire response before rendering, creating a broken user experience.
  3. ✓Runaway Token Costs: Failing to implement per-user token quotas, allowing malicious actors or automated bots to drain thousands of dollars from your billing account in hours.
  4. ✓Lack of Idempotency: Users clicking "Submit" multiple times during slow generations, spawning duplicate background LLM calls and wasting compute credits.

The Production AI Web Architecture Blueprint#

Architecture Blueprint
System Flow
┌─────────────────────────────────────────────────────────────┐
│                 Client Layer (Browser / Mobile)             │
│    React 19 / Next.js 15 UI  •  SSE Stream Consumer         │
└─────────────────────────────┬─────────────────────────────┘
                              │ HTTPS (Encrypted Session Token)
┌─────────────────────────────▼─────────────────────────────┐
│              Next.js 15 Edge Route Handler (BFF)            │
│   ┌─────────────────────────────────────────────────────┐   │
│   │ 1. Auth & Session Validation (JWT / Supabase Auth)  │   │
│   │ 2. Rate Limiting & Token Quota Check (Upstash Redis)│   │
│   │ 3. Prompt Injection Sanitization & Delimiting       │   │
│   └─────────────────────────┬───────────────────────────┘   │
└─────────────────────────────┼───────────────────────────────┘
                              │ Internal API Key (Encrypted Secret)
┌─────────────────────────────▼───────────────────────────────┐
│            Frontier AI Providers (Groq / Gemini / OpenAI)   │
│      Chunked Token Stream (Server-Sent Events: text/event-stream)
└─────────────────────────────────────────────────────────────┘

Production Implementation: Secure Streaming Handler in Next.js 15#

Here is the hardened Next.js 15 Route Handler implemented by Rajput Bhavin Engineering:

TypeScript
Production Code
import { NextRequest, NextResponse } from 'next/server';
import { Redis } from '@upstash/redis';
import { Ratelimit } from '@upstash/ratelimit';

// Initialize Redis Rate Limiting (10 AI requests per minute per IP)
const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});

const ratelimit = new Ratelimit({
  redis,
  limiter: Ratelimit.slidingWindow(10, '60 s'),
});

export const runtime = 'edge';

export async function POST(req: NextRequest) {
  const ip = req.headers.get('x-forwarded-for') || '127.0.0.1';
  const { success } = await ratelimit.limit(ip);

  if (!success) {
    return NextResponse.json(
      { error: 'Rate limit exceeded. Please wait a minute before sending more queries.' },
      { status: 429 }
    );
  }

  const { prompt } = await req.json();
  if (!prompt || typeof prompt !== 'string' || prompt.length > 2000) {
    return NextResponse.json({ error: 'Invalid prompt payload.' }, { status: 400 });
  }

  // Forward to LLM Provider via Edge Fetch
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4o',
      messages: [
        {
          role: 'system',
          content: 'You are a concise, enterprise technical assistant at Rajput Bhavin Engineering.',
        },
        { role: 'user', content: prompt },
      ],
      stream: true,
      max_tokens: 1000,
    }),
  });

  if (!response.ok) {
    return NextResponse.json({ error: 'Upstream AI provider error' }, { status: 502 });
  }

  return new Response(response.body, {
    headers: {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache, no-transform',
    },
  });
}

4 Best Practices for AI Web Applications#

#1. Implement Optimistic UI & Typing Indicators

Do not leave users staring at a disabled button. Display animated skeleton loaders or real-time typing indicators within 50 milliseconds of their click.

#2. Client-Side Abort Controllers

Allow users to stop a generating response immediately. Wire the browser's native `AbortController` to the fetch request to disconnect the socket and save backend token compute costs.

#3. Local In-Browser Caching

Cache identical queries locally in `IndexedDB` or `localStorage`. If a user repeats an identical question, return the cached answer instantly without making a network round-trip.

#4. Continuous Telemetry & Feedback Loops

Add simple 👍 / 👎 feedback widgets beneath AI responses. Log user ratings and token counts to Sentry or PostHog to continuously optimize prompt performance.

Engineer Production AI Systems with Rajput Bhavin Engineering#

Don't settle for fragile AI wrappers. Build enterprise-grade AI software designed for speed, security, and scale.

AI Engineering & Automation

Have a workflow you want to automate with AI?

Rajput Bhavin Engineering builds custom AI agents, RAG knowledge systems, and intelligent automation workflows for businesses in Ahmedabad, Gujarat, and globally.

RB

Rajput Bhavin

Systems Architect

Founder and Systems Architect at Rajput Bhavin Engineering in Gota, Ahmedabad. Specializes in high-concurrency cloud software, Next.js web applications, multi-tenant SaaS architecture, and autonomous AI systems.

Connect Now