AIAI Club
← Back to articles
ENGLISH GUIDE

Node.js / TypeScript Practical Example: Efficiently Calling Gemini on the Next.js Server Side

A must-read for full-stack frontend engineers! Based on the official @google/generative-ai package, this example uses modern TypeScript to write robust Next.js server-side routes and asynchronous API handling.

1. Install the Official npm Dependency Package

npm install @google/generative-ai

2. Complete Next.js API Route Endpoint Code

import { GoogleGenerativeAI } from "@google/generative-ai";
import { NextResponse } from "next/server";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);

export async function POST(req: Request) {
const { prompt } = await req.json();
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent(prompt);
const response = await result.response;
return NextResponse.json({ text: response.text() });
}
It uses modern TypeScript type definitions, with full code completion and excellent concurrency handling.

This English translation is based on a Chinese source article. Prices are approximate where stated and conditions should be confirmed with the official provider or seller.