# How to Send Verification and Password Reset Emails in Next.js

Send email verification and password reset links from the Next.js App Router with Sendtern. Test both messages in Email Playground before enabling live delivery.

## 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/`.

```env
APP_ORIGIN=http://localhost:3000
SENDTERN_API_KEY=st_replace_me
SENDTERN_FROM=sandbox@sendtern.test
SENDTERN_MODE=sandbox
SENDTERN_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](https://nextjs.org/docs/app/guides/environment-variables) · [Sendtern quickstart](https://sendtern.com/docs/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.

```ts
import "server-only";

const actions = {
  verify: {
    path: "/verify-email",
    subject: "Confirm your email",
    instruction: "Open this link to confirm your email address.",
  },
  reset: {
    path: "/reset-password",
    subject: "Reset your password",
    instruction: "Open this link to choose a new password.",
  },
} as const;

type AuthEmail = {
  kind: keyof typeof actions;
  to: string;
  token: string;
  eventId: string;
};

export async function sendAuthEmail({ kind, to, token, eventId }: AuthEmail) {
  const { APP_ORIGIN, SENDTERN_API_KEY, SENDTERN_FROM, SENDTERN_MODE } = process.env;
  if (!APP_ORIGIN || !SENDTERN_API_KEY || !SENDTERN_FROM) {
    throw new Error("Set APP_ORIGIN, SENDTERN_API_KEY and SENDTERN_FROM");
  }

  const action = actions[kind];
  const link = new URL(action.path, APP_ORIGIN);
  link.searchParams.set("token", token);
  const endpoint = SENDTERN_MODE === "live" ? "/emails" : "/test/emails";

  const response = await fetch("https://sendtern.com" + endpoint, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${SENDTERN_API_KEY}`,
      "Content-Type": "application/json",
      "Idempotency-Key": `auth-${kind}-${eventId}`,
    },
    body: JSON.stringify({
      from: SENDTERN_FROM,
      to,
      subject: action.subject,
      text: `${action.instruction}\n\n${link}`,
    }),
    signal: AbortSignal.timeout(10_000),
  });

  if (!response.ok) {
    throw Object.assign(new Error(`Sendtern HTTP ${response.status}`), {
      status: response.status,
      retryAfter: response.headers.get("Retry-After"),
    });
  }

  const { id } = await response.json();
  if (typeof id !== "string") throw new Error("Sendtern response is missing an ID");
  return id;
}
```

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](https://sendtern.com/docs/sending).

## 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](https://nextjs.org/docs/app/getting-started/route-handlers).

```ts
import { randomUUID } from "node:crypto";
import { sendAuthEmail } from "../../../../lib/send-auth-email";

export async function POST(request: Request) {
  if (process.env.NODE_ENV !== "development" || process.env.SENDTERN_MODE !== "sandbox") {
    return new Response(null, { status: 404 });
  }

  const input = await request.json().catch(() => null);
  const kind = input?.kind;
  if (kind !== "verify" && kind !== "reset") {
    return Response.json({ error: "Use verify or reset" }, { status: 400 });
  }

  const to = process.env.SENDTERN_TEST_TO;
  if (!to) {
    return Response.json({ error: "Set SENDTERN_TEST_TO" }, { status: 500 });
  }

  const id = await sendAuthEmail({ kind, to, token: "playground-example", eventId: randomUUID() });
  return Response.json({ id }, { status: 201 });
}
```

Start `npm run dev` and run both requests from a Bash-compatible shell. Open Email Playground in the same Sendtern project.

```bash
curl -fsS http://localhost:3000/api/dev/auth-email \
  -H 'Content-Type: application/json' -d '{"kind":"verify"}'

curl -fsS http://localhost:3000/api/dev/auth-email \
  -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 `verify` message 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 `reset` token 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_ORIGIN` and `Referrer-Policy: no-referrer` on production token pages. [OWASP password reset guidance](https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html).

## 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](https://sendtern.com/docs/domains).

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](https://sendtern.com/docs/statuses).
