# Send Email with Next.js: App Router Tutorial

> Send email with Next.js from Route Handlers and Server Actions with an email API: a server-side key, contact forms, templates and safe retries on Vercel.

Canonical: https://www.cresca.xyz/blog/send-email-nextjs
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

In the App Router, the place to **send email with Next.js** is server code: a Route Handler or a Server Action. Both run on the server, so the API key never ends up in the browser bundle. With Cresca the send itself is one `fetch` to `https://api.cresca.xyz/api/v1/emails`; you get an email id back and Cresca delivers from your verified domain within seconds. This guide builds a server-only client in `lib/`, a contact form endpoint, an invite flow with a Server Action, template-based emails and the environment setup for Vercel.

**TL;DR**

- Name the variable `CRESCA_API_KEY`. A `NEXT_PUBLIC_` prefix would put it in the client bundle.
- Import `server-only` at the top of the client module so no client component can pull it in.
- Put what visitors type into `text` or template variables, never into raw HTML.
- Pass an `Idempotency-Key` for any send a retry could duplicate.

## Before you start

- A Next.js 14 or later project on the App Router. The code is plain JavaScript and works unchanged in TypeScript files.
- A verified domain on [Sending Domains](https://app.cresca.xyz/sending-domains), an active sender on it such as `hello@acme.com`, and a *Sending access* key from [API keys](https://app.cresca.xyz/api-keys). That key type can send but cannot read logs or edit templates, which is all a web app should hold. The [email API quickstart](https://www.cresca.xyz/docs/quickstart) covers the DNS records and every step in the dashboard.
- The `server-only` package: `npm install server-only`.

## Keep the API key on the server

Next.js inlines every variable whose name starts with `NEXT_PUBLIC_` into the JavaScript it sends to browsers. Other variables in `process.env` are only readable on the server. So the key goes in `.env.local` under a plain name. It starts with `cr_live_` and Cresca shows it only once, so paste it in right away:

```bash
# .env.local (never commit this file)
CRESCA_API_KEY=cr_live_xxxxxxxxx
```

Next.js loads `.env.local` automatically during development, and the `.gitignore` that `create-next-app` generates already excludes it.

## Send email with Next.js: a server-only client

`lib/cresca.js` is the one module that talks to Cresca. Route Handlers and Server Actions import it. Client components cannot, because the `import 'server-only'` line turns that mistake into a build error instead of a leaked key. Besides the request itself, it handles:

- **Idempotency.** With an `Idempotency-Key`, a retried request returns the first result instead of sending again, even if the first response never reached your function. Keys live for 24 hours. Build them from your data, for example `team-invite/` plus the invite id, not from `Date.now()` or a random UUID. More in [idempotency](https://www.cresca.xyz/docs/idempotency).
- **Retries for temporary failures only.** Network errors, the 10-second timeout, `429 rate_limit_exceeded`, `409 concurrent_idempotent_requests` and 5xx responses are retried with exponential backoff, or after `retry-after` when Cresca sends that header. Other 4xx responses are thrown immediately, because repeating them changes nothing.
- **A typed error.** Failures become a `CrescaError` with `status` and `code`, where `code` is the API's stable error `name`, such as `validation_error`. Check the code, not the message text, which can be reworded.

```js
// lib/cresca.js: server-only client for the Cresca email API.
import 'server-only';

const API_URL = 'https://api.cresca.xyz/api/v1';
const ATTEMPTS = 3;

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const backoff = (attempt) => 2 ** (attempt - 1) * 1000 + Math.random() * 250;

export class CrescaError extends Error {
  constructor(status, name, message) {
    super(`${status} ${name}: ${message}`);
    this.status = status;
    this.code = name;
  }
}

export async function cresca(path, payload, { idempotencyKey } = {}) {
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(API_URL + path, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.CRESCA_API_KEY}`,
          'Content-Type': 'application/json',
          ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),
        },
        body: JSON.stringify(payload),
        cache: 'no-store',
        signal: AbortSignal.timeout(10_000),
      });
    } catch (err) {
      if (attempt === ATTEMPTS) throw err;
      await sleep(backoff(attempt));
      continue;
    }

    const body = await res.json().catch(() => ({}));
    if (res.ok) return body;

    const name = body.name ?? 'unknown_error';
    const retryable =
      res.status >= 500 ||
      (res.status === 429 && name !== 'monthly_quota_exceeded') ||
      name === 'concurrent_idempotent_requests';
    if (!retryable || attempt === ATTEMPTS) {
      throw new CrescaError(res.status, name, body.message ?? res.statusText);
    }
    const retryAfter = Number(res.headers.get('retry-after'));
    await sleep(retryAfter > 0 ? retryAfter * 1000 : backoff(attempt));
  }
}
```

Two choices here are specific to Next.js. `ATTEMPTS` is 3 because serverless functions have an execution time limit and every backoff eats into it; if an email must keep retrying for minutes, hand it to a queue. And `cache: 'no-store'` makes sure Next.js never caches this request.

## A contact form Route Handler

A form posts JSON to `/api/contact`. The handler validates it, emails your team and answers the browser:

```js
// app/api/contact/route.js
import { NextResponse } from 'next/server';
import { cresca, CrescaError } from '@/lib/cresca';

export async function POST(request) {
  const { email, message } = await request.json();
  if (typeof email !== 'string' || !email.includes('@') ||
      typeof message !== 'string' || message.length === 0 || message.length > 5000) {
    return NextResponse.json({ error: 'Please enter an email and a message.' }, { status: 400 });
  }

  try {
    await cresca('/emails', {
      from: 'Acme Website <website@acme.com>',
      to: 'team@acme.com',
      reply_to: email,
      subject: 'New contact form message',
      text: `From: ${email}\n\n${message}`,
    });
  } catch (err) {
    console.error('Contact email failed', err instanceof CrescaError ? err.code : err);
    return NextResponse.json({ error: 'Could not send your message.' }, { status: 502 });
  }

  return NextResponse.json({ ok: true });
}
```

What to copy into your own handlers:

- The visitor's address goes in `reply_to`. `from` has to be your own verified sender, and with `reply_to` set, your team can hit Reply and reach the visitor.
- The message goes out as `text`, so nothing a visitor types is ever rendered as HTML.
- A Cresca failure becomes a 502 with a readable message for the visitor, while the error code goes to your logs.
- Public forms attract bots. Put a rate limit or a CAPTCHA in front so they cannot spend your email allowance.

## Send email from a Server Action

For a form inside your app, a Server Action saves you the API route. It imports the same client. Keep in mind that every Server Action can be called as a public POST endpoint, so it has to check the session itself, as `sendInvite` does first:

```js
// app/invite/actions.js
'use server';

import { cresca } from '@/lib/cresca';
import { getCurrentUser, createInvite } from '@/lib/auth'; // your own code

export async function sendInvite(formData) {
  const user = await getCurrentUser();
  if (!user) throw new Error('Not signed in');

  const invite = await createInvite(user, String(formData.get('email')));

  await cresca(
    '/emails',
    {
      to: invite.email,
      template: {
        id: 'team-invite',
        variables: { INVITER: user.name, ACCEPT_LINK: invite.url },
      },
    },
    { idempotencyKey: `team-invite/${invite.id}` },
  );

  return { ok: true };
}
```

The page hands the action straight to the form's `action` prop, with no client-side fetch code:

```jsx
// app/invite/page.jsx
import { sendInvite } from './actions';

export default function InvitePage() {
  return (
    <form action={sendInvite}>
      <input name="email" type="email" required />
      <button type="submit">Send invite</button>
    </form>
  );
}
```

The idempotency key is tied to the invite id, so a retry of this send cannot deliver the same invite twice. A double-click still runs `createInvite` twice and creates two invites, so deduplicate there if that matters to you.

## Templates instead of email markup in JSX

The invite above sends no HTML at all. It names the `team-invite` template and passes `INVITER` and `ACCEPT_LINK`. The template lives in Cresca's editor, with the dynamic parts marked in triple braces such as `{{{ACCEPT_LINK}}}`, so a designer or marketer can change the email and publish it without a deploy. How templates behave (details in [templates and variables](https://www.cresca.xyz/docs/templates)):

- Only the *published* version is sent, so drafts are safe to edit.
- Values are HTML-escaped, so a user's name cannot inject markup.
- A variable with no value and no fallback fails the request with `422 validation_error`, and the message names it.

If your emails are already React components, keep them: render the component to an HTML string on the server and send that string as `html`.

## File uploads as attachments, and batches

When a form uploads a file, read it in the Route Handler with `request.formData()`, call `await file.arrayBuffer()`, and encode the bytes with `Buffer.from(bytes).toString("base64")`. That string is the attachment's `content`, next to `filename` and an optional `content_type`. Cresca accepts up to 20 attachments and 7 MB in total per email, refuses executable types such as .exe and .js, and cannot fetch attachments by URL yet. An inline image needs a `content_id` and `<img src="cid:logo">` in the HTML. Keep uploads small: the whole request body is limited to 10 MB.

For many recipients, `POST /emails/batch` takes an array of up to 100 emails. Items accept the same fields as a single send except `attachments` and `scheduled_at`. The batch is validated as a whole: one bad item and nothing is sent, with the error naming that item's zero-based index. On success you get `{"data": [{"id": "..."}, ...]}` in your order, and the batch counts as a single request against your rate limit. Do not run batches inside a page request. Use a background job or a scheduled function that calls `cresca("/emails/batch", chunk, ...)` once per 100 emails, with a separate key for each chunk.

## Deploying on Vercel

- Add `CRESCA_API_KEY` in the project settings under Environment Variables, for Production, and for Preview if preview deployments should send real email. New values only apply to new deployments, so redeploy afterwards.
- Give each environment its own sending-access key. If a preview key leaks, you revoke it without touching production.
- A `POST` Route Handler runs on every request and never at build time, so one form submission sends one email.
- The client only uses `fetch`, so it runs in both the Node.js and the Edge runtime.

## Errors to handle when you send email with Next.js

Where an error shows up depends on where you call the client. In a Route Handler you catch it and return a status, as the contact form does. In a Server Action, an uncaught error goes to the nearest `error.js` boundary, and production builds hide its message from the browser, so return a result such as `{ ok: false }` for failures the user should see. The common codes are below; the [errors page](https://www.cresca.xyz/docs/errors) has the full list.

| Status | code | Meaning | Retried by lib/cresca.js? |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | The `from` in your code or template is not an active sender on a verified domain. | No |
| 422 | `validation_error` | A field is invalid or a template variable is missing. | No |
| 422 | `missing_required_field` | No `to`, `from` or `subject`, and no template providing them. | No |
| 429 | `rate_limit_exceeded` | Your plan's requests per second are used up for now. | Yes, after `retry-after` |
| 429 | `monthly_quota_exceeded` | The monthly email allowance is used up. | No |
| 409 | `concurrent_idempotent_requests` | A request with the same key is still in progress. | Yes |
| 5xx | `application_error` | A problem on Cresca's side. | Yes, with backoff |

With three attempts, an error that is still there on the third try is thrown. Suppressed recipients (earlier hard bounces, complaints and unsubscribes) are skipped quietly and the request still returns success; see [suppression](https://www.cresca.xyz/docs/suppression).

## Confirm delivery after the 200

The `200` your Route Handler sees means Cresca accepted the email. Delivery shows up afterwards, in the app under [Transactional](https://app.cresca.xyz/transactional), or through the API with a full-access key. Your deployed app does not need that key; the sending-access key cannot read emails anyway.

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

`last_event` goes from `queued` to `sent`, then to `delivered` or `bounced`. The other statuses are in [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle).

## Frequently asked questions

### Can I use NEXT\_PUBLIC\_CRESCA\_API\_KEY?

No. The prefix tells Next.js to embed the value in the browser bundle, where anyone can read it and send email from your domain. Use `CRESCA_API_KEY` and read it only in Route Handlers, Server Actions or other modules that import `server-only`.

### Does this work with the Pages Router?

Yes. Call `cresca()` from an API route under `pages/api` and read the body from `req.body`. Drop the `import 'server-only'` line in that case, since the package is meant for the App Router. Key handling and retry rules stay the same.

### Can I use React Email with Cresca?

Yes. Render the React Email component to an HTML string on the server and send it as `html`. The alternative is a Cresca template, where your Next.js code sends only the alias and the variables.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

Outside Next.js, the [send email API guide](https://www.cresca.xyz/blog/send-email-api) has every field of the Emails API with cURL examples, the [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) explains the bigger picture, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) compares the two ways to send.

## Start sending

Add the key to `.env.local`, copy `lib/cresca.js`, and your first Route Handler can send within minutes. Cresca is free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. **[Sign up](https://app.cresca.xyz/signup)**, then follow the [quickstart](https://www.cresca.xyz/docs/quickstart) or read the [API docs](https://www.cresca.xyz/docs).
