next.jshttprequestvercel

Next.js API timeout on Vercel


I just started using Next.js and am trying to set up a function in the API path. Locally, everything works fine but after I deploy to Vercel, I always get a timeout when calling the function. However, the request I send inside the function to add a contact to an email list is successful.

This is my code. I have a feeling that it might have something to do with the last two lines but I'm not sure. I'd appreciate any help.

var http = require("https");

export default (req, res) => {
  const body = JSON.parse(req.body);

  var options = {
    method: "PUT",
    hostname: "api.sendgrid.com",
    port: null,
    path: "/v3/marketing/contacts",
    headers: {
      authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
      "content-type": "application/json",
    },
  };

  var callback = (response) => {
    var chunks = [];

    response.on("data", function (chunk) {
      chunks.push(chunk);
    });

    response.on("end", function () {
      var body = Buffer.concat(chunks);
      console.log(body.toString());
    });
  };

  var data = JSON.stringify({
    list_ids: ["1e4e78b5-3aa4-4cdd-bf81-d1f7a3014098"],
    contacts: [
      {
        email: body.email,
      },
    ],
  });

  var request = http.request(options, callback);

  request.write(data)

  request.end();
  
  res.status(204).json({ status: "Ok" });
};

Solution

  • I ran into the same issue on Vercel. Eventually figured out that Vercel doesn't like the 204 status code.

    Change this line

      res.status(204).json({ status: "Ok" });
    

    to

      res.status(200).json({ status: "Ok" });
    

    and it should work.