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 guideDetailed steps
- **400 API key not valid**:key 错或没读到 → 检查 `.env.local`、重启 dev。
- **403 / PERMISSION_DENIED**:key 没开对应 API,或地区/项目限制 → 在 Google AI Studio / Cloud 确认 key 权限。
- **429 RESOURCE_EXHAUSTED**:超免费额度或 RPM/TPM 限制 → 降速、加重试退避、或换更高配额。
- **生产读不到**:Vercel 没配 `GEMINI_API_KEY` → 补环境变量并重新部署。
- key 只在服务端,泄露立刻在 Google AI Studio 吊销换新。
- 免费额度有限,给 `/api/gemini` 加频率限制,别被人刷爆配额。
Commands or code
npm install @google/generative-aiRisk 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.