0

The usual thing - everything works great in development and then it doesn't in production for no obvious reason. I have a NextJS app hosted on Vercel.

I tried adding async await to my code as suggested by another StackOverflow thread but I still can't make this work. I've added the Sendinblue API key as an environment variable in Vercel. Here's my contact.js in the api folder:

export default async function (req, res) {
  require("dotenv").config();
  const Sib = require("sib-api-v3-sdk");
  const client = Sib.ApiClient.instance;
  const apiKey = client.authentications["api-key"];
  apiKey.apiKey = process.env.SendinBlueApiKey;

  const tranEmailApi = new Sib.TransactionalEmailsApi();

  const sender = {
    email: req.body.email,
  };

  const receivers = [
    { email: "example@example.com" },
  ];

  await new Promise((resolve, reject) => {
    tranEmailApi
      .sendTransacEmail({
        sender,
        to: receivers,
        subject: `${req.body.service} from ${req.body.name}`,
        textContent: req.body.message + " | Sent from: " + req.body.email,
        htmlContent: `<div>${req.body.message}</div><p>Sent from:
      ${req.body.name} , 
      ${req.body.email}</p>`,
      })
      .then(res.status(200).send())
      .catch(console.log);
  });
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146

1 Answers1

1

I had the same problem it was driving me up the walls. Replace this:

await new Promise((resolve, reject) => {
tranEmailApi
  .sendTransacEmail(...)
  .then(res.status(200).send())
  .catch(console.log);;
}

with this

const emailResult = await tranEmailApi.sendTransacEmail(...);

I think the problem is that otherwise the vercel function finishes before the sendinblue api call returns.

Lucas
  • 13,679
  • 13
  • 62
  • 94