A handler runs application logic in response to a request or an execution event. In Next.js, route handlers implement backend API logic; in LangChain.js, callback handlers hook into chain and language-model execution. section 2.8.6 section 8.3.1
Handler structure depends on what triggers it:
- A Next.js route handler lives in an API path in a route.js or route.ts file and can export method-specific functions such as POST. It can use request and response objects, and an optional dynamic export configures caching. section 2.8.6
- A LangChain.js callback handler is supplied through a callbacks list. Its methods respond to events such as chain start, chain error, and new LLM tokens; callbacks can be attached to provider calls or individual invocations. section 8.3.1
- In component tests, event handlers can be checked for correct responses to actions such as clicks or form submissions. section 8.4.1
Listing 2.7 Handling the API backend logic
import { GoogleGenerativeAI } from "@google/generative-ai";
export const dynamic = 'force-dynamic'; #1
const openai = new GoogleGenerativeAI (
process.env.GEMINI_API_KEY || '' #2
);
export async function POST(req) {. #3
const { text } = await req.json(); #4
// Code to request completion data from Google. #5
return Response.json({ message }); #6
}
See a Next.js POST handler that reads request JSON and returns a JSON response. section 2.8.6
Table 8.1 Common callback handlers in LangChain.js
| Event |
Trigger |
Method |
| Chain start |
When a chain starts running |
|
| Chain end |
When a chain ends |
|
| Chain error |
When a chain errors |
|
| LLM start |
When an LLM starts |
|
| LLM new token |
When an LLM or chat model emits a new token |
|
| LLM end |
When an LLM or chat model ends |
|
| LLM errors |
When an LLM or chat model encounters an error |
|
Compare common LangChain.js callback events with the methods that handle them. section 8.3.1





















