Next.js集成Telegram Bot API本地正常、Vercel生产环境失效的解决方法
问题解决办法
1. 检查Vercel环境变量配置
- 登录Vercel控制台进入项目,找到「Settings」→「Environment Variables」
- 确认
TG_TOKEN和TG_CHATID已添加,且Production环境的开关处于开启状态(变量条目右侧的toggle要打开) - 注意变量名大小写必须和代码里的完全一致,Vercel环境变量区分大小写
2. 将Telegram调用逻辑迁移到服务器端
Telegram Bot API不允许在浏览器客户端直接调用:一来会暴露敏感的TG_TOKEN,二来浏览器的CORS策略可能拦截请求。需把发送逻辑放到Next.js的API路由或Server Component中:
示例API路由(app/api/telegram/route.js)
import { sprintf } from "sprintf-js"; import { NextResponse } from 'next/server'; export async function POST(request) { const { postID, title } = await request.json(); const message = sprintf("%s - %s", title, postID); try { const res = await fetch(`https://api.telegram.org/bot${process.env.TG_TOKEN}/sendMessage`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: message, chat_id: process.env.TG_CHATID, parse_mode: "html" }) }); const data = await res.json(); console.log('Telegram API响应:', data); return NextResponse.json(data); } catch (e) { console.error('发送消息失败:', e); return NextResponse.json({ error: e.message }, { status: 500 }); } }
客户端调用该API路由
// 替换原有的Telegram类调用代码 fetch('/api/telegram', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ postID: post["_id"], title: post["name"] }) }).then(res => res.json()).then(res => console.log(res)).catch(e => console.error(e))
3. 完善错误日志捕获
原代码中的.catch(e => console.log(e))在Vercel生产环境客户端无法查看日志,迁移到服务器端后,Vercel的「Functions」日志会记录所有console.log和console.error内容:
- 进入Vercel项目的「Logs」→「Functions」,即可查看API路由的运行日志
4. 排除Vercel防火墙限制
Vercel默认允许对外HTTP/HTTPS请求,api.telegram.org不在限制域名列表中,基本可以排除防火墙权限问题。若仍有疑虑,可在API路由中尝试请求其他公开API(如https://jsonplaceholder.typicode.com/todos/1),验证请求是否正常。
内容的提问来源于stack exchange,提问作者miguel morillo
相关产品推荐
相关产品推荐

