AI Tools Guide

Openai API Nextjs Route Handler Guide

在 Next.js 接 OpenAI API 的正确姿势:API Key 放服务端、用 App Router 的 Route Handler 调用、流式返回、处理 401/429/quota 报错,绝不在前端暴露 key。附可直接用的 route.ts 代码。

What is the problem?

在 Next.js 接 OpenAI API 的正确姿势:API Key 放服务端、用 App Router 的 Route Handler 调用、流式返回、处理 401/429/quota 报错,绝不在前端暴露 key。附可直接用的 route.ts 代码。

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. **401 Incorrect API key provided**:key 错、过期、或没读到 → 检查 `.env.local` 拼写、重启 dev(环境变量启动时才读)。
  2. **429 Rate limit / insufficient_quota**:超频或余额不足 → 看 OpenAI 后台用量;加重试退避;`insufficient_quota` 是要充值,不是限流。
  3. **key 在前端被暴露**:说明你在客户端组件直接调了 OpenAI → 立刻挪到 Route Handler,并在 OpenAI 后台**吊销并换新 key**。
  4. **生产 undefined**:本地有 `.env.local`,但 Vercel 没配 → 在 Vercel 环境变量补 `OPENAI_API_KEY` 并重新部署。
  5. key 只在服务端,前端零暴露;
  6. `.env*` 已 gitignore;

Commands or code

npm install openai

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.