# Next.js

Send a Next.js app's mail with the TypeScript SDK, check each webhook in a route handler, and develop against a test server.

The TypeScript SDK, `@sendora/sdk`, sends a Next.js app's mail from its server code, and a route handler checks each webhook's signature against the raw body. This guide's samples use the App Router, and run on Next.js 15 and 16.

## Before you start

- A [server key](https://sendora.se/docs/keys), which you create on the server's **API keys** tab in the dashboard. A [test server](https://sendora.se/docs/test-servers)'s key works before Sendora approves your account, and it delivers nothing.
- A [verified sending domain](https://sendora.se/docs/domains) for the From address. A test server checks the domain too.

## Install

```sh
npm install @sendora/sdk
```

## Settings

Set the server key and the webhook's secret in `.env.local`. You get the secret once you create the webhook, as [Webhooks](#webhooks) below shows.

```bash
SENDORA_API_TOKEN=sk_…
SENDORA_WEBHOOK_SECRET=whsec_…
```

- `SENDORA_API_TOKEN` is the server key, and `SENDORA_WEBHOOK_SECRET` the webhook's signing secret.
- Next.js reads `.env.local` in development, in `next build` and in `next start`. A new app's `.gitignore` keeps the file out of git. In production, set both variables in the host's environment.
- Next.js keeps both on the server. Never give either the `NEXT_PUBLIC_` prefix, which puts a variable into the JavaScript that browsers load.

Make the client in `lib/sendora.ts`:

```typescript
import 'server-only';
import { Sendora } from '@sendora/sdk';

let client: Sendora | undefined;

// Made at its first use, since next build loads this
// module, often where the key is not set.
export function sendora(): Sendora {
  client ??= new Sendora({
    token: process.env.SENDORA_API_TOKEN,
  });
  return client;
}
```

- The samples import the module as `@/lib/sendora`, through the alias for the app's root that a new app sets up.
- `server-only` fails the build if a Client Component imports the module, so the key stays on the server. Next.js handles the import itself. Install the `server-only` package only if your linter asks for it.
- The SDK throws when the key is missing. `next build` runs the modules that pages import, often where the key is not set. So the client is made at its first use, and the app builds without the key.

## Send mail

Send from server code, such as a Server Action or a route handler. This Server Action, in `app/contact/actions.ts`, sends a contact form's message to your support address:

```typescript
'use server';

import { redirect } from 'next/navigation';
import { sendora } from '@/lib/sendora';

export async function sendMessage(formData: FormData) {
  const email = formData.get('email');
  const message = formData.get('message');
  if (
    typeof email !== 'string' ||
    typeof message !== 'string'
  ) {
    throw new Error(
      'The form sends an address and a message.',
    );
  }

  await sendora().email.send({
    from: {
      email: 'no-reply@example.se',
      name: 'Example AB',
    },
    to: ['support@example.se'],
    headers: { 'Reply-To': email },
    subject: 'A message from the contact form',
    text: message,
    tag: 'contact-form',
  });
  redirect('/contact/sent');
}
```

The form in `app/contact/page.tsx` calls it:

```tsx
import { sendMessage } from './actions';

export default function ContactPage() {
  return (
    <form action={sendMessage}>
      <label>
        Your address
        <input name="email" type="email" required />
      </label>
      <label>
        Message
        <textarea name="message" required />
      </label>
      <button type="submit">Send</button>
    </form>
  );
}
```

- Anyone can post to a Server Action, not only your form. So the action sends to your own address, and takes the visitor's only for `Reply-To`. An action that sends to an address from the form would let anyone mail anyone.
- Sendora refuses a header value that holds a line break, so the visitor's address cannot add a header of its own.
- `send()` returns the accepted message, with Sendora's `messageId`, which the log and the webhooks use.
- The tag sets the form's mail apart in the log and in every webhook. Add [metadata](https://sendora.se/docs/sending#attachments-headers-tags-and-metadata) for ids of your own, such as an order's.
- If Sendora refuses the mail, `send()` throws a `SendoraError` with the [error code](https://sendora.se/docs/errors). Next.js then shows its error page.
- `redirect()` sends the visitor on to `/contact/sent`, a page of your own.

## Webhooks

A route handler checks each delivery's signature, then handles its event. A delivery is one post of one event to your webhook.

1. Add the route handler, `app/api/webhooks/sendora/route.ts`. This one logs a hard bounce, and files each received mail as [Received mail](#received-mail) explains:

```typescript
import { SendoraError } from '@sendora/sdk';
import { sendora } from '@/lib/sendora';
import { fileTicket } from '@/lib/tickets';

export async function POST(request: Request) {
  // receive() checks the signature over the raw body.
  const event = await sendora()
    .webhooks.receive(
      request,
      process.env.SENDORA_WEBHOOK_SECRET,
    )
    .catch((error: unknown) => {
      if (error instanceof SendoraError) {
        return null;
      }
      throw error;
    });
  if (event === null) {
    return new Response(null, { status: 400 });
  }

  if (event.event === 'bounced' && event.details.hard) {
    console.warn(
      'A message bounced for good',
      event.messageId,
    );
  } else if (event.event === 'inbound') {
    await fileTicket(event.inboundMessageId);
  }
  return new Response(null, { status: 204 });
}
```

2. Create a webhook under the server's [Webhooks](https://app.sendora.se/servers) tab, with the address of the route, such as `https://example.se/api/webhooks/sendora`. If the app receives mail, create it through the API instead, as [Received mail](#received-mail) says.
3. Put its secret in `SENDORA_WEBHOOK_SECRET`, and deploy.

The App Router never parses a route handler's body. `receive()` reads the raw body from the request and checks the signature before it parses anything. It returns the event, typed by its name in `event.event`, so `event.details` has that event's fields. [Webhooks](https://sendora.se/docs/webhooks#events) says when Sendora sends each event, and [Webhook events](https://sendora.se/docs/api/webhook-events) lists their fields.

- The route answers 204 once it has handled the event. If it throws, Next.js answers 500, and Sendora delivers the event again later, on the schedule that [Webhooks](https://sendora.se/docs/webhooks#retries-dead-letters-and-replay) gives.
- Sendora waits only as long as [Limits](https://sendora.se/docs/limits#webhooks) says, so queue slow work. Work that you pass to `after()` from `next/server` runs once the answer has gone. Sendora never learns that such work failed, and delivers nothing again.
- A delivery whose signature is missing, wrong or more than five minutes old gets 400, since `receive()` throws a `SendoraError` with `invalid_signature` or `stale_signature`. Without the secret, it throws a `TypeError`, and the route answers 500.
- A delivery can arrive more than once. Key your handling on `event.id`, the delivery's id, which stays the same on each attempt.
- If `proxy.ts`, or `middleware.ts` before Next.js 16, guards every route, leave the webhook's path out of its `matcher`. Sendora counts a redirect as a failure, a redirect to a sign-in page included.
- To [roll the secret](https://sendora.se/docs/webhooks#roll-the-secret), create the new one and set `SENDORA_WEBHOOK_SECRET` to it. Sendora signs each delivery with both until you delete the old one.

## Received mail

The route handler above files each received mail. An `inbound` event has the message's `inboundMessageId`, and `lib/tickets.ts` fetches the mail by it:

```typescript
import { mkdir, writeFile } from 'node:fs/promises';
import { sendora } from '@/lib/sendora';

export async function fileTicket(
  inboundMessageId: string,
) {
  const mail = await sendora().inbound.get(
    inboundMessageId,
  );

  // Only a DMARC pass proves who sent it.
  const folder =
    mail.authentication.dmarc === 'pass'
      ? 'tickets'
      : 'tickets/unverified';
  await mkdir(folder, { recursive: true });
  await writeFile(
    `${folder}/${inboundMessageId}.txt`,
    mail.text ?? '',
  );
}
```

- The route fetches the mail, so create its webhook through the API with `inboundContent` set to `reference`, as in `sendora().webhooks.create({ url, inboundContent: 'reference' })`. A webhook from the dashboard carries the whole mail in each `inbound` event, as [Inbound](https://sendora.se/docs/inbound#the-inbound-event) explains.
- Only a DMARC `pass` proves that the From domain sent the message. With any other verdict, the From address may be forged.
- Sendora keeps the mail's content for the stream's retention, as [Inbound](https://sendora.se/docs/inbound#what-sendora-keeps) says. After that, the route finds its `text` null.
- This sample files the text on the server's disk. On a host without a disk of its own, keep the mail where the app keeps its data.
- A test server has no inbound stream, so receive mail on a live server.

## Develop against a test server

A test server checks and logs each mail as a live server does, and delivers none of it. Its keys start with `sk_test_`.

1. Create a test server under [Servers › New server](https://app.sendora.se/servers/new), with **Testserver** ticked, and a key on its **API keys** tab.
2. Put the key in `SENDORA_API_TOKEN` in `.env.local` on your machine, and in CI. Keep a live server's key in production.
3. Send to the [simulator's addresses](https://sendora.se/docs/test-servers#the-simulators-addresses), such as `hardbounce@simulator.sendora.se`, to act out a bounce or a complaint. The message's events show in the dashboard's message log, as [Messages and events](https://sendora.se/docs/messages) explains.

Then refuse a test key where mail must arrive. Next.js calls `register()` in `instrumentation.ts`, in the app's root beside `app/`, once as the server starts:

```typescript
import { isTestKey } from '@sendora/sdk';

// Next.js calls register() once as the server starts.
export function register() {
  const token = process.env.SENDORA_API_TOKEN ?? '';
  if (
    process.env.NODE_ENV === 'production' &&
    isTestKey(token)
  ) {
    throw new Error(
      'SENDORA_API_TOKEN is a test key; ' +
        'nothing would be delivered',
    );
  }
}
```

With a test key in production, the server then answers every request with 500, and its log says why. `next start` runs in production mode wherever it runs, on a staging server too. So if staging sends with a test key, base the check on a variable that you set in production alone, such as `APP_ENV=production`.

Sendora posts webhooks only to a public HTTPS address, so a test server's events cannot reach your machine. Post a signed delivery to the route yourself instead. With `npm run dev` running, `scripts/try-webhook.mts` posts a hard bounce, signed as [Verify the signature](https://sendora.se/docs/webhooks#verify-the-signature) describes:

```typescript
import { createHmac, randomUUID } from 'node:crypto';

const body = JSON.stringify({
  id: randomUUID(),
  attempt: 1,
  event: 'bounced',
  messageId: randomUUID(),
  recipient: 'hardbounce@simulator.sendora.se',
  occurredAt: new Date().toISOString(),
  serverId: randomUUID(),
  streamId: randomUUID(),
  broadcastId: null,
  tag: 'contact-form',
  metadata: {},
  test: true,
  details: {
    code: 550,
    response: '5.1.1 No such user',
    classification: 'InvalidRecipient',
    hard: true,
    expired: false,
  },
});

// Signed as Sendora signs each delivery.
const secret = process.env.SENDORA_WEBHOOK_SECRET ?? '';
const t = String(Math.floor(Date.now() / 1000));
const v1 = createHmac('sha256', secret)
  .update(`${t}.${body}`)
  .digest('hex');

const response = await fetch(
  'http://localhost:3000/api/webhooks/sendora',
  {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'sendora-signature': `t=${t},v1=${v1}`,
    },
    body,
  },
);
console.log(response.status);
```

Run it with `node --env-file=.env.local scripts/try-webhook.mts`, on Node 22.18 or newer. It prints 204 once the route has taken the delivery, and the dev server logs the bounce. The script and the route both read the secret from `.env.local`, so any value there works on your machine.
