SaketSingh

Basics of Integrating OpenAI API in Next.js (Step-by-Step Guide)

👤Saket Singh
|
đź“…September 7, 2025
|
⏱️4 min read
Basics of Integrating OpenAI API in Next.js (Step-by-Step Guide)

Artificial Intelligence is no longer a “nice-to-have” – it’s becoming a must-have in modern applications. With tools like OpenAI’s GPT models, you can easily add AI-powered chat, content generation, or assistants into your Next.js apps.

In this guide, I’ll walk you through how to integrate the OpenAI API into a Next.js project and build a simple ChatGPT-like interface. By the end, you’ll have a working chatbot running locally on your machine.


Step 1: Install Dependencies

In your Next.js project, open the terminal and install the official OpenAI SDK:

npm install openai

This package lets you interact with OpenAI’s API without having to worry about low-level HTTP requests.


Step 2: Get Your OpenAI API Key

To connect your app with OpenAI:

  1. Go to OpenAI API Keys.
  2. Create a new API key.
  3. Copy the key somewhere safe. You’ll need it soon.

⚠️ Keep this key secret – never share or expose it in public repos.


Step 3: Setup Environment Variables

Inside your Next.js project root, create a .env.local file and add your key:
OPENAI_API_KEY=your_api_key_here
👉 Important: .env.local should never be committed to GitHub. (Add it to your .gitignore if it’s not already there.)

Step 4: Create an API Route in Next.js

With the App Router (Next.js 13+), you can set up an API route under app/api/chat/route.ts. This route will handle requests from your chat UI and talk to OpenAI.
import { NextResponse } from "next/server";
import OpenAI from "openai";

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

export async function POST(req: Request) {
  try {
    const { messages } = await req.json();

    const completion = await client.chat.completions.create({
      model: "gpt-4o-mini", // or gpt-4o / gpt-3.5-turbo
      messages,
    });

    return NextResponse.json({ reply: completion.choices[0].message });
  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

This file does the heavy lifting:

  • Accepts chat messages from the frontend.
  • Sends them to OpenAI’s API.
  • Returns the assistant’s reply.

Step 5: Build a Simple Chat UI

Now let’s create a basic chat page at app/chat/page.tsx:
"use client";
import { useState } from "react";

export default function ChatPage() {
  const [messages, setMessages] = useState<{ role: string; content: string }[]>([]);
  const [input, setInput] = useState("");

  const sendMessage = async () => {
    if (!input.trim()) return;

    const newMessage = { role: "user", content: input };
    setMessages([...messages, newMessage]);
    setInput("");

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

    const data = await res.json();
    if (data.reply) {
      setMessages((prev) => [...prev, data.reply]);
    }
  };

  return (
    <div style={{ padding: "20px" }}>
      <h2>ChatGPT in Next.js</h2>
      <div style={{ border: "1px solid #ccc", padding: "10px", height: "400px", overflowY: "auto" }}>
        {messages.map((msg, i) => (
          <p key={i}><b>{msg.role}:</b> {msg.content}</p>
        ))}
      </div>
      <div style={{ marginTop: "10px" }}>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          style={{ width: "70%", padding: "8px" }}
          placeholder="Type your message..."
        />
        <button onClick={sendMessage} style={{ padding: "8px 12px", marginLeft: "10px" }}>
          Send
        </button>
      </div>
    </div>
  );
}

This UI:

  • Displays chat history.
  • Lets the user type messages.
  • Sends them to your API route and shows AI responses.

Step 6: Run Your App

Start the development server:

npm run dev

Open http://localhost:3000/chat in your browser.

Congrats. You now have a working ChatGPT-like chatbot running in your Next.js project.


What’s Next? (Extend Your App 🚀)

Now that the basics are working, you can level up your chatbot with more features:

  • Streaming responses → Show the AI typing in real-time.
  • Database storage → Save chat history using Postgres, MongoDB, or SQLite.
  • Authentication → Use NextAuth.js to secure chat for logged-in users.
  • Custom assistants → Add system prompts to make the bot act like a teacher, coder, or support agent.

Final Thoughts

Integrating OpenAI into Next.js is surprisingly simple. With just a few lines of code, you can create powerful AI-driven features that bring your app to life.

Whether you’re building a chatbot, a writing assistant, or even an AI-powered knowledge base, this setup gives you the foundation to explore endless possibilities.


Tags

#Ai#Chatbot#Nextjs#Openai
Share this post: