如何使用 Vercel 函数接收并处理来自 Typeform 的提交数据?

解读

面试官真正想考察的是“无服务器函数 + 第三方 Webhook”的闭环落地能力,而不仅是“把 Typeform 数据存起来”。
在国内面试场景里,企业关心三点:

  1. 合规:数据先落地海外节点再回源国内,需规避跨境传输风险;
  2. 稳定:Typeform 的 Webhook 出口 IP 段可能被墙,必须做重试与兜底;
  3. 成本:Vercel 函数按 GB-s 计费,要防止大流量表单把账单打爆。
    因此,回答时要体现“边缘函数选型 → 鉴权 → 限流 → 数据清洗 → 回写国内数据库 → 可观测性”的完整链路,并给出代码级细节。

知识点

  1. Vercel Edge Function vs Serverless Function 的选型差异(冷启、CPU 时间、Node 兼容层)。
  2. Typeform Webhook 签名验证算法:HMAC-SHA256 + 签名头 Typeform-Signature。
  3. 国内合规方案:边缘函数只负责验签与转发,通过内网隧道或 SCF 云函数回写国内 MongoDB/PostgreSQL。
  4. 限流与防重:使用 Vercel KV(Upstash Redis)做 IP 级滑动窗口 + 事件 ID 去重。
  5. 可观测性:在函数内使用 console.log 写入 Vercel Runtime Logs,并对接阿里 SLS 或腾讯云 CLS 的 HTTP 收集器。
  6. 异常重试:Typeform 默认 5 秒超时且不重试,需在函数侧立即返回 200,异步队列消费失败时调用 Typeform Responses API 回拉补录。

答案

(以下代码可直接放进 api/typeform-webhook.ts,使用 Serverless Function,Node 18 runtime)

import type { VercelRequest, VercelResponse } from '@vercel/node';
import crypto from 'crypto';
import { Redis } from '@upstash/redis';

const SIGNING_SECRET = process.env.TYPEFORM_SIGNING_SECRET!;
const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL!;
const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN!;

const redis = new Redis({
  url: REDIS_URL,
  token: REDIS_TOKEN,
});

export default async function handler(req: VercelRequest, res: VercelResponse) {
  if (req.method !== 'POST') return res.status(405).json({ message: 'Method Not Allowed' });

  const signature = req.headers['typeform-signature'] as string | undefined;
  if (!signature) return res.status(401).json({ message: 'Missing Signature' });

  const raw = await readRawBody(req);
  const hash = crypto.createHmac('sha256', SIGNING_SECRET).update(raw).digest('hex');
  if (`sha256=${hash}` !== signature) return res.status(403).json({ message: 'Invalid Signature' });

  const body = JSON.parse(raw);
  const eventId = body.event_id;

  // 幂等去重
  const dup = await redis.set(`typeform:${eventId}`, '1', { nx: true, ex: 3600 });
  if (!dup) return res.status(200).json({ message: 'Duplicate Event' });

  // 限流:同一 IP 1 分钟最多 60 次
  const ip = getClientIp(req);
  const key = `rate:${ip}`;
  const current = await redis.incr(key);
  if (current === 1) await redis.expire(key, 60);
  if (current > 60) return res.status(429).json({ message: 'Too Many Requests' });

  // 清洗数据
  const answers = body.form_response.answers.reduce((acc: any, cur: any) => {
    acc[cur.field.ref] = cur[cur.type];
    return acc;
  }, {});

  // 立即返回 200,避免 Typeform 重试
  res.status(200).json({ received: true });

  // 异步写入国内数据库(示例:腾讯云云函数 HTTP 触发器)
  await fetch(process.env.INTERNAL_GATEWAY!, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Internal-Token': process.env.INTERNAL_TOKEN! },
    body: JSON.stringify({ answers, submitted_at: body.form_response.submitted_at }),
  }).catch(err => console.error('Async forward failed', err));
}

function readRawBody(req: VercelRequest): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    let body = Buffer.alloc(0);
    req.on('data', chunk => (body = Buffer.concat([body, chunk])));
    req.on('end', () => resolve(body));
    req.on('error', reject);
  });
}

function getClientIp(req: VercelRequest): string {
  const xff = req.headers['x-forwarded-for'];
  return Array.isArray(xff) ? xff[0].split(',')[0].trim() : xff?.split(',')[0].trim() || '0.0.0.0';
}

部署步骤

  1. 在 Vercel Dashboard 里新建项目,绑定 GitHub 仓库。
  2. 添加环境变量:TYPEFORM_SIGNING_SECRET、UPSTASH_REDIS_REST_URL、UPSTASH_REDIS_REST_TOKEN、INTERNAL_GATEWAY、INTERNAL_TOKEN。
  3. 在 Typeform Admin → Connect → Webhooks 里填写 https://<your-domain>/api/typeform-webhook,保存后点击“Test”触发验签。
  4. 观察 Vercel Real-time Logs 出现 received: true 即接入成功。

拓展思考

  1. 如果表单字段包含文件上传(如 Typeform’s file upload question),边缘函数 4.5 MB 内存限制无法承载大文件,应让 Typeform 先把文件存到 S3,再在 Webhook 里只接收文件 URL,然后异步转存到国内 COS/OSS。
  2. 当业务需要“根据答案实时打标签并回写 Typeform 隐藏字段”时,可调用 Typeform Responses API PATCH /forms/{form_id}/responses/{response_id},但需注意该接口有 120 req/min 全局限速,应做令牌桶限流。
  3. 为了降低跨境时延,可在 Vercel 的 edge-config 里动态切换“海外节点直接回写”与“先落盘再同步”两种策略,依据字段是否含敏感 PII 实时决策,实现合规与性能的平衡。