# Send email from Next.js (/docs/guides/send-email-nextjs)

The `coss` SDK runs in a Next.js server: route handlers, server actions and other server code. It
has zero dependencies and returns `{ data, error }` instead of throwing.

## Set up the project [#set-up-the-project]

Install the SDK:

```package-install
coss
```

Create an API key in the dashboard, in your project's **Development** environment, and put it in
`.env.local`:

```sh title=".env.local"
COSS_API_KEY=coss_test_...
```

Or run `npx coss-cli init` in the project: it approves a development key in the dashboard, writes it
to `.env.local` and installs the SDK ([CLI](/docs/cli#set-a-project-up)).

`new Coss()` reads `COSS_API_KEY` from the environment. Keep every call in server code: the key is
a secret, and the SDK refuses to run where a `document` global exists. Create one client and import
it wherever you send:

```ts twoslash title="lib/coss.ts"
import { Coss } from "coss";

export const coss = new Coss();
```

## Development and production keys [#development-and-production-keys]

Keys from the **Development** environment start with `coss_test_`. Emails sent with them are
recorded but never delivered, and they accept any `from` address. Sending to
`bounce@simulator.amazonses.com` simulates a bounce, so you can test failure handling
([sandbox behaviour](/docs/environments#sandbox-behaviour)).

Keys from the **Production** environment start with `coss_live_` and deliver real email, but only
from a domain your organization has verified. [Add your domain](/docs/email/domains), publish the
DNS records it lists, and wait for it to verify before you switch keys. A live send from any other
domain returns a `domain_not_verified` error.

## Send an email from a route handler [#send-an-email-from-a-route-handler]

```ts twoslash title="app/api/welcome/route.ts"
import { Coss } from "coss";

const coss = new Coss();

export async function POST(request: Request) {
  const { email, name } = (await request.json()) as { email: string; name: string };

  const { data, error } = await coss.email.send({
    from: "Acme <hello@acme.com>",
    to: email,
    subject: "Welcome to Acme",
    text: `Hi ${name}, thanks for signing up.`,
  });

  if (error) {
    console.error(error.code, error.message, error.request_id);
    return Response.json({ error: "Could not send the email" }, { status: 502 });
  }

  return Response.json({ id: data.id, status: data.status });
}
```

The send returns at once with `status: "queued"`: coss.com hands the email to the delivery
provider moments later. If you build `html` from what a user typed, escape it first.

## Send an email from a server action [#send-an-email-from-a-server-action]

A server action can send straight from a form, with no API route:

```ts twoslash title="app/contact/actions.ts"
"use server";

import { Coss } from "coss";

const coss = new Coss();

export type ContactState = { ok: boolean; message: string } | null;

export async function sendContactMessage(
  _prev: ContactState,
  formData: FormData,
): Promise<ContactState> {
  const email = String(formData.get("email"));
  const message = String(formData.get("message"));

  const { error } = await coss.email.send({
    from: "Acme website <website@acme.com>",
    to: "support@acme.com",
    reply_to: email,
    subject: `Message from ${email}`,
    text: message,
  });

  if (error) return { ok: false, message: "Your message couldn't be sent. Try again." };
  return { ok: true, message: "Thanks, we'll be in touch." };
}
```

```tsx twoslash title="app/contact/contact-form.tsx"
type ContactState = { ok: boolean; message: string } | null;
declare function sendContactMessage(prev: ContactState, formData: FormData): Promise<ContactState>;
// ---cut---
"use client";

import { useActionState } from "react";

export function ContactForm() {
  const [state, action, pending] = useActionState(sendContactMessage, null);

  return (
    <form action={action}>
      <input name="email" type="email" required />
      <textarea name="message" required />
      <button type="submit" disabled={pending}>Send</button>
      {state && <p>{state.message}</p>}
    </form>
  );
}
```

## Handle errors [#handle-errors]

Every SDK method returns `{ data, error }` and never throws for API or network failures. Checking
`error` narrows `data`. `error.code` says what went wrong, and `error.issues` lists invalid fields of
a `validation_error`:

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
// ---cut---
const { data, error } = await coss.email.send({
  from: "Acme <hello@acme.com>",
  to: "ada@example.com",
  subject: "Your receipt",
  text: "Thanks for your order.",
});

if (error?.code === "validation_error") {
  for (const issue of error.issues ?? []) console.log(issue.path, issue.message);
} else if (error) {
  console.error(error.type, error.code, error.request_id);
}
```

The SDK already retries network errors, timeouts, `409`, `429` and `5xx` responses. See
[errors and retries](/docs/sdk/errors) for every error type.

## Send without duplicates [#send-without-duplicates]

Each send carries an idempotency key, which the SDK reuses across its own retries. Pass your own
to make a resubmitted form or a retried job safe too: for 24 hours, a request with the same key
returns the original email instead of sending another.

```ts twoslash
import { Coss } from "coss";
const coss = new Coss();
declare const order: { id: string; email: string };
// ---cut---
await coss.email.send(
  {
    from: "Acme <orders@acme.com>",
    to: order.email,
    subject: `Order ${order.id} confirmed`,
    html: "<p>Your order is confirmed.</p>",
  },
  { idempotencyKey: `order-confirmation-${order.id}` },
);
```

## Send React Email components [#send-react-email-components]

Pass a [React Email](https://react.email) component as `react` instead of `html`. The SDK renders
it into HTML and plain text with `@react-email/render`, an optional peer dependency:

```package-install
@react-email/render
```

```tsx twoslash title="app/api/welcome/route.tsx"
import type { ReactElement } from "react";
import { Coss } from "coss";
const coss = new Coss();
declare function WelcomeEmail(props: { name: string }): ReactElement;
// ---cut---
const { data, error } = await coss.email.send({
  from: "Acme <hello@acme.com>",
  to: "ada@example.com",
  subject: "Welcome to Acme",
  react: <WelcomeEmail name="Ada" />,
});
```

Rendering happens in your server, before the request. `react` can't be combined with `html`, and a
missing renderer returns a `react_renderer_missing` error without sending. To keep content out of
your code instead, send a [template](/docs/email/templates) with `template_id` and `variables`.

## Follow delivery with webhooks [#follow-delivery-with-webhooks]

Each recipient has its own delivery status. Rather than polling `coss.email.get()`, add a
[webhook endpoint](/docs/webhooks) and handle the events in a route handler. Verify every request
with its endpoint's `whsec_…` secret:

```ts twoslash title="app/api/webhooks/coss/route.ts"
import { verifyWebhook, WebhookVerificationError } from "coss";

export async function POST(request: Request) {
  try {
    const event = await verifyWebhook(
      await request.text(),
      request.headers,
      process.env.COSS_WEBHOOK_SECRET!,
    );

    if (event.type === "email.bounced") {
      console.log("Bounced:", event.data.recipient);
    }
    return new Response("ok");
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return new Response("invalid signature", { status: 400 });
    }
    throw error;
  }
}
```

Pass the raw body from `request.text()`, not parsed JSON. coss.com can't reach `localhost`, so
during development run `coss listen --forward-to localhost:3000/api/webhooks/coss`: it forwards
the environment's events to your server and saves a `COSS_WEBHOOK_SECRET` in `.env.local`
([receive webhooks locally](/docs/cli#receive-webhooks-locally)).

## Next steps [#next-steps]

- [Sending email](/docs/email/sending): attachments, scheduled sends, batches, tags and categories
- [Verify a domain](/docs/email/domains) before you send live
- [Delivery status](/docs/email/delivery): what each email and recipient status means
- [Verifying webhooks](/docs/sdk/webhooks) and the [event types](/docs/webhooks#events)
- [Send email with Node.js](/docs/guides/send-email-nodejs)
