The short answer: send email from server code only. Use a Server Action when a form in your app triggers the email, and a Route Handler when something outside calls you (a webhook, a cron job). Keep the API key in an environment variable without the NEXT_PUBLIC_ prefix, and give each send an idempotency key so a retry does not send the email twice.
This guide uses the SMTPfast Node SDK (@smtpfast/sdk), which runs in the Node.js and Edge runtimes and has no runtime dependencies. The same structure works with any email API.
What you need
- A Next.js app with the App Router.
- An SMTPfast account with a verified sending domain: publish the DKIM, SPF and DMARC records SMTPfast gives you at your DNS host, then verify. See Domains.
- An API key with the
email:sendscope, plusemail:readif you look emails up by id (step 5).
npm install @smtpfast/sdk
# .env.local (no NEXT_PUBLIC_ prefix, so it never reaches the browser)
SMTPFAST_API_KEY=sf_...
Step 1: one server-only email module
Put the client in one file and mark it server-only. If a Client Component ever imports it, the build fails instead of shipping your key to the browser.
// lib/email.ts
import "server-only";
import { SMTPfast } from "@smtpfast/sdk";
export const smtpfast = new SMTPfast(); // reads SMTPFAST_API_KEY
export async function sendWelcomeEmail(to: string, name: string) {
return smtpfast.emails.send(
{
from: "Acme <[email protected]>",
to: [to],
subject: `Welcome, ${name}`,
html: `<p>Hi ${name}, your account is ready.</p>`,
category: "transactional",
},
{ idempotencyKey: `welcome-${to}` },
);
}
server-only is a small package (npm install server-only). category: "transactional" matters: SMTPfast treats email without a category as marketing and adds an unsubscribe link, which you do not want on a sign-in code or a receipt. Escape any user input you put into HTML; the example keeps it short.
Step 2: send from a Server Action
Use a Server Action when your own UI triggers the email, such as a signup or invite form.
// app/signup/actions.ts
"use server";
import { redirect } from "next/navigation";
import { sendWelcomeEmail } from "@/lib/email";
export async function signUp(formData: FormData) {
const email = String(formData.get("email") ?? "").trim();
const name = String(formData.get("name") ?? "").trim();
if (!email.includes("@") || !name) redirect("/signup?error=missing");
// ...create the user in your database first...
await sendWelcomeEmail(email, name);
redirect("/welcome");
}
// app/signup/page.tsx
import { signUp } from "./actions";
export default function SignupPage() {
return (
<form action={signUp}>
<input name="name" placeholder="Name" />
<input name="email" type="email" placeholder="[email protected]" />
<button type="submit">Sign up</button>
</form>
);
}
A Server Action is a public HTTP endpoint, the same as a Route Handler. Check the session and validate the input inside it, and rate limit forms that anyone can submit.
Do not make the user wait for the email
If the email is not part of the response, send it after the response with after() from next/server. The user sees the next page at once, and the send runs when the response is finished.
import { after } from "next/server";
after(async () => {
await sendWelcomeEmail(email, name);
});
after() is not a queue. If the send fails, nothing retries it beyond the SDK's own retries (two by default, after a 429, 408, 5xx or a dropped connection). For email that must go out, write a row to your database first and send from a job that can retry.
Step 3: send from a Route Handler
Use a Route Handler when another system calls you, for example a payment webhook that should send a receipt.
// app/api/receipts/route.ts
import { smtpfast } from "@/lib/email";
export async function POST(request: Request) {
// Check the caller's signature or token here before you trust the body.
const { orderId, email, total } = await request.json();
const sent = await smtpfast.emails.send(
{
from: "Acme <[email protected]>",
to: [email],
subject: `Receipt for order ${orderId}`,
text: `Thanks for your order. Total: ${total}.`,
category: "transactional",
},
{ idempotencyKey: `receipt-${orderId}` },
);
return Response.json({ id: sent.id });
}
The idempotency key is the order id, so if the payment provider delivers the same webhook twice within 24 hours, the API returns the first answer instead of sending a second receipt. Keys are kept for 24 hours, so also record in your database that the receipt went out, for retries that come later.
Step 4 (optional): React Email templates
With React Email, the template is a component, and you render it to HTML on the server:
npm install @react-email/components @react-email/render
// emails/welcome.tsx
import { Html, Body, Heading, Text } from "@react-email/components";
export function WelcomeEmail({ name }: { name: string }) {
return (
<Html>
<Body>
<Heading>Welcome, {name}</Heading>
<Text>Your account is ready.</Text>
</Body>
</Html>
);
}
Rename lib/email.ts to lib/email.tsx so it can hold JSX, and render inside the send function:
// lib/email.tsx
import "server-only";
import { SMTPfast } from "@smtpfast/sdk";
import { render } from "@react-email/render";
import { WelcomeEmail } from "@/emails/welcome";
export const smtpfast = new SMTPfast();
export async function sendWelcomeEmail(to: string, name: string) {
const html = await render(<WelcomeEmail name={name} />);
return smtpfast.emails.send(
{ from: "Acme <[email protected]>", to: [to], subject: `Welcome, ${name}`, html, category: "transactional" },
{ idempotencyKey: `welcome-${to}` },
);
}
React escapes name for you here. SMTPfast also creates the plain-text part for you when you send only HTML. For templates you edit in a dashboard instead of in code, see Templates and React Email templates.
Step 5: know what happened to the email
emails.send returns an id when the API accepts the email. Delivery happens after that. To react to bounces and complaints, add a webhook (paid plans) and check its signature in a Route Handler. The SDK's parseWebhook takes the raw body, so read it with request.text(), not request.json():
// app/api/webhooks/smtpfast/route.ts
import { parseWebhook } from "@smtpfast/sdk";
export async function POST(request: Request) {
const event = await parseWebhook({
payload: await request.text(),
headers: request.headers,
secret: process.env.SMTPFAST_WEBHOOK_SECRET!,
});
if (event.type === "email.bounced") {
// mark the address as bad in your database
}
return new Response(null, { status: 204 });
}
On any plan you can also look up an email by id (smtpfast.emails.get(id)) or open it in the dashboard log, which shows every attempt and the reason for a bounce.
Server Action or Route Handler?
| Server Action | Route Handler | |
|---|---|---|
| Who calls it | Your own forms and components | Anyone with the URL: webhooks, cron, other services |
| Typical email | Welcome, invite, contact form | Receipt from a payment webhook, scheduled digest |
| Input | FormData or arguments |
Request body and headers |
| Check before sending | Session and input | Signature or token of the caller |
Before you go live
- The
fromaddress is on a verified domain, and DKIM, SPF and DMARC pass. Check them with the SPF, DKIM and DMARC checkers. - The API key is only in server environment variables, and it has only the scopes it needs.
- Every send that can be retried has an idempotency key.
- Transactional email has
category: "transactional". - Public forms that send email have a rate limit or a captcha, or they become a spam relay.
If you are choosing a provider, the email API price comparison lists free tiers and prices, and Node.js without an SDK shows the same send with plain fetch().
Frequently asked questions
How do I send email from Next.js?
Call an email API from server code: a Server Action for form submissions, or a Route Handler (app/api/.../route.ts) for webhooks and other HTTP callers. Install an SDK such as @smtpfast/sdk, put the API key in an environment variable without the NEXT_PUBLIC_ prefix, and call emails.send with from, to, subject and html.
Can I send email from a Next.js Client Component?
No. Code in a Client Component runs in the browser, so the API key would be public and anyone could send email as you. Send from a Server Action, a Route Handler or other server-only code, and import 'server-only' in the module that holds the key.
Can I use SMTP and Nodemailer in Next.js instead of an API?
Yes, in the Node.js runtime. Nodemailer opens a TCP connection, so it does not run in the Edge runtime, and some hosts block outbound SMTP ports. An HTTP email API works in both runtimes and returns an id you can look up later.
Do I need React Email to send email from Next.js?
No. Any HTML string works. React Email lets you write the template as a React component and render it to HTML on the server before you call the API.
Ready to get started?
Start sending transactional email today. Free to start, no credit card required.
Get Started for FreeRelated Posts
Cheapest Transactional Email API in 2026: Free Tiers and Prices Compared
Amazon SES is the cheapest per email at $0.10 per 1,000, but you wire up bounce handling and logs yourself. Among managed email APIs, Mailjet (6,000 a month) and Mailtrap (4,000) have the largest monthly free tiers, and SMTPfast has the lowest price we found at 50,000 and 100,000 emails a month ($19). Every price below was checked on the provider's own pricing page on 21 November 2026.
How to Check the SPF, DKIM and DMARC Records for Your Domain
Look up three DNS TXT records: SPF at the domain itself (v=spf1), DKIM at selector._domainkey.yourdomain.com (v=DKIM1, or a CNAME to your provider), and DMARC at _dmarc.yourdomain.com (v=DMARC1). Use dig on macOS and Linux, nslookup on Windows, or a free online checker, then send a real test email to confirm all three pass.