AI Tools Guide

Gemini API Nextjs Guide

在 Next.js 接 Google Gemini API 的正确做法:用 @google/generative-ai SDK、key 放服务端 Route Handler、流式返回、处理 400/403/429 报错,绝不在前端暴露 key。附可用代码。

What is the problem?

在 Next.js 接 Google Gemini API 的正确做法:用 @google/generative-ai SDK、key 放服务端 Route Handler、流式返回、处理 400/403/429 报错,绝不在前端暴露 key。附可用代码。

Quick solution

Treat this as a AI tools tutorial issue. First confirm the environment, inputs, permissions, logs, and delivery boundary. Then use the linked deep guide for the full checklist before changing production code or promising a result.

Read the deep guide

Detailed steps

  1. **400 API key not valid**:key 错或没读到 → 检查 `.env.local`、重启 dev。
  2. **403 / PERMISSION_DENIED**:key 没开对应 API,或地区/项目限制 → 在 Google AI Studio / Cloud 确认 key 权限。
  3. **429 RESOURCE_EXHAUSTED**:超免费额度或 RPM/TPM 限制 → 降速、加重试退避、或换更高配额。
  4. **生产读不到**:Vercel 没配 `GEMINI_API_KEY` → 补环境变量并重新部署。
  5. key 只在服务端,泄露立刻在 Google AI Studio 吊销换新。
  6. 免费额度有限,给 `/api/gemini` 加频率限制,别被人刷爆配额。

Commands or code

npm install @google/generative-ai

Risk notes

Confirm the real project environment, account permissions, platform rules, and output quality before delivery. Do not ship AI-generated changes without human review, and do not claim indexing, income, deployment success, or ranking improvements without measured evidence.