Next.js 14 and GPT-4o: Build a Chat App

Share:
Tutorial Intermediate ⏱ 40 min read © Gate of AI 2026-06-10

Build a chat application using Next.js 14 and integrate it with OpenAI’s GPT-4o for real-time AI-driven conversations.

Prerequisites

  • Node.js version 18 or higher
  • Next.js 14
  • An OpenAI API key
  • Intermediate JavaScript and React knowledge

What We’re Building

In this tutorial, we will build a chat application using Next.js 14 and integrate it with OpenAI’s GPT-4o model. The application will allow users to have real-time conversations with an AI, leveraging the advanced capabilities of the GPT-4o model for generating human-like responses.

The finished project will feature a user-friendly interface where users can send messages and receive responses powered by GPT-4o. This application will demonstrate how to effectively use Next.js’ App Router and React’s concurrent features for building responsive and scalable applications.

Setup and Installation

We’ll begin by setting up a new Next.js project and installing the necessary dependencies for our application, including the OpenAI SDK for accessing GPT-4o.

npx create-next-app@latest my-chat-app
cd my-chat-app
npm install @openai/openai
npm install tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

Next, we’ll configure our environment variables. These are crucial for storing sensitive information such as your OpenAI API key.

# .env.local
OPENAI_API_KEY=your-openai-api-key

Ensure that your `.env.local` file is included in your `.gitignore` to prevent sensitive information from being exposed in your version control.

Step 1: Setting Up the API Route

To interact with the OpenAI API, we’ll set up an API route in Next.js. This will handle requests from our frontend and communicate with the OpenAI API.

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

export async function POST(request) {
  const { message } = await request.json();
  const client = new OpenAI(process.env.OPENAI_API_KEY);

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

    return new Response(JSON.stringify({ reply: response.choices[0].message.content }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Failed to fetch response from OpenAI' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

This code defines a POST endpoint that accepts a JSON payload with a user’s message, interacts with the OpenAI API, and returns the AI’s response. Proper error handling ensures that any issues with the API call are gracefully managed.

Step 2: Building the Chat Interface

Next, we’ll create a simple chat interface using React components. This will consist of an input field for the user’s message and a display area for the conversation.

// app/page.js
import { useState } from 'react';

export default function Chat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');

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

    const newMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, newMessage]);

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

    const data = await response.json();
    setMessages(prev => [...prev, { role: 'ai', content: data.reply }]);
    setInput('');
  };

  return (
    
{messages.map((msg, index) => (
{msg.content}
))}
setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && sendMessage()} />
); }

This component manages the chat state, handles user input, and displays messages. The `sendMessage` function sends the user’s input to our API route and updates the message list with the AI’s response.

Step 3: Styling the Application

To enhance the user experience, we’ll apply some basic styles using Tailwind CSS. This will make our chat application visually appealing and easy to use.

// styles/globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;

.chat-container {
  max-width: 600px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.messages {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  padding: 10px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.message.user {
  background-color: #e1ffc7;
  text-align: right;
}

.message.ai {
  background-color: #f1f0f0;
  text-align: left;
}

These styles provide a clean layout for the chat interface, with distinct styles for user and AI messages to differentiate them easily.

⚠️ Common Mistake: Ensure your API endpoint is correctly configured in the `fetch` call. Mistyping the endpoint URL or method can lead to CORS errors or failed requests.

Testing Your Implementation

To verify that our chat application works correctly, we can simulate a conversation and check the AI’s responses. Ensure that the messages are sent and received without errors.

// Test by opening the application in your browser and interacting with the chat interface.
npm run dev

After running the application, open your browser and navigate to http://localhost:3000. Enter a message and confirm that you receive an AI-generated response. This interaction confirms that the integration with OpenAI’s API is working as expected.

What to Build Next

  • Enhance the chat interface with more advanced styling and animations to improve user engagement.
  • Implement user authentication to personalize the chat experience and store conversation history.
  • Integrate additional AI models or services to provide diverse capabilities such as sentiment analysis or language translation.
Share:

Was this tutorial helpful?