Set up a sending key for your Next.js server
Create a sending-only key in your Sendtern project. Put these values in .env.local in the Next.js project root. The example assumes app/ and lib/ are siblings. In a project with src/app/, place both under src/.
1APP_ORIGIN=http://localhost:3000
2SENDTERN_API_KEY=st_replace_me
3SENDTERN_FROM=sandbox@sendtern.test
4SENDTERN_MODE=sandbox
5SENDTERN_TEST_TO=mailbox@example.com
Set SENDTERN_API_KEY to your project key. sandbox@sendtern.test works with an unrestricted sending key in Email Playground. If your key is restricted to a verified domain, use a From address on that exact domain in sandbox too. Keep the key on the server and restart next dev after changing the environment. Next.js environment variables · Sendtern quickstart.
Use one server-side function for both emails
Run npm install server-only and save this function as lib/send-auth-email.ts. Pass the recipient, the auth token your application has issued, and an event ID from your database or job queue. The function builds the link from the origin you control and sends a plain-text message through Sendtern.
1import "server-only";
2
3const actions = {
4 verify: {
5 path: "/verify-email",
6 subject: "Confirm your email",
7 instruction: "Open this link to confirm your email address.",
8 },
9 reset: {
10 path: "/reset-password",
11 subject: "Reset your password",
12 instruction: "Open this link to choose a new password.",
13 },
14} as const;
15
16type AuthEmail = {
17 kind: keyof typeof actions;
18 to: string;
19 token: string;
20 eventId: string;
21};
22
23export async function sendAuthEmail({ kind, to, token, eventId }: AuthEmail) {
24 const { APP_ORIGIN, SENDTERN_API_KEY, SENDTERN_FROM, SENDTERN_MODE } = process.env;
25 if (!APP_ORIGIN || !SENDTERN_API_KEY || !SENDTERN_FROM) {
26 throw new Error("Set APP_ORIGIN, SENDTERN_API_KEY and SENDTERN_FROM");
27 }
28
29 const action = actions[kind];
30 const link = new URL(action.path, APP_ORIGIN);
31 link.searchParams.set("token", token);
32 const endpoint = SENDTERN_MODE === "live" ? "/emails" : "/test/emails";
33
34 const response = await fetch("https://sendtern.com" + endpoint, {
35 method: "POST",
36 headers: {
37 Authorization: `Bearer ${SENDTERN_API_KEY}`,
38 "Content-Type": "application/json",
39 "Idempotency-Key": `auth-${kind}-${eventId}`,
40 },
41 body: JSON.stringify({
42 from: SENDTERN_FROM,
43 to,
44 subject: action.subject,
45 text: `${action.instruction}\n\n${link}`,
46 }),
47 signal: AbortSignal.timeout(10_000),
48 });
49
50 if (!response.ok) {
51 throw Object.assign(new Error(`Sendtern HTTP ${response.status}`), {
52 status: response.status,
53 retryAfter: response.headers.get("Retry-After"),
54 });
55 }
56
57 const { id } = await response.json();
58 if (typeof id !== "string") throw new Error("Sendtern response is missing an ID");
59 return id;
60}
With SENDTERN_MODE=sandbox, this calls POST /test/emails. Setting the mode to live switches to POST /emails. The returned ID identifies the stored email. Use it to find the message in Email Playground or in the live delivery log. Sendtern sending API.
Test both messages in Email Playground
Add app/api/dev/auth-email/route.ts. The Route Handler runs only with next dev in sandbox mode and uses a fixed recipient from the environment. The sample token lets you inspect the link before wiring up the account flow. Next.js Route Handlers.
1import { randomUUID } from "node:crypto";
2import { sendAuthEmail } from "../../../../lib/send-auth-email";
3
4export async function POST(request: Request) {
5 if (process.env.NODE_ENV !== "development" || process.env.SENDTERN_MODE !== "sandbox") {
6 return new Response(null, { status: 404 });
7 }
8
9 const input = await request.json().catch(() => null);
10 const kind = input?.kind;
11 if (kind !== "verify" && kind !== "reset") {
12 return Response.json({ error: "Use verify or reset" }, { status: 400 });
13 }
14
15 const to = process.env.SENDTERN_TEST_TO;
16 if (!to) {
17 return Response.json({ error: "Set SENDTERN_TEST_TO" }, { status: 500 });
18 }
19
20 const id = await sendAuthEmail({ kind, to, token: "playground-example", eventId: randomUUID() });
21 return Response.json({ id }, { status: 201 });
22}
Start npm run dev and run both requests from a Bash-compatible shell. Open Email Playground in the same Sendtern project.
1curl -fsS http://localhost:3000/api/dev/auth-email \
2 -H 'Content-Type: application/json' -d '{"kind":"verify"}'
3
4curl -fsS http://localhost:3000/api/dev/auth-email \
5 -H 'Content-Type: application/json' -d '{"kind":"reset"}'
Use the returned IDs to open both captures. Check the From address, recipient, subject, and the expected /verify-email or /reset-password path with its token query parameter. Sandbox captures messages without outbound SMTP. A real click-through test uses links issued by your authentication code.
Connect email to registration and password reset
- After creating the pending account, issue a verification token tied to the user and intended email. Queue a
verifymessage with the event ID. When the user opens the link, show a confirmation action. Consume the token atomically with the update that verifies the address after that action. Mail scanners can then open the URL with a GET request safely. - For password reset, rate-limit requests per account and requester. Give existing and unknown accounts the same public response and keep response times comparable. For an eligible account, issue a
resettoken and queue the message to the address from the account record. On submission, update the password and consume the token atomically. Revoke existing sessions as appropriate. - Generate random, time-limited, single-use tokens per purpose. Store token hashes in the auth database and keep raw tokens out of logs and analytics. Use a trusted HTTPS
APP_ORIGINandReferrer-Policy: no-referreron production token pages. OWASP password reset guidance.
Retry a failed send without a duplicate email
If the request times out, Sendtern may already have saved the message. Retry temporary failures with backoff and the original eventId, sender, recipient, subject, and link. Honor Retry-After when present. Sendtern returns the original email ID for the same request and key within 24 hours. Changing the payload under the same key returns 409.
Persist one event ID and message payload per send, ideally in an outbox written with the account change. Encrypt queued payloads that contain raw tokens and purge them promptly. When a user requests a fresh link, issue a new token and event ID and invalidate the previous link. For a 401, 403, or 422, correct the key, sender, or payload before retrying.
Enable live delivery and check the first messages
Add your sending domain in Sendtern and publish the DNS records shown in the dashboard. Verify the domain, then set SENDTERN_FROM to an address on it, APP_ORIGIN to your public HTTPS URL, and SENDTERN_MODE=live in your deployment environment. Domain setup.
Run registration and password reset with an address you control. Look up both email IDs in Sendtern and complete each flow in your app. delivered records the recipient mail server's SMTP acceptance. Check the actual mailbox for folder placement. For a delay or bounce, open the timeline and read the SMTP response. Delivery statuses.
