3

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" });
};

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sounds interesting. I'll give it a try and report back.
0

I had a problem that after deployment to Vercel . The API route returned 504 gateway timeout vercel .

I found the solution here https://vercel.com/docs/errors/FUNCTION_INVOCATION_TIMEOUT

increasing maxDuration for this route according to the plan

set a variable to specify the node.js runtime and the timeout

export const runtime = 'nodejs';
export const maxDuration = 59;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.