Judeson
Judeson

Reputation: 31

Why am I getting a 500 error when sending emails using Resend in my Next.js API route?

I'm building a Next.js application where I'm trying to send emails using the Resend service within an API route. However, I keep encountering a 500 error, and I'm not sure what's causing it. Below are the details:

app/api/send/route.ts

import { Resend } from "resend";
import { MeetingRequest } from "@/api/email-templates/MeetingRequest";

const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_KEY);

export async function POST(request: Request) {
  const {
    to_email,
    receiver_name,
    scheduler_id,
    scheduler_name,
    scheduled_time,
    scheduler_tz,
    question_title,
    question_id,
    sender_note,
  } = await request.json();

  try {
    const { data, error } = await resend.emails.send({
      from: "Codey from CodingOH <[email protected]>",
      to: [to_email],
      subject: `You received a meeting request from ${scheduler_name}!`,
      react: MeetingRequest({
        receiver_name,
        scheduler_id,
        scheduler_name,
        scheduled_time,
        scheduler_tz,
        question_title,
        question_id,
        sender_note,
      }),
    });

    if (error) {
      console.error("[UP] Error sending email:", error);
      return Response.json({ error }, { status: 500 });
    }

    return Response.json({ data });
  } catch (error) {
    console.error("[DOWN] Error sending email:", error);
    return Response.json({ error }, { status: 500 });
  }
}

app/questions/[id]/route.tsx

const response = await fetch("/api/send", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    to_email: question.asker?.email_address ?? "",
    receiver_name: question.asker?.first_name ?? "",
    scheduler_id: coder?.auth_id ?? "",
    scheduler_name: `${coder?.first_name} ${coder?.last_name}`,
    scheduled_time: formattedDate?.toISOString() ?? "",
    scheduler_tz: coder?.timezone ?? "",
    question_title: question.question ?? "",
    question_id: question.id ?? 0,
    sender_note: scheduleMessage || "",
  }),
});
if (!response.ok) {
  console.error(
    "Error sending meeting request email:",
    await response.text()
  );
} else {
  const data = await response.json();
  console.log("Meeting request email sent:", data);
}

api/email-templates/MeetingRequest.tsx

import React from "react";
import Link from "next/link";
import { FaCode } from "react-icons/fa6";
import { parseISO, format } from "date-fns";
import { toZonedTime } from "date-fns-tz";

export const MeetingRequest = (props: {
  receiver_name: string;
  scheduler_id: string;
  scheduler_name: string;
  scheduled_time: string;
  scheduler_tz: string;
  question_title: string;
  question_id: number;
  sender_note: string;
}) => {
  const {
    receiver_name,
    scheduler_id,
    scheduler_name,
    scheduled_time,
    scheduler_tz,
    question_title,
    question_id,
    sender_note,
  } = props;

  const date = parseISO(scheduled_time);
  const zonedDate = toZonedTime(date, scheduler_tz);
  const formattedDate = format(zonedDate, "MMMM dd, yyyy 'at' h:mm a");

  return (
    <main className="flex flex-col items-center justify-center bg-slate-200">
      <div className="flex items-center justify-center w-full py-2 bg-slate-300">
        <Link href="https://codingoh.com" className="flex flex-row items-center ml-[10px]">
          <FaCode className="text-3xl" />
          <div className="flex flex-col">
            <span className="text-2xl text-blue-700 font-bold ml-2">CodingOH</span>
            <span className="text-[10.5px] ml-2">Stack Overflow in Real Time</span>
          </div>
        </Link>
      </div>
      <div className="flex flex-col gap-2 w-full p-2 bg-white text-sm">
        <p>Hi {receiver_name},</p>
        <p>
          <Link href={`https://codingoh.com/users/${scheduler_id}`} className="text-blue-500 hover:underline">
            {scheduler_name}
          </Link> 
          has requested a meeting with you on 
          <span className="font-bold underline">{formattedDate}</span>.
          Specically, {scheduler_name.split(" ")[0]} wants to help you out with
          this question:{" "}
          <Link href={`https://codingoh.com/questions/${question_id}`} className="text-blue-500 hover:underline">
            {question_title}
          </Link>.
        </p>
        {sender_note && (
          <div className="bg-slate-300 p-2 rounded-md">
            <p className="font-semibold">Sender Note</p>
            <p>{sender_note}</p>
          </div>
        )}
        <p>
          You can choose to <span className="text-green-500">accept</span>, 
          <span className="text-red-500">reject</span>, or 
          <span className="text-blue-500">reschedule</span> the meeting. If you
          plan on rescheduling the meeting to another time, let 
          {scheduler_name.split(" ")[0]} know what time you would like it
          scheduled at. Make sure to include your time zone to avert confusion
          about the starting time.
        </p>
        <div className="flex items-center justify-center w-full">
          <Link href={`https://codingoh.com/questions/${question_id}`} className="p-2 bg-blue-600 text-white rounded-md">
            Check Out the Meeting Request
          </Link>
        </div>
        <div>
          <p>Best,</p>
          <p className="flex flex-row items-center gap-1 text-blue-700 font-bold">
            CodingOH <FaCode />
          </p>
        </div>
      </div>
    </main>
  );
};

GitHub Repo: https://github.com/jesuschrist-immanuel/stack-overflow-clone

When I make the POST request, I get a 500 error and the response returns {"error":{}}. I suspect this might be an issue with how I'm using the resend.emails.send method, but I'm not sure how to troubleshoot further.

Things I've tried:

Any guidance or assistance in resolving this issue would be greatly appreciated!

Upvotes: 0

Views: 117

Answers (0)

Related Questions