Back to ArticlesAI & Fullstack

Building Production AI-Powered Web Applications with Gemini API & Firebase

A practical engineering guide to integrating Google's Gemini multimodal models into Next.js applications with Firebase authentication, Firestore streaming, and secure API key management.

AK
Akorede Adekunle
Software Engineer & GDG On Campus Lead
February 12, 2026•7 min read

Introduction

In late 2025 and 2026, artificial intelligence moved from novelty chat interfaces into core application logic. During my presentation at **DevFest Ado-Ekiti 2026**, I shared practical architecture patterns for integrating Google's Gemini models into production web applications without sacrificing latency or user security.

When building AI-powered web applications, engineers frequently face three bottlenecks: 1. **API Key Leakage**: Exposing AI provider secrets in client-side bundles. 2. **Perceived Latency**: Waiting 4 to 8 seconds for bulk LLM responses without streaming feedback. 3. **Session Persistence**: Managing prompt context across authenticated user sessions.

Here is how to solve each of these systematically using Next.js App Router and Firebase.


1. Secure Server-Side Proxying via Next.js Route Handlers

Never initialize `@google/genai` directly in client components (`"use client"`). Always route generative requests through authenticated Next.js Route Handlers:

// app/api/ai/generate/route.js
import { GoogleGenAI } from '@google/genai';
import { NextResponse } from 'next/server';

const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });

export async function POST(req) { try { const { prompt, userId } = await req.json(); // 1. Verify user session or rate limit via Firebase Token if (!prompt || typeof prompt !== 'string') { return NextResponse.json({ error: 'Valid prompt is required' }, { status: 400 }); }

// 2. Stream generation with gemini-2.5-flash for low latency const response = await ai.models.generateContent({ model: 'gemini-2.5-flash', contents: prompt, });

return NextResponse.json({ result: response.text }); } catch (error) { console.error('Gemini Generation Error:', error); return NextResponse.json({ error: 'AI generation failed' }, { status: 500 }); } } ```


2. Streaming Responses for Instant Perceived Speed

Users perceive an application as fast when the first token renders in under 600ms, even if the total completion takes longer. By using Gemini's streaming API (`generateContentStream`) paired with standard `ReadableStream`, tokens stream directly to the React interface as they are generated.


3. Persisting Conversation Context in Firestore

When building context-aware tools like **BrainBash** (our adaptive exam preparation ecosystem), historical student queries inform subsequent question explanations.

We structure prompt histories using Firebase Firestore: - `/users/{uid}/ai_sessions/{sessionId}/messages` - Each document contains: `{ role: 'user' | 'model', text: string, timestamp: Timestamp }`

Before dispatching to Gemini, we serialize the last 6 messages into the contents array, keeping token usage efficient while preserving contextual relevance.


Key Takeaway

AI capabilities are only as good as the software architecture supporting them. Focus on zero-trust key management, streaming UI patterns, and efficient Firestore persistence to deliver AI experiences that feel instant and dependable.

Tags:#Gemini API#Next.js#Firebase#AI Engineering#TypeScript
NEXT TECHNICAL ARTICLE

Architecting Sub-20ms Developer Data APIs with Next.js, Edge CDN & Prisma

Read Next