Next.js fetch API error
- https://vercel.com/docs/projects/environment-variables/system-environment-variables
- https://laros.io/how-to-get-the-current-url-with-nextjs-on-vercel
fetch 了全部的URL:=https://docs-vector-search-demo.vercel.app/api/vectorSearch=,错误的使用是只有 =/api/vectorSearch=。
一个 work 的步骤:
- 在 Vercel 设置环境变量:=NEXT_PUBLIC_URL=https://$NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL=
- 本地环境变量 .env.development:
1NEXT_PUBLIC_URL=http://localhost:3000
- 使用 dotenv-expand 处理
1npm install dotenv-expand
1// next.config.js
2
3const dotenvExpand = require("dotenv-expand");
4
5dotenvExpand.expand({ parsed: { ...process.env } });
6
7// The rest of your config
- 最终效果
1console.log(process.env.NEXT_PUBLIC_URL);
2
3// Output localhost: http://localhost:3000
4// Output preview: https://random-url.vercel.app
5// Output production: https://your-website.com