Skip to main content
Reggie Pangilinan
HomeBlogAbout
GitHubLinkedIn

© 2026 reggiepangilinan.com All rights reserved.

GitHubLinkedIn
Adding AI-Powered Blog Search with Google Gemini in Next.js
←Back to Blog

Adding AI-Powered Blog Search with Google Gemini in Next.js

A plain-English guide to how Gemini works, comparing Google search options, real-world free-tier traffic math, security guardrails, and how to scale without rewriting your site.

December 3, 2026·Reggie Pangilinan·12 min read
Adding AI-Powered Blog Search with Google Gemini in Next.js

Most blog search bars are frustratingly literal. If a reader visits a technical blog and types _"how do you keep hosting free?"_, a traditional keyword search only looks for the exact word "free". If the article was titled _"Running a Next.js Site for $1/Month on Contentful & Netlify"_, a basic search bar shrugs and returns 0 results.

We just upgraded the /blog page on reggiepangilinan.com with AI-powered blog search using Google Gemini. Visitors can still filter posts instantaneously as they type or browse by topic—but pressing Enter or clicking Ask AI now reads across every published article, writes a concise grounded answer, ranks the most relevant posts, and highlights _why_ each article matches.

If you have ever wondered how AI search actually works under the hood—without drowning in machine-learning jargon—this guide walks through the whole journey: what Gemini is, how the four Google search options compare, how far the free tier really goes with real traffic math, the security guardrails that protect your wallet, and how to scale if your blog grows to thousands of posts.

🧠 AI & Google Gemini 101 (In Plain English)

Before writing a single line of code, it helps to demystify what "AI" and "Google Gemini" actually mean when you plug them into a website.

  • What is an LLM (Large Language Model)? Think of an LLM as a super-fast reader that has learned the patterns of human language. Instead of matching letters one by one like Ctrl+F, it understands meaning, intent, and synonyms—it knows that _"keep hosting free"_, _"$0/month infrastructure"_, and _"free-tier quotas"_ are all talking about the same idea.

  • What is Google Gemini? Gemini is Google's family of AI models. Just like cars come in different sizes—from nimble city hatchbacks to heavy-duty trucks—Gemini comes in tiers. For a blog search bar, you do not need the heaviest reasoning model; you want a fast, lightweight Flash / Flash-Lite model (like gemini-3.5-flash-lite) that answers in under two seconds for fractions of a penny.

  • What are Tokens? AI models do not read by character or page—they read in chunks called tokens. As a rough rule of thumb in English, 1 token is about 4 characters (or roughly ¾ of a word). A 1,000-word blog post is roughly 1,300 to 1,500 tokens.

  • What is a Context Window? Think of the context window as the AI's desk space—how much reading material you can hand it in a single request. Modern Gemini models have a 1 million token context window, which is roughly 700,000+ words (several full-length novels). For a personal blog with 15 to 200 posts, the _entire blog catalog_ fits comfortably on Gemini's desk in one shot.

  • How do you stop AI from making things up ("hallucinating")? Two simple tricks: Grounding and Structured JSON Output. Instead of asking Gemini open-ended questions from its memory, we hand it _only_ our published Contentful articles and instruct it to answer strictly from that text. Then we require Gemini to reply in a strict JSON schema containing exact post slugs—and our server double-checks every single slug against Contentful before showing it to the reader.

Infographic explaining AI and Google Gemini 101: Keyword Search vs. Gemini AI Search, 1M token context window, structured JSON grounding, and sub-2-second Flash-Lite speed
Infographic explaining AI and Google Gemini 101: Keyword Search vs. Gemini AI Search, 1M token context window, structured JSON grounding, and sub-2-second Flash-Lite speed

Key takeaway: You do not need a PhD, a custom machine-learning model, or an expensive vector database to add genuinely smart AI search to a personal blog. A single HTTPS POST request to the Gemini API with your article summaries and a strict JSON schema gets you 95% of the magic with zero extra infrastructure.

🔍 The 4 Ways to Build Google AI Search (And Why Hybrid Won)

When people say _"let's add Google search with AI to the blog"_, there are actually four very different products in Google's ecosystem. Choosing the wrong one can lock you into surprise cloud bills, slow crawl delays, or a deprecated API.

Infographic comparing the 4 Google AI search options: Hybrid Instant + Gemini API (Recommended), Gemini Web Grounding, Vertex AI Search, and retiring Custom Search JSON API
Infographic comparing the 4 Google AI search options: Hybrid Instant + Gemini API (Recommended), Gemini Web Grounding, Vertex AI Search, and retiring Custom Search JSON API

Here is how the four options stack up:

  • Option 1: Hybrid Instant Filter + Google Gemini API (What We Built ✅)

  • How it works: As a visitor types in /blog, client-side JavaScript filters titles, excerpts, and tags in 0 ms (zero API calls). When the visitor presses Enter or clicks Ask AI, our Next.js route (src/app/api/blog/search/route.ts) sends the question plus a compact plain-text digest of every published Contentful post to Google's Gemini REST API.

  • Why it won: It works the exact second you publish a new post (no waiting for Googlebot to crawl your site), maps results 1-to-1 to your native blog cards, has a real $0/month free tier (and works with Google AI Pro's included monthly API credits), and degrades gracefully to local keyword search if the API key is missing.

  • Option 2: Gemini API + Grounding with Google Search

  • How it works: You tell Gemini to run a live Google Web Search restricted to site:yourdomain.com and summarize what Google's index returns.

  • Why we skipped it: Search Grounding is not available on the Gemini 3+ free tier (it requires paid Cloud billing, with a monthly free allowance followed by roughly $14 per 1,000 grounded requests plus token costs). Worse, brand-new blog posts are invisible until Googlebot indexes them, and mapping web URLs back to rich Contentful cards is clunky.

  • Option 3: Vertex AI Search (Google Cloud Site Search)

  • How it works: Google Cloud crawls your website into an enterprise search engine and gives you a managed AI search widget or API.

  • : It is built for massive corporate websites with 10,000+ pages, requires full Google Cloud project/billing setup, and meters at plus model tokens after trial credits. Total overkill for a personal blog.

⚙️ How Our Hybrid Architecture Actually Works

We designed the search feature to feel effortless for readers while staying lean in code—zero heavy AI SDK packages added to package.json, just native fetch and TypeScript.

  • Step 1 — Zero-Latency Typing (0 ms): src/app/blog/page.tsx strips heavy RichText bodies before sending lightweight post summaries to src/components/BlogSearch/BlogSearch.tsx. Typing a word or toggling a topic in the collapsible Browse topics drawer filters all posts instantaneously in the browser without spending a single AI token.

  • Step 2 — Intentional AI Invocation: Pressing Enter, clicking Ask AI, or clicking one of the curated starter prompts sends a POST request to /api/blog/search.

  • Step 3 — Compact Contentful Digest: On the server, src/lib/rich-text-plain-text.ts converts each Contentful RichText article into clean plain text capped at 1,800 characters per post. That keeps the prompt fast, affordable, and well within Gemini's context window.

  • Step 4 — Grounded JSON Response + Server Verification: src/lib/blog-search.ts calls the Gemini REST API with responseMimeType: "application/json" and a strict responseSchema returning an answer, ranked results[] with a 1-sentence relevanceReason per post, and 2–3 clickable suggestedQueries. Every returned slug is checked against the real Contentful catalog so broken or hallucinated links are impossible.

📊 Real-World Usage Math: How Far Does the Free Tier Go?

"Free tier" sounds great in theory, but what does it actually support in real monthly blog traffic? Let's run the honest numbers.

First, how big is one AI search?

  • Each post digest is roughly ~550 tokens (title, subtitle, tags, excerpt, and up to 1,800 characters of body text).

  • At 15 published posts: 15 × 550 ≈ 8,500 input tokens + ~350 output tokens ≈ ~9,000 total tokens per AI search.

  • At 50 published posts: 50 × 550 ≈ 28,000 input tokens + ~350 output tokens ≈ ~28,500 total tokens per AI search.

Second, how many visitors actually click Ask AI?

  • On most technical blogs, 80% to 90% of visitors land directly on a single article from Google, LinkedIn, or GitHub, read it, and leave without ever touching search.

  • Of the 10% to 20% who browse /blog, many just scroll or use the 0 ms instant keyword/topic filter (which costs 0 AI API calls).

  • In practice, only 3% to 5% of total monthly visitors run an AI search—and roughly 20% to 30% of those queries (especially starter prompts!) hit our 10-minute server cache.

Now put those numbers together across three realistic tiers:

  • Tier A — Google AI Studio Free Tier ($0/month, no credit card)

  • Even assuming conservative free-tier quotas (roughly 10–15 requests/minute and 250–1,000 requests/day depending on model and Google's current free-tier limits):

  • At just 250 AI searches/day, that is ~7,500 AI searches/month.

  • With a 4% AI-search rate and 25% cache hit rate, 7,500 AI searches/month comfortably supports ~200,000 to 250,000 monthly blog visitors!

  • The only free-tier constraint you might ever notice is a per-minute burst (for example, if a post hits the front page of Hacker News and 20 people click Ask AI in the exact same minute). Even then, our fallback kicks in immediately so nobody sees an error screen.

  • Tier B — Google AI Pro Included Credits ($10/month credit already included if you subscribe)

  • If you already have a Google AI Pro subscription, you can claim $10/month in Gemini API credits inside Google AI Studio (each monthly grant lasts 12 months and stacks).

  • On a Flash-Lite model (roughly $0.25–$0.30 per 1M input tokens and $1.50–$2.50 per 1M output tokens), one AI search at 15 posts costs roughly $0.0034 (about one-third of a penny).

  • That $10/month credit covers ~2,900 AI searches/month at 15 posts (or ~1,075 AI searches/month at 50 posts)—supporting ~30,000 to 90,000+ monthly visitors with higher paid-tier rate limits and zero free-tier training retention, without paying anything extra beyond your existing AI Pro plan.

Bottom line: For a personal or mid-sized technical blog getting anywhere from 500 to 100,000+ monthly visitors, the Hybrid Instant + Gemini architecture runs comfortably for $0/month on the free tier—or effortlessly inside Google AI Pro's included credits if you want paid-tier stability.

📅 Timeline: How Long Does the Free Tier Last at 1 Post/Week?

Assuming a steady publishing pace of 1 blog post per week (~52 posts per year) starting from roughly 15 published posts today, here is how long this exact setup lasts before you ever need to touch the architecture:

Infographic timeline showing how far the Gemini Flash-Lite free tier lasts when publishing 1 blog post per week, from 15 posts today through 3.5 to 4 years on Stage 1 and 10+ years with Stage 2 embeddings
Infographic timeline showing how far the Gemini Flash-Lite free tier lasts when publishing 1 blog post per week, from 15 posts today through 3.5 to 4 years on Stage 1 and 10+ years with Stage 2 embeddings
  • Today (Month 0 · ~15 posts): Each AI search sends ~8,500 input tokens (less than 1% of Gemini's 1M context window). Runs completely free on Google AI Studio Free Tier, or ~$0.0034/search on AI Pro credits.

  • Year 1 (~67 posts): Each AI search sends ~37,000 input tokens (3.7% of context window). Still $0/month on the Free Tier for typical personal-blog traffic, and ~$0.012/search on AI Pro credits (~830 AI searches/month, or ~25,000–30,000 monthly visitors).

  • Year 2 (~119 posts): Each AI search sends ~65,500 input tokens (6.5% of context window). Around Month 20 (~100 posts), you simply bump maxCatalogPosts in src/config/blog.ts. Still $0/month for steady traffic, though heavy per-minute bursts start getting closer to free-tier tokens-per-minute (TPM) caps.

  • Years 3.5 to 4 (~180–220 posts · Natural Upgrade Point): Each AI search crosses ~100,000–120,000 input tokens (~10–12% of context window). Gemini can technically hold much more, but this is the practical point to turn on Stage 2 (pre-filtering to the top 15 posts with embeddings) to keep response times under 2 seconds and stay well below per-minute token caps.

  • Years 5 to 10+ (260–500+ posts): Once you add lightweight embedding pre-filtering (which only hands Gemini the top 15 candidate posts per question), every query drops right back down to ~8,500 input tokens—effectively resetting your free-tier / $10 AI Pro runway for another decade.

At 1 post per week, you get ~3.5 to 4 full years on the zero-database Stage 1 architecture before even needing an embedding pre-filter—and 10+ years on free/low-cost tiers once Stage 2 is added.

🛡️ Security & Cost Guardrails Built In

Exposing an AI endpoint on a public website without guardrails is a recipe for abuse. Bots love scraping open endpoints, and a single loop without limits can burn through a daily quota in minutes. Here are the five guardrails we built directly into src/app/api/blog/search/route.ts and src/lib/blog-search.ts:

  • Server-Only API Key: GEMINI_API_KEY is never exposed to the browser, never prefixed with NEXT_PUBLIC_, and never logged in console output. In netlify.toml, Netlify's secrets scanner stays enabled for all secret keys while omitting only the non-secret GEMINI_MODEL name.

  • 200-Character Query Cap: Rejects empty or oversized queries with HTTP 400, preventing prompt-stuffing attacks where someone pastes a 20-page document into your search box.

  • Per-IP Sliding-Window Rate Limiter (10 AI searches/minute): Stops automated scripts from hammering Gemini. Best of all, when an IP hits the limit, the route gracefully degrades to local lexical search instead of throwing an ugly error.

  • 10-Minute Normalized-Query Cache: Queries are lowercased and whitespace-normalized before caching ("Next.js ISR" and " next.js isr " share one cache entry). Only successful AI answers are cached so transient errors never stick.

  • Zero-Secret Graceful Fallback: Local dev environments, CI pipelines, and Deploy Previews without GEMINI_API_KEY still compile cleanly and serve instant keyword + topic search—and /api remains disallowed in robots.txt so search crawlers never waste AI calls.

Infographic showing the 4 built-in security and cost guardrails (200 char cap, 10/min rate limit, 10 min cache TTL, 0 secrets fallback) alongside the 3-stage scaling ladder from 10 to 2,000+ posts
Infographic showing the 4 built-in security and cost guardrails (200 char cap, 10/min rate limit, 10 min cache TTL, 0 secrets fallback) alongside the 3-stage scaling ladder from 10 to 2,000+ posts

🚀 Scaling Later: What Changes as the Blog Grows?

The best part of putting all search logic behind a single POST /api/blog/search contract is that your frontend UI never needs to change as the blog grows. You only upgrade the retrieval layer behind the API route when you actually hit the next threshold:

  • Stage 1 — 10 to 200 Posts (Where We Are Today · $0/mo): Send the compact plain-text catalog directly in Gemini's context window. Zero extra databases, zero sync jobs, instant indexing the second you hit Publish in Contentful.

  • Stage 2 — 200 to 2,000 Posts (~$1–$5/mo): Once sending every post on every query gets heavy (above ~100K input tokens per call), add two lightweight upgrades:

  • Gemini Context Caching: Cache the static blog catalog inside Gemini's API so repeated queries pay a fraction of normal input token costs.

  • Pre-Filtering with Embeddings (Gemini Embedding 2): Generate a small numeric vector for each post when Contentful publishes it, pick the top 10–15 candidate posts using fast cosine similarity, and send only those 15 posts to Gemini to synthesize the final answer.

  • Stage 3 — 2,000+ Posts or Multi-Site Search (Usage-Based): Move the embeddings into a dedicated vector store (like Supabase pgvector or Pinecone) or graduate to Vertex AI Search—keeping the exact same /blog search bar, AI Answer card, and match-reason UI on the frontend.

✨ Wrapping Up

Adding AI search to a blog does not have to mean bolted-on chatbot widgets, complex vector pipelines, or unpredictable cloud bills. By pairing 0 ms instant client-side filtering with a grounded, schema-enforced Google Gemini API route—and wrapping it in simple, honest guardrails—visitors get an intelligent search experience that actually understands what they are looking for, while the entire site stays fast, secure, and free-tier friendly.

Try it out yourself on the /blog page—type a question, click one of the starter prompts, or open the Browse topics drawer to explore by tag.

Keep Reading

Related Posts

December 2, 2026

Generative Engine Optimization (GEO) in Next.js 16: llms.txt, RSS, JSON-LD & Crawler Access

A plain-English primer on Generative Engine Optimization (GEO) plus six concrete Next.js 16 upgrades: dynamic /llms.txt, /rss.xml, Person & WebSite JSON-LD, explicit AI bot rules, and non-JS visibility.

Next.jsSEO
December 2, 2026

Four Silent Sitemap & SEO Bugs I Found Auditing My Next.js 16 Blog

What sitemaps, robots.txt, and canonical URLs actually do for search indexing—plus four silent SEO bugs I found and fixed auditing my Next.js 16 + Contentful blog.

Next.jsSEO
December 2, 2026

Setting Up Contentful Draft Preview in Next.js 16 (and the Gotchas Along the Way)

Adding Contentful Draft Preview to a Next.js 16 + Netlify site—including the iframe CSP, SameSite cookie, and unpublished asset gotchas that tripped me up.

Next.jsContentful
Topics
Next.jsTypeScriptContentfulNetlifyAISEOSecurity

Share this article

Found this helpful? Copy the link or scan the QR code to share it.

←All blog posts
Why we skipped it
$1.50 to $4.00 per 1,000 queries
  • Option 4: Google Custom Search JSON API

  • How it works: Google's legacy programmable search JSON endpoint.

  • Why we skipped it: Google closed it to new customers and is shutting it down on January 1, 2027. Never build new features on a retiring API.

  • Step 5 — Discoverability Everywhere: We also wired clickable Swiss-dot topic tags across /blog and /blog/[slug], synced ?q= and ?tag= in the URL for shareable searches, added a visible RSS link in the blog masthead, and added SearchAction JSON-LD in src/lib/seo.ts so search engines know the blog is searchable.

  • Tier C — Viral Traffic Spike (100,000 visitors in 48 hours)
  • Because repeated queries and starter prompts are served from the 10-minute cache and each IP is capped at 10 AI searches/minute, a viral spike will not drain your quota or create a surprise invoice.