AI Tools Guide

ENV Variable Missing Fix

本地配了 .env 但 process.env 还是 undefined,常见于没重启 dev、前端变量缺 NEXT_PUBLIC_ 前缀、.env 文件名/位置不对、没装 dotenv、变量名拼错、构建平台没配。逐条给真实修复。

What is the problem?

本地配了 .env 但 process.env 还是 undefined,常见于没重启 dev、前端变量缺 NEXT_PUBLIC_ 前缀、.env 文件名/位置不对、没装 dotenv、变量名拼错、构建平台没配。逐条给真实修复。

Quick solution

Treat this as a Node.js errors troubleshooting 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. Next.js:浏览器要读的变量改成 `NEXT_PUBLIC_API_URL`;
  2. Vite:改成 `VITE_API_URL`,代码里用 `import.meta.env.VITE_API_URL`。
  3. **密钥类(API key、token)不要加前缀**,那样会泄露到前端。
  4. **`.env` 必须进 `.gitignore`**,别把密钥提交进仓库或公开。
  5. 给前端加前缀的变量等于公开,绝不要把密钥、token 加 `NEXT_PUBLIC_` / `VITE_`。
  6. [报错解释器](/tools/error-explainer)

Commands or code

npm install dotenv

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.