
本文详解 resend node.js sdk 的正确初始化方式,重点解决因错误解构导致的 `typeError: resend is not a constructor` 问题,并提供可直接运行的配置示例与最佳实践。
Resend 官方 node.js SDK(resend npm 包)并非默认导出一个可直接 new 的类,而是一个命名导出(named export)模块,其核心客户端类名为 Resend。因此,若按 CommonJS 方式直接 require(“resend”) 并对整个模块调用 new,将触发 TypeError: resend is not a constructor —— 这正是你遇到的根本原因。
✅ 正确初始化方式(推荐)
使用解构语法导入 Resend 类,再实例化:
const { Resend } = require("resend"); const resend = new Resend(process.env.RESEND_API_KEY); // 注意:环境变量名建议使用 RESEND_API_KEY(非 KEY_RESEND),更符合惯例
? 提示:process.env.RESEND_API_KEY 需在 .env 文件中预先配置,例如:RESEND_API_KEY=re_1234567890abcdef…
? 常见错误写法(会导致报错)
// ❌ 错误:resend 是一个对象,不是构造函数 const resend = require("resend"); const instance = new resend(process.env.KEY_RESEND); // TypeError! // ❌ 错误:未解构即尝试 new(ESM 语法下同理) import resend from "resend"; // 默认导入在 v3+ 不可用 const client = new resend(...);
✅ 完整可运行示例(修复后的 sendMail.js)
const { Resend } = require("resend"); // 初始化客户端(全局单例,避免重复创建) const resendClient = new Resend(process.env.RESEND_API_KEY); const sendMail = async (from, to, subject, html, text = "") => { try { const data = await resendClient.emails.send({ from, to, subject, html, text, // 注意:原代码中未定义变量 `text`,此处已修正为参数传入或设默认空字符串 headers: { "X-Entity-Ref-ID": Date.now().toString(), // 建议使用唯一标识(如时间戳/UUID),而非 API Key }, tags: [ { name: "category", value: "reset_password", }, ], }); console.log("✅ Email sent successfully:", data); return data; } catch (error) { console.error("❌ Failed to send email:", error); throw error; // 建议抛出错误,便于上层统一处理 } }; module.exports = sendMail;
⚠️ 注意事项与最佳实践
- 环境变量安全:确保 .env 文件已通过 dotenv 加载(如 require(‘dotenv’).config()),且不提交至 git。
- API Key 权限:在 Resend Dashboard 中确认 API Key 具备 emails.send 权限,并已验证发件域名(如 yourdomain.com)和邮箱地址(如 noreply@yourdomain.com)。
- 参数校验:生产环境建议对 from、to、subject、html 做基础非空校验,避免静默失败。
- 错误处理:resendClient.emails.send() 抛出的是标准 Error 对象,包含 name、message 和 statusCode 属性,应优先依据 error.statusCode(如 422 表示参数错误)做精细化响应。
- ESM 支持:若项目使用 ES Module(”type”: “module”),请改用:
import { Resend } from "resend"; const resend = new Resend(process.env.RESEND_API_KEY);
✅ 总结
new resend(…) 报错的本质是模块导出方式理解偏差。只需牢记:resend 包导出的是 { Resend },而非默认构造函数。采用 const { Resend } = require(“resend”) 解构后实例化,即可彻底解决该问题。此模式也适用于 Resend SDK 所有后续版本(v3.x+),具备长期兼容性。