Upon a user's registration, I am attempting to send a registration/account activation email. While the email sends successfully via Azure's email services when running on localhost, deployments on Vercel do not trigger the email (although the user is added to the database).
I have researched issues related to Vercel-hosted deployments and email sending problems, often stemming from serverless functions terminating prematurely upon receiving a response, before the email is sent out. Despite trying asynchronous function calls with await/async methods in Microsoft's Azure Email Communication services, I have not been able to achieve the desired behavior. Are there any suggestions or fixes for this specific problem?
Similar issue link
Main takeaways from the provided link:
- Requests must be resolved within 10 seconds on the free tier (60 seconds for pro),
- Vercel appears to terminate a serverless function immediately after receiving a response, potentially halting unfinished side effects.
The solution mentioned adding an await statement to the email sending process, but since Azure's email client includes
const poller = await emailClient.beginSend(emailMessage);
const result = await poller.pollUntilDone();
the entire operation should await completion before the function returns, ensuring that the email is sent before termination.
Below is the key part of the code responsible for sending emails found in the api/register/route.ts
file.
export async function POST(
request: Request,
) {
const connectionString = process.env['COMMUNICATION_SERVICES_CONNECTION_STRING'];
const emailClient = new EmailClient(connectionString);
async function main() {
const emailMessage = {
senderAddress: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fcb893b29388ae998c9085bc9a95ffbbc4b0e6bbb7b1">[email protected]</a>",
content: {
subject: ``,
text: ``,
html: ``,
},
recipients: {
to: [{ address: user.email }], // rest of the code is omitted for brevity
},
};
const poller = await emailClient.beginSend(emailMessage);
const result = await poller.pollUntilDone();
console.log("Email sent: %s", result);
}
main().catch(console.error);
// setTimeout(() => { return NextResponse.json(user); }, 3000);
return NextResponse.json(user);
}
I attempted using a timeout buffer before responding to allow time for the email to be sent before the serverless function ends, however, it resulted in an error being thrown and caught both here and in the outer caller of this api route.ts.
My expectation was for the email to be successfully sent before the serverless function terminates, although errors were encountered during the process.
"error TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:261:61)"