Next.js course Elaborate on "We don't want email endpoint in real application"?

In the Next.js course “sending emails” lesson Mosh says this is just for demo purposes and that we wouldn’t want a send-email end point in a real application.

He gives the example that instead, when a user buys something we would send off an email. And that this is part of business operations.

So I am confused as to what this means. How would we send off that email?

Would I create a function or hook on the client side and send it that way instead?

Or do you mean on a endpoint like “api/order” we would make it part of that process instead of it having it’s own send-email endpoint?

Thinking more about it I guess that’s what was meant. It wouldn’t be safe sending off emails from the front end.

I am not actually enrolled in it, So, I might be missing some context. What I understand is, sending email is an I/O heavy task. There are several network calls involved to SMTP server and we do not want to block the main thread.
Instead we often do it as a background task, often running in a completely different server. In general, we send emails by Sendgrid, Mailgun etc in background. So, as to avoid blocking the request for several seconds.
Reference : 9. Asynchronous programming for FastAPI

2 Likes

Thanks @shubhamgargii

We are using react-email and resend as the integration react email integrations

For demo purposes we setup a api/send-email endpoint.

After giving it some more thought, I’m pretty sure all Mosh was saying was that in a real application we would send the email from another endpoint process such as api/register or api/checkout instead of actually having a separate endpoint for sending the email.

This is the demo

import { NextResponse } from 'next/server';
import { Resend } from 'resend';
import WelcomeTemplate from '~/emails/WelcomeTemplate';

const resend = new Resend(process.env.RESEND_API_KEY);

export async function POST() {
  await resend.emails.send({
    from: 'foo@somelegitdomain.com',
    to: 'user@useremail.com',
    subject: 'Welcome Foo',
    react: <WelcomeTemplate name="user name" />,
  });

  return NextResponse.json({});
}

As for your good points about async and passing the I/O heavy task off to another server, I’m wondering and can only assume at this point if resend actually waits for confirmation that the email was successfully sent or just sends it off and returns so my code can continue. Surely they take care of things on their end. I can’t even test it until I setup a legitimate domain. It won’t work with gmail.

Seems I’ve got some reading, coding, and testing to do.

Thanks