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

Sendgrid在Next.js本地正常,部署到Vercel后出现Unauthorized错误

问题:SendGrid + Next.js 部署到Vercel后出现401未授权错误

问题详情

  • 本地环境中SendGrid与Next.js的集成功能可正常运行
  • 部署到Vercel后触发**Response Error: Unauthorized(未授权)**错误
  • 已完成SendGrid的单发件人验证(Single Sender Verification)且验证状态有效
  • 尝试创建新的API Key后问题仍未解决

API路由代码

import type { NextApiRequest, NextApiResponse } from "next";
const sgMail = require("@sendgrid/mail");

type EmailData = {
  to: string;
  from: string;
  subject: string;
  text: string;
  html: string;
};

type DataResponse = {
  data?: any;
  success: boolean;
  error?: string;
};

const emailAddress = process.env.SENDGRID_EMAIL as string;
const emailAddressTo = process.env.SENDGRID_EMAIL_TO as string;

sgMail.setApiKey(process.env.SENDGRID_API_KEY as string);

export default async function _(req: NextApiRequest, res: NextApiResponse<DataResponse>) {
  if (req.method !== "POST") {
    res.status(400).json({ success: false, error: "Invalid request" });
    return;
  }

  const data = JSON.parse(req.body);
  const { name, email, phone = "", message = "" } = data;

  console.log("sgMail", sgMail);
  console.log("--------------");
  console.log("process.env.SENDGRID_API_KEY", process.env.SENDGRID_API_KEY);
  console.log("--------------");
  console.log("SENDGRID_EMAIL", process.env.SENDGRID_EMAIL);
  console.log("--------------");
  console.log("SENDGRID_EMAIL_TO", process.env.SENDGRID_EMAIL_TO);
  console.log("--------------");

  const text = `
  Name: ${name} \r\n
  Email: ${email} \r\n
  Phone: ${phone} \r\n
  message: ${message} \r\n
`;

  let emailData: EmailData = {
    to: emailAddressTo,
    from: emailAddress,
    subject: "Form submission",
    text: text,
    html: `<div>${text.replace(/\r\n/g, "<br>")}</div>`,
  };

  try {
    await sgMail.send(emailData);
  } catch (error) {
    console.log(error);
    res.status(400).json({ success: false, error: "Error while sending email" });
    return;
  }

  res.status(200).json({ success: true, data: {} });
}

服务器错误日志

sgMail MailService {
  client: Client {
    auth: 'Bearer HIDDEN BUT ITS THERE',
    impersonateSubuser: '',
    defaultHeaders: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'User-Agent': 'sendgrid/7.7.0;nodejs'
    },
    defaultRequest: {
      baseUrl: 'https://api.sendgrid.com/',
      url: '',
      method: 'GET',
      headers: {},
      maxContentLength: Infinity,
      maxBodyLength: Infinity
    }
  },
  substitutionWrappers: [ '{{', '}}' ],
  secretRules: [],
  MailService: [class MailService]
}
--------------
process.env.SENDGRID_API_KEY HIDDEN BUT ITS THERE
--------------
SENDGRID_EMAIL HIDDEN BUT ITS THERE
--------------
SENDGRID_EMAIL_TO: HIDDEN BUT ITS THERE
--------------
ResponseError: Unauthorized
    at node_modules/@sendgrid/client/src/classes/client.js:146:29
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 401,
  response: {
    headers: {
      server: 'nginx',
      date: 'Sun, 19 Feb 2023 20:57:56 GMT',
      'content-type': 'application/json',
      'content-length': '97',
      connection: 'close',
      'access-control-allow-origin': 'https://sendgrid.api-docs.io',
      'access-control-allow-methods': 'POST',
      'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
      'access-control-max-age': '600',
      'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
      'strict-transport-security': 'max-age=600; includeSubDomains'
    },
    body: { errors: [Array] }
  }
}

内容的提问来源于stack exchange,提问作者Bug_Pandz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:05:19