# Send transactional email with Next.js: from request to delivery status

Build a Next.js App Router email flow with a safe local fixture, stable request keys, server-side calls, error handling, and a message status lookup.

Author: Stampwing
Canonical: https://www.stampwing.com/guides/send-email-nextjs
Published: 2026-10-04
Reviewed: 2026-10-05
Category: Engineering

Run the request and status flow locally without an API key or any real delivery.

## Short answer

Section link: https://www.stampwing.com/guides/send-email-nextjs#short-answer

Call your email provider from server-side code, keep a stable identity for each logical send, and save the returned message ID. Treat the initial response as acceptance, then observe delivery separately. Start with a local fixture before introducing a real provider.

## Before you start

Section link: https://www.stampwing.com/guides/send-email-nextjs#before-you-start

For: Developers using the Next.js App Router.

Bring: A local App Router project, Node.js 22+ and two terminals. Match the URL and Origin header.

Scope: The downloaded route works only in development and calls a loopback fixture. It cannot send email.

## Start with the local API fixture

Section link: https://www.stampwing.com/guides/send-email-nextjs#setup

This walkthrough uses the Next.js App Router and standard fetch. The downloadable route is development-only and always calls a loopback fixture. It does not depend on a publicly available Stampwing endpoint. Stampwing remains in early access preparation.

Use Node.js 22 or later and an existing Next.js App Router project. Download the local email API fixture and start it in a separate terminal. It stores simulated messages in memory and never sends email.

Start the fixture

```shell
node email-mock-server.mjs
# Listening on http://127.0.0.1:3027
# Simulated messages; no real delivery
```

[Download email-mock-server.mjs](https://www.stampwing.com/downloads/email-mock-server.mjs)

## Keep the provider call on the server

Section link: https://www.stampwing.com/guides/send-email-nextjs#route

Download next-email-route.ts and place it at app/api/email-example/route.ts, or src/app/api/email-example/route.ts if your project uses a src directory. Start Next.js in development mode.

The route accepts only same-origin local requests, uses a fixed synthetic recipient, validates the operation key, and has a bounded upstream timeout. It intentionally ignores request-body recipient input, so the tutorial cannot become an arbitrary-recipient sending endpoint.

In a real app, authentication and business authorization belong before the send. Derive the recipient from the authorized business action, not from an untrusted form field. Keep provider secrets in server environment variables; never use a NEXT_PUBLIC_ variable for an API key.

The fixture call inside the route

```typescript
const response = await fetch("http://127.0.0.1:3027/api/v1/emails", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Idempotency-Key": key,
  },
  body: JSON.stringify({
    to: "reader@example.test",
    subject: "A local test",
    text: "No email leaves this fixture.",
  }),
  signal: AbortSignal.timeout(5000),
  cache: "no-store",
});
```

## Make the request, then repeat it

Section link: https://www.stampwing.com/guides/send-email-nextjs#request

The command below assumes Next.js is running at localhost:3000. If your port or hostname differs, change both the URL and Origin header to match exactly. Keep the idempotency key unchanged for the repeat request.

You should receive HTTP 202 with an ID, queued status, and demo mode. Running the same command again should return the same ID. A fixed fixture response is evidence of the protocol flow only; it is not a delivery event.

Call your development route

```shell
curl -i http://localhost:3000/api/email-example \
  -X POST \
  -H "Origin: http://localhost:3000" \
  -H "Idempotency-Key: next-example-42"
```

## Look up the accepted message separately

Section link: https://www.stampwing.com/guides/send-email-nextjs#status

Copy the returned ID into the fixture lookup below. The response remains queued because the fixture does not simulate a receiving server. This makes the boundary visible: request acceptance and delivery observation are separate parts of the application.

For a real provider, store the ID with the original business event and update the delivery timeline through authenticated status lookups or verified webhooks. Limit polling and stop when the operation reaches an appropriate terminal or review state.

If you expose a status route in your app, authenticate it and resolve the message through the current user’s authorized business record. An unguessable message ID is not authorization. Return only the fields the page needs, and prevent shared caching of account-specific status responses.

Replace RETURNED_ID with the fixture response ID

```shell
curl http://127.0.0.1:3027/api/v1/emails/RETURNED_ID
```

[Understand the delivery status handoffs](https://www.stampwing.com/guides/email-delivered-but-not-received)

## Make failure visible without losing the operation

Section link: https://www.stampwing.com/guides/send-email-nextjs#errors

Stop the fixture server and repeat the request. The Next.js example returns a service error rather than pretending the email was queued. Restarting the fixture clears its memory; production persistence must survive restarts.

An upstream timeout has an unknown outcome. Keep the same key for recovery. Validation failures, authorization failures, and conflicts require different handling from a temporary connection problem. Do not expose raw provider responses or secrets in a public error.

A production flow should use a durable outbox, bounded retry scheduling, rate limits, and an authenticated action. Those controls are deliberately not implied by a short route-handler tutorial.

| Local result | What to check |
| --- | --- |
| 404 from the example route | The file path must match /api/email-example. The example intentionally returns 404 outside development. |
| 403 | Use localhost or 127.0.0.1 and an Origin header matching the request URL exactly, including the port. |
| 400 | Supply the documented stable Idempotency-Key; the fixture route accepts 1–120 letters, digits, colons, underscores or hyphens. |
| 503 | Check the loopback fixture and keep the original key. The upstream outcome is unknown. |
| 202 with mode: demo | The local request was accepted; no real email was sent. |

## Decide what your route’s success response promises

Section link: https://www.stampwing.com/guides/send-email-nextjs#business-commit-boundary

The downloadable route waits for a local fixture. A production checkout has a different obligation: once it reports an order as saved, the email intent must survive the request ending. Store the order and outbox intent in the same transaction. Let the route return the application operation ID; let the worker attach the provider message ID later.

Do not keep a database transaction open while waiting for an email provider. Locks and connections remain occupied during network delays, and rolling back your database cannot retract an email already accepted remotely. A post-commit queue notification can reduce latency, but a polling worker must still recover committed rows when that notification is lost.

Application flow · pseudocode, not a drop-in Next.js route

```text
authenticate request; authorize the business operation
validate input; derive recipient from owned application data
begin database transaction
  save business change under a stable operation identity
  insert immutable email intent with scoped uniqueness
commit
return operation ID and the last confirmed state

worker: claim intent → submit → persist outcome
ambiguous outcome: reconcile or quarantine
```

Note: A 202 response is your application’s contract, not proof of inbox delivery. If the database connection drops during COMMIT, the commit outcome can also be unknown: reconcile using the same business identity. A browser timeout must not mint a new order or email identity.

[Exercise transaction rollback and worker claims in PostgreSQL](https://www.stampwing.com/guides/prevent-duplicate-emails#outbox-postgres-lab)

[AWS: separate the business transaction from remote dispatch](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html)

## Move to a provider with an explicit integration checklist

Section link: https://www.stampwing.com/guides/send-email-nextjs#connect

If you already have access to a Stampwing workspace, its connection flow supplies the deployment-specific endpoint and a scoped Test credential. This public tutorial makes no assumption about a hosted service URL or availability.

Do not turn the sample into production code by deleting only its development guard. A detached promise or timer is not a durable job. Next.js after() can extend work beyond the response within the deployment’s execution limits, but it does not persist a job across crashes. Commit the business event and outbox before returning success, then let a worker perform recoverable sends.

1. Choose the provider endpoint and documented API contract. Configure its server-side credentials separately for Test and Live.
2. Replace the fixture adapter while retaining the same application event identity and stored payload.
3. Validate authorization, recipient derivation, rate limits, and template rendering in your application.
4. Add signed webhooks or a scoped status lookup and test duplicates before enabling Live delivery.
5. Complete domain authentication and a controlled delivery exercise. Keep production sending out of automated tests.

## Check what changes when the route is deployed

Section link: https://www.stampwing.com/guides/send-email-nextjs#deployment-boundaries

Keep provider keys in server-only configuration. If a job must outlive a request, store it before returning success and let a worker perform the send. The short tutorial route intentionally leaves those application-specific decisions to you.

| Local example | Production responsibility |
| --- | --- |
| Loopback fixture at 127.0.0.1 | Use the provider’s authenticated HTTPS endpoint. Loopback on a host points to that host. |
| Fixed synthetic recipient | Derive the recipient from an authorized operation in your own database. |
| In-memory fixture state | Persist the operation key, content, and returned message ID across restarts. |
| One bounded fetch | Use a durable job for delayed retries; do not depend on work continuing after the response. |
| Development request checks | Enforce your session, authorization, CSRF strategy, and per-operation rate limits. |

[Plan a retry budget without sending email](https://www.stampwing.com/tools/email-retry-calculator)

## Sources

Section link: https://www.stampwing.com/guides/send-email-nextjs#sources

- [Next.js: Route Handlers](https://nextjs.org/docs/app/api-reference/file-conventions/route)
- [Next.js: environment variables](https://nextjs.org/docs/app/guides/environment-variables)
- [Next.js: after() and execution limits](https://nextjs.org/docs/app/api-reference/functions/after)
- [AWS: separate the business transaction from remote dispatch](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html)

Example download: [Download the Next.js route](https://www.stampwing.com/downloads/next-email-route.ts)

## Related guides

- https://www.stampwing.com/guides/test-transactional-email
- https://www.stampwing.com/guides/prevent-duplicate-emails
- https://www.stampwing.com/guides/reliable-email-webhooks
- https://www.stampwing.com/guides/nextjs-contact-form-email
- https://www.stampwing.com/guides/send-email-cloudflare-workers

Editorial policy: https://www.stampwing.com/resources/editorial
