You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vercel上部署基于whatsapp-web.js的Node.js API?

基于whatsapp-web.js的API部署到Vercel的正确步骤

核心限制说明

Vercel的Serverless Functions存在最长10秒的执行时长限制,且属于无状态环境,无法持久化WhatsApp的登录会话——而whatsapp-web.js需要维持长连接和会话状态,这是直接部署失败的核心原因,必须调整架构适配Vercel环境。

具体部署方案

1. 改用Vercel Edge Functions替代Serverless Functions

Edge Functions支持最长60秒的执行时长,更适配实时连接场景。在项目中创建api/whatsapp.js文件,代码示例如下:

const { Client, LocalAuth } = require('whatsapp-web.js');
const puppeteer = require('puppeteer-core');
const chromium = require('chrome-aws-lambda');

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: '仅支持POST请求' });
  }

  const { number, message } = req.body;

  const browser = await puppeteer.launch({
    args: chromium.args,
    executablePath: await chromium.executablePath,
    headless: chromium.headless,
  });

  const client = new Client({
    authStrategy: new LocalAuth(),
    puppeteer: { browser },
  });

  client.on('ready', async () => {
    try {
      const chatId = `${number}@c.us`;
      await client.sendMessage(chatId, message);
      res.status(200).json({ success: true, message: '消息发送成功' });
      await client.destroy();
      await browser.close();
    } catch (err) {
      res.status(500).json({ error: '消息发送失败', details: err.message });
      await client.destroy();
      await browser.close();
    }
  });

  client.on('auth_failure', () => {
    res.status(401).json({ error: 'WhatsApp认证失败,请重新登录' });
  });

  client.initialize();
}

2. 配置必要依赖包

在项目根目录的package.json中添加依赖:

{
  "dependencies": {
    "whatsapp-web.js": "^1.23.0",
    "puppeteer-core": "^21.0.0",
    "chrome-aws-lambda": "^12.0.0"
  }
}

3. 解决会话持久化问题

Vercel无状态环境无法保存LocalAuth的本地会话文件,需改用RemoteAuth策略,将会话数据存储到外部数据库(如MongoDB、Redis),示例代码:

const { Client, RemoteAuth } = require('whatsapp-web.js');
const { MongoStore } = require('wwebjs-mongo');
const mongoose = require('mongoose');

await mongoose.connect('你的数据库连接字符串');
const store = new MongoStore({ mongoose: mongoose });

const client = new Client({
  authStrategy: new RemoteAuth({
    store: store,
    backupSyncIntervalMs: 300000
  })
});

4. 调整Vercel部署配置

  • 进入Vercel项目设置,将函数执行超时时间调到最大值(Edge Functions为60秒)
  • 添加环境变量:MONGODB_URI(使用RemoteAuth时必填)、NODE_ENV=production

5. 处理首次登录验证

首次部署后需要完成WhatsApp扫码登录,可选择两种方式:

  • 本地运行一次代码,完成扫码后将会话数据同步到远程数据库
  • 在Edge Functions中添加临时逻辑,首次调用接口时返回二维码URL,扫码完成后再调用发送接口

替代方案:分离长进程服务

如果需要维持长期在线的WhatsApp客户端,可以将核心的WhatsApp客户端部署到支持长进程的平台(如Heroku、DigitalOcean Droplet),Vercel仅作为前端API网关,负责转发请求到该长进程服务。


内容的提问来源于stack exchange,提问作者ALEXANDER JUNIOR MONZON MONTAL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:17:24