Send email with Next.js

Send email from a route handler or a server action, without leaking the key to the browser.

You need a verified sending domain and an API key from Settings › API Keys. If neither exists yet, the quickstart covers both in a couple of minutes.

Install

npm i sending-sdk

Send

import { Sending } from "sending-sdk";
 
const sending = new Sending({ apiKey: process.env.SENDING_API_KEY! });
 
export async function POST(req: Request) {
  const { email, userId } = await req.json();
  const { id } = await sending.emails.send({
    from: "Acme <[email protected]>",
    to: email,
    subject: "Welcome",
    html: "<p>You're in.</p>",
    // Tied to the event, not random: a retried request must not send twice.
    idempotencyKey: `welcome-${userId}`,
  });
  return Response.json({ id });
}

A successful call answers 202 with the message id: accepted and queued, not yet delivered. Delivery, opens, bounces and complaints arrive later, on webhooks or in the dashboard.

What changes in Next.js

Keep the call server-side: a route handler, a server action or a server component. The API key is a full-account credential and anything imported by a client component ends up in the bundle.

The thing that catches people

In development a route handler can run twice per request under React Strict Mode. With a stable idempotencyKey the second call is recognised and returns the first id instead of sending again.

Next

  • All the fields: cc and bcc, reply-to, attachments, templates, scheduling.
  • Webhooks: delivery, bounce and complaint events, signed with HMAC.
  • Domains: SPF, DKIM and MAIL FROM, and why sending is refused until they are in place.
  • MCP: the same operations as tools, when the one writing the code is an agent.

Nearby: JavaScript and TypeScript

All 30 stacks