DEV Community

S M Tahosin
S M Tahosin

Posted on

How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed)

Here's how I integrated Google Gemini's free API into a Next.js app - calling it directly from the client with zero backend cost.

Why Client-Side?

I initially used a serverless function (API route) to call Gemini. But on Netlify's free tier, functions have a 10-second timeout. Gemini sometimes takes 5-8 seconds, and with cold starts, it was hitting 502 errors.

Solution: Call the Gemini API directly from the browser. Since I'm using the free tier API key (rate-limited by Google), there's no security concern.

Setup

1. Get a Free Gemini API Key

Go to aistudio.google.com. Free tier gives you:

  • 15 requests per minute
  • 1,500 requests per day

2. Environment Variable

NEXT_PUBLIC_GEMINI_API_KEY=your_key_here
Enter fullscreen mode Exit fullscreen mode

3. Call the API

const res = await fetch(
  `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      contents: [{ parts: [{ text: prompt }] }],
      generationConfig: { maxOutputTokens: 2000, temperature: 0.7 },
    }),
  }
);
const data = await res.json();
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text;
Enter fullscreen mode Exit fullscreen mode

4. Static Export for Netlify

// next.config.ts
const nextConfig = { output: "export" };
Enter fullscreen mode Exit fullscreen mode

No serverless functions needed. Deploy with netlify deploy --prod --dir out.

Live Examples

Source: github.com/x-tahosin/maxai-writer

Questions? Drop them below!

Top comments (0)