Building AI-Powered Apps with Next.js and LangChain

Le Do NghiemSoftware Engineer
2025-09-03 2 min read

AI is transforming web development, and Next.js paired with LangChain makes it easy to build intelligent apps. This post shows how to create a chatbot in Next.js.
Use LangChain to process user queries and return AI-generated responses.
// app/api/chat/route.ts
import { NextResponse } from "next/server";
import { ChatOpenAI } from "langchain/chat_models/openai";
import { HumanMessage } from "langchain/schema";
export async function POST(request: Request) {
const { message } = await request.json();
const model = new ChatOpenAI({ openAIApiKey: process.env.OPENAI_API_KEY });
const response = await model.call([new HumanMessage(message)]);
return NextResponse.json({ reply: response.content });
}
Call the API from your Next.js frontend:
"use client";
import { useState } from "react";
export default function Chat() {
const [message, setMessage] = useState("");
const [reply, setReply] = useState("");
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const res = await fetch("/api/chat", {
method: "POST",
body: JSON.stringify({ message }),
headers: { "Content-Type": "application/json" },
});
const { reply } = await res.json();
setReply(reply);
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button type="submit">Send</button>
</form>
<p>{reply}</p>
</div>
);
}
Combining Next.js with LangChain opens up possibilities for AI-driven features like chatbots and content generation. Start experimenting with AI in your apps today!