Generative Artificial Intelligence is transforming user expectations, shifting apps from static form entries to conversational interfaces. Google's Gemini models offer developer-friendly APIs with multi-modal reasoning capabilities. In this guide, we will step through integrating Gemini's latest API into a Node.js backend using the official SDK, showing how to process prompts, stream text, and structure JSON responses.
To use Google Gemini, get an API key from Google AI Studio and install the SDK:
npm install @google/generative-ai dotenv
Add the token to your environment config:
GEMINI_API_KEY=your_actual_key_here
Let's write a simple service that sends a prompt to the Gemini model and logs the text response:
import { GoogleGenerativeAI } from '@google/generative-ai';
import dotenv from 'dotenv';
dotenv.config();
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
export async function generateTip(skill) {
try {
const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' });
const prompt = 'Give me one practical coding tip for learning ' + skill + '. Keep it under 3 sentences.';
const result = await model.generateContent(prompt);
const response = await result.response;
return response.text();
} catch (error) {
console.error('Gemini generateContent error:', error);
return 'Keep practicing to master your skills!';
}
}
For longer content (like articles or explanations), waiting for the model to generate the full text causes latency. Streaming lets you display output words as they are ready:
export async function streamExplanation(topic, res) {
const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' });
const result = await model.generateContentStream('Explain the core architecture of ' + topic + ' step-by-step.');
for await (const chunk of result.stream) {
const chunkText = chunk.text();
res.write(chunkText); // Stream words directly to Express response
}
res.end();
}
To map AI responses directly to application logic, force the API to return a structured JSON response:
const model = genAI.getGenerativeModel({
model: 'gemini-1.5-flash',
generationConfig: {
responseMimeType: 'application/json',
responseSchema: {
type: 'object',
properties: {
title: { type: 'string' },
difficulty: { type: 'string', enum: ['Beginner', 'Intermediate', 'Advanced'] },
steps: {
type: 'array',
items: { type: 'string' }
}
},
required: ['title', 'difficulty', 'steps']
}
}
});
Integrating Gemini AI into Node.js application flows is clean and simple. Leveraging generative AI streams, structured schemas, and system prompt contexts allows you to create highly engaging features for your application users.