mailguncloudflare-pagesmailgun-api

Mailgun sending API works on local dev server, but catches Bad Request error on Cloudflare Pages deployment?


In my Astro project, I handle form submissions server-side to email me the form data via Mailgun. When I tested it on my local dev server, my request to the Mailgun api got a 200, and I sent the email to myself successfully. However, once I deployed to Cloudflare Pages, my api call would catch an error of Error: Bad Request" upon reaching the try { const res = await mg.messages.create( ... ) } catch (err) {...} block accordiing to CF server logs, where the error was not an object returned to res, but rather an err that was caught. Relevant code below:

formHandler.ts

export const prerender = false;
import type { APIRoute } from "astro";
import { MAIL_SERVER, MG_SENDING_API, INQUIRY_INBOX } from "astro:env/server";
import Mailgun from "mailgun.js";
import FormData from "form-data";

export const POST: APIRoute = async ({ request }) => {
  const data = await request.formData();

  const msg = data.get("message");
  
  const mailgun = new Mailgun(FormData);
  const mg = mailgun.client({
    username: "api",
    key: MG_SENDING_API,
  });
  
  try {
    const apiRes = await mg.messages.create(MAIL_SERVER, {
      from: `Inquiry <relay@${MAIL_SERVER}>`,
      to: [INQUIRY_INBOX],
      subject: "New Inquiry",
      html: `<h5>Inquiry:</h5> <p>${msg}</p>`
    });

    if (apiRes.status===200) {
      ...
    } else {
      ...
   }
  } catch (err) {
    console.error(err);
};

UPDATE: I just tried adding a wrangler.toml file to enable node compatibility mode on CF, but the error still persists.

Any suggestions for what may be causing the error would be appreciated. Thanks.


Solution

  • RESOLVED

    UPDATE: I have identified the issue as the fact that Cloudflare Workers don't run in a full node environment, and thus they don't support certain dependencies in the "form-data" library. After refactoring my formHandler to make a fetch call to Mailgun's api directly rather than using the mailgun.js and form-data libraries, the issue was resolved on my deployed website.