Next.js
Send email from a Next.js App Router app — a Server Action, a Route Handler, React Email, a one-line webhook endpoint, and an end-to-end check with the magic addresses.
1. Install and set the key
npm install @charchy/sendCHARCHY_SEND_KEY=chy_test_…
CHARCHY_SEND_FROM="My App <no-reply@myapp.com>"
CHARCHY_WEBHOOK_SECRET=whsec_…Never a NEXT_PUBLIC_ variable: those are bundled into the browser. On
Vercel, add the same three under Settings → Environment Variables.
2. The client
import "server-only"
import { CharchySend } from "@charchy/send"
/** Reads CHARCHY_SEND_KEY when an email is sent, not now: `next build` never needs the key. */
export const send = new CharchySend()
export const FROM = process.env.CHARCHY_SEND_FROM! // "My App <no-reply@myapp.com>"Creating the client reads no key — the key is read when an email is sent — so
next build, which imports every route module, runs fine without it. With no
key at run time, a send returns missing_api_key and nothing goes out.
server-only turns an import from a Client Component into a build error.
3. From a Server Action
"use server"
import { FROM, send } from "@/lib/charchy-send"
export type InviteState = { sent: boolean; error?: string }
export async function sendInvite(_previous: InviteState, formData: FormData): Promise<InviteState> {
// A Server Action is a public POST endpoint: check the session and permission here.
const email = String(formData.get("email"))
const inviteId = crypto.randomUUID() // in your app: the id of the invitation you just saved
const { error } = await send.emails.send(
{
from: FROM,
to: email,
subject: "You're invited to My App",
html: `<p><a href="https://myapp.com/invite/${inviteId}">Accept the invitation</a></p>`,
tags: { type: "invite" },
},
{ idempotencyKey: `invite/${inviteId}` }
)
if (error) {
console.error(error.code, error.requestId)
return { sent: false, error: error.code === "validation_error" ? "Check the address." : "Couldn't send. Try again." }
}
return { sent: true }
}"use client"
import { useActionState } from "react"
import { sendInvite } from "./actions"
export function InviteForm() {
const [state, action, pending] = useActionState(sendInvite, { sent: false })
return (
<form action={action}>
<input type="email" name="email" required />
<button type="submit" disabled={pending}>
{pending ? "Sending…" : "Send invite"}
</button>
{state.error && <p role="alert">{state.error}</p>}
{state.sent && <p>Invitation sent.</p>}
</form>
)
}The SDK never throws: every call resolves to { data, error }. It retries
network errors, 5xx and 429 itself, with the same idempotency key — no
retry loop of your own.
4. From a Route Handler, with React Email
npm install @react-email/render @react-email/componentsimport { Body, Button, Html, Preview, Text } from "@react-email/components"
export function WelcomeEmail({ name }: { name: string }) {
return (
<Html>
<Preview>Welcome to My App</Preview>
<Body>
<Text>Welcome, {name}.</Text>
<Button href="https://myapp.com/start">Get started</Button>
</Body>
</Html>
)
}import { FROM, send } from "@/lib/charchy-send"
import { WelcomeEmail } from "@/emails/welcome"
export async function POST(request: Request) {
// Your auth check here, then read what you need from the request.
const { userId, email, name } = (await request.json()) as { userId: string; email: string; name: string }
const { data, error } = await send.emails.send(
{
from: FROM,
to: email,
subject: "Welcome to My App",
react: WelcomeEmail({ name }), // rendered to html with @react-email/render
tags: { type: "welcome" },
},
{ idempotencyKey: `welcome/${userId}` }
)
if (error) return Response.json({ error: error.code }, { status: error.statusCode ?? 502 })
return Response.json({ id: data.id })
}react needs @react-email/render (Node 20+); without it the call returns
react_render_error. Route Handlers run on Node.js by default — leave out a
runtime export; the Edge runtime is deprecated.
Don't make the person wait
When the email isn't the answer to the request, send it after the response
with after() (on Vercel it runs inside waitUntil):
import { after } from "next/server"
import { FROM, send } from "@/lib/charchy-send"
export async function POST(request: Request) {
const { email } = (await request.json()) as { email: string }
const user = await createUser(email)
// Answer now; send once the response is out.
after(async () => {
const { error } = await send.emails.send(
{ from: FROM, to: user.email, subject: "Welcome", text: "Glad you're here." },
{ idempotencyKey: `welcome/${user.id}` }
)
if (error) console.error("welcome email", error.code, error.requestId)
})
return Response.json({ id: user.id }, { status: 201 })
}Sign-in codes from Better Auth go the same way,
through its advanced.backgroundTasks option.
5. Webhooks in one line
import { webhookHandler } from "@charchy/send"
export const POST = webhookHandler({
"email.bounced": (event) => markUndeliverable(event.data.recipient, `bounced: ${event.data.bounce.type}`),
"email.complained": (event) => markUndeliverable(event.data.recipient, "complained"),
})It verifies the signature on the raw body with CHARCHY_WEBHOOK_SECRET, runs
the handler for that event type, and answers 204 — 400 to a bad
signature, 500 when a handler throws, so the event is sent again. Handlers
run before the answer, which must come within 5 seconds: hand slow work to
after() or a queue. In the dashboard, under Webhooks, add
https://myapp.com/api/webhooks/charchy. More: Webhooks,
verifyWebhook to do it yourself.
6. Check it end to end
With a test key, the magic addresses play out a known outcome, free:
// npx tsx --env-file=.env.local scripts/email-check.ts
import { CharchySend, unwrap } from "@charchy/send"
const send = new CharchySend()
for (const outcome of ["delivered", "bounced"] as const) {
const sent = await send.emails
.send(
{ from: "My App <hello@example.com>", to: send.test.address(outcome, "nextjs"), subject: "Check", text: "ok" },
{ idempotencyKey: `email-check/${outcome}/${Date.now()}` }
)
.then(unwrap)
const email = await send.emails.waitFor(sent.id, { until: [outcome], timeoutMs: 30_000 }).then(unwrap)
console.log(outcome, email.id, email.status)
}The bounce also reaches your webhook endpoint as email.bounced (deployed, or
through a tunnel to localhost). For CI, see
Testing in CI.
Pages Router
The same client works in pages/api. For webhooks, turn off the body parser
so the signature can be checked against the exact bytes:
import type { NextApiRequest, NextApiResponse } from "next"
import { verifyWebhook, type WebhookEvent } from "@charchy/send"
export const config = { api: { bodyParser: false } }
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const chunks: Buffer[] = []
for await (const chunk of req) chunks.push(chunk as Buffer)
let event: WebhookEvent
try {
event = await verifyWebhook({ payload: Buffer.concat(chunks), headers: req.headers })
} catch {
return res.status(400).send("Invalid signature")
}
await handleCharchyEvent(event)
res.status(204).end()
}