Next.js Advanced

AI Integration

OpenAI API, streaming responses, AI chat, and server-side AI processing.

Advertisement

AI Integration

OpenAI API, streaming responses, AI chat, and server-side AI processing.

Overview

Next.js enables AI-powered features with server components and streaming.

Key Concepts

  • Server Components — Process AI on server
  • Streaming — Stream AI responses to client
  • Edge Runtime — Low-latency AI processing
  • Prompt Engineering — Design effective prompts
  • Rate Limiting — Control AI API usage

Code Examples

// app/api/chat/route.js
import OpenAI from 'openai';

const openai = new OpenAI();

export async function POST(request) {
  const { messages } = await request.json();

  const stream = await openai.chat.completions.create({
    model: 'gpt-4',
    messages,
    stream: true
  });

  return new Response(stream.toReadableStream(), {
    headers: { 'Content-Type': 'text/plain' }
  });
}

// Client component
'use client';
import { useState } from 'react';

function Chat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const userMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setLoading(true);

    const response = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ messages: [...messages, userMessage] })
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let assistantMessage = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      assistantMessage += decoder.decode(value);
      setMessages(prev => [
        ...prev.slice(0, -1),
        { role: 'assistant', content: assistantMessage }
      ]);
    }

    setLoading(false);
  };

  return (
    <div>
      <div className="messages">
        {messages.map((msg, i) => (
          <div key={i} className={msg.role}>
            {msg.content}
          </div>
        ))}
      </div>
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={(e) => setInput(e.target.value)} />
        <button type="submit" disabled={loading}>Send</button>
      </form>
    </div>
  );
}

Practice

Build an AI chat interface with streaming responses and conversation history.