How to beginner · 4 min read

How to add AI to Next.js app

Quick answer
Add AI to a Next.js app by calling an LLM API like gpt-4o from your API routes or server components. Use the OpenAI SDK to send user prompts and receive AI-generated responses, then render them in your React UI.

PREREQUISITES

  • Node.js 18+
  • Next.js 13+
  • OpenAI API key (free tier works)
  • npm install openai

Setup

Install the official openai SDK and set your API key in environment variables for secure access.

bash
npm install openai

Step by step

Create a Next.js API route that uses the OpenAI SDK to call the gpt-4o model. Then, build a React component to send user input to this API and display the AI response.

typescript
import { NextApiRequest, NextApiResponse } from 'next';
import { OpenAI } from 'openai';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    res.status(405).json({ error: 'Method not allowed' });
    return;
  }

  const { prompt } = req.body;
  if (!prompt) {
    res.status(400).json({ error: 'Prompt is required' });
    return;
  }

  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: prompt }],
    });

    const aiText = response.choices[0].message.content;
    res.status(200).json({ result: aiText });
  } catch (error) {
    res.status(500).json({ error: 'OpenAI API request failed' });
  }
}

// React component example
import { useState } from 'react';

export default function AIChat() {
  const [prompt, setPrompt] = useState('');
  const [response, setResponse] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);
    const res = await fetch('/api/ai', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt }),
    });
    const data = await res.json();
    setResponse(data.result || 'No response');
    setLoading(false);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <textarea
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="Ask something..."
          rows={4}
          cols={50}
        />
        <br />
        <button type="submit" disabled={loading}>
          {loading ? 'Loading...' : 'Send'}
        </button>
      </form>
      <pre>{response}</pre>
    </div>
  );
}

Common variations

You can use async React components with useEffect for fetching AI responses, switch to streaming completions for real-time output, or try other models like gpt-4o-mini for faster, cheaper calls.

typescript
import { useState, useEffect } from 'react';

export default function StreamingAI() {
  const [prompt, setPrompt] = useState('Hello AI');
  const [response, setResponse] = useState('');

  useEffect(() => {
    async function fetchAI() {
      const res = await fetch('/api/ai', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ prompt }),
      });
      const data = await res.json();
      setResponse(data.result);
    }
    fetchAI();
  }, [prompt]);

  return (
    <div>
      <input value={prompt} onChange={e => setPrompt(e.target.value)} />
      <pre>{response}</pre>
    </div>
  );
}

Troubleshooting

  • If you get a 401 error, verify your OPENAI_API_KEY is set correctly in your environment.
  • For CORS issues, ensure API routes are called from the same Next.js domain or configure headers properly.
  • If responses are slow, try smaller models like gpt-4o-mini or cache results.

Key Takeaways

  • Use Next.js API routes to securely call AI models with the OpenAI SDK.
  • Render AI responses in React components by fetching from your API route.
  • Switch models or use streaming for cost and performance tuning.
  • Always keep your API key in environment variables, never in client code.
Verified 2026-04 · gpt-4o, gpt-4o-mini
Verify ↗