import type { NextApiRequest, NextApiResponse } from "next" import { Resend } from "resend" const resend = new Resend(process.env.RESEND_API_KEY) const FROM_ADDRESS = process.env.RESEND_FROM_ADDRESS || "Nexment " const CORS_HEADERS: Record = { "Access-Control-Allow-Origin": process.env.ALLOWED_ORIGIN || "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", } interface MailerRequestBody { fromName: string toEmail: string content: string url: string } function buildEmailHtml(body: MailerRequestBody): string { return `
Nexment

${body.fromName} left a reply:

${body.content}

Reply back

You're receiving this because someone replied to your comment.

` } function setCorsHeaders(res: NextApiResponse) { Object.entries(CORS_HEADERS).forEach(([key, value]) => res.setHeader(key, value) ) } const handler = async (req: NextApiRequest, res: NextApiResponse) => { setCorsHeaders(res) if (req.method === "OPTIONS") { res.status(204).end() return } if (req.method !== "POST") { res.status(405).json({ error: "Method not allowed" }) return } const body = req.body as MailerRequestBody if (!body.toEmail) { res.status(400).json({ error: "Target email missing" }) return } const { data, error } = await resend.emails.send({ from: FROM_ADDRESS, to: [body.toEmail], subject: `You received a new reply from ${body.fromName}!`, html: buildEmailHtml(body), }) if (error) { res.status(500).json(error) return } res.status(200).json(data) } export default handler