502 error from Netlify function

Function that was working is returning 502

Impacting:

//  /pages/APItest.js
export default function APItest() {
  function testApi() {
    console.log("fetching");
    fetch("/.netlify/functions/mailchimp", {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        firstName: "testperson",
        lastName: "testperson",
        email: "hellonewemail@gmail.com",
        product: "fundamentals-membership",
      }),
    })
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  }

  return (
    <>
      <div>
        <button className="btn btn-accent" onClick={testApi}>
          Test Mailchimp
        </button>
      </div>
    </>
  );
}

//  /functions/mailchimp.js
const mc = require("@mailchimp/mailchimp_marketing");
require("dotenv").config();
const fs = require("fs").promises;

const LIST_ID = process.env.MAILCHIMP_LIST_ID;

mc.setConfig({
  apiKey: process.env.MAILCHIMP_API_KEY,
  server: "us8",
});

const crypto = require("crypto");

const headers = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "Content-Type",
};

exports.handler = async function (event, context) {
  let contactObj = { statusCode: 200, headers, response: "something happened" };
  try {
    let payments = await fs.readFile("./src/data/payments.json");
    payments = JSON.parse(payments);
    const data = JSON.parse(event.body);
    const product = payments.find((payment) => payment.name === data.product);

    const id = crypto
      .createHash("md5")
      .update(data.email.toLowerCase())
      .digest("hex");

    const mergeFields = {
      EMAIL: data.email,
      FNAME: data.firstName,
      LNAME: data.lastName,
    };

    mc.lists
      .getListMember(LIST_ID, id)
      .then(function (data) {
        console.log("Existing subscriber.");
        // Update subscriber with new tag
        mc.lists.setListMember(LIST_ID, id, {
          email_address: data.email,
          status: "subscribed",
          tags: [product.name],
          merge_fields: mergeFields,
        });
        contactObj.response = "Updated subscriber: " + data.email;
        return contactObj;
      })
      .catch(function (err) {
        console.log("Adding", data.email);
        mc.lists.addListMember(LIST_ID, {
          email_address: data.email,
          status: "subscribed",
          status_if_new: "subscribed",
          merge_fields: mergeFields,
          tags: [product.name],
        });
        contactObj.response = "Updated subscriber: " + data.email;
        return contactObj;
      })
      .catch(function (err) {
        console.log("Error:", err);
        contactObj.statusCode = err.status;
        contactObj.response = err.error;
        return contactObj;
      });
  } catch (err) {
    console.log(err);
    contactObj.statusCode = 400;
    contactObj.response = JSON.stringify({ error: err.message });
    return contactObj;
  }
};
//  netlify.toml
# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
  [headers.values]
  Access-Control-Allow-Origin = "*"
  
[build]
  functions = "functions" # netlify dev uses this directory to scaffold and serve your functions
  publish = "build"

[dev]
  command = "npm run start"
  port = 8888
  targetPort = 3000
  publish = "dist" 
  autoLaunch = true
  framework = "create-react-app"

[functions]
  directory = "functions"
  node_bundler = "esbuild"
  external_node_modules = ["@mailchimp/mailchimp_marketing", "dotenv", "sib-api-v3-sdk", "stripe"]
  included_files = ["./src/data/payments.json"]

Hey @NicoleJaneway,

Would you be able to share a HAR file recording of this issue or the x-nf-request-id? I checked and couldn’t find any 502 or any status over 499 for that site.

Also, I didn’t see any error in your Function console, so it’s hard to see what the problem could be.

Hi there - the error is on Data Strategy Professionals when you hit the Test Mailchimp button.

Could you try adding return before mc.lists? So something like return mc.lists

Working - thank you!!