Send email from Next.js

Send email from a Next.js App Router route handler or server action with the coss SDK, then render React Email and follow delivery with webhooks.

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

Install the SDK:

npm install coss

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

.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).

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:

lib/coss.ts
import {  } from "coss";

export const  = new ();

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).

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, 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

app/api/welcome/route.ts
import {  } from "coss";

const  = new ();

export async function (: ) {
  const { ,  } = (await .()) as { : string; : string };

  const { ,  } = await ..({
    : "Acme <hello@acme.com>",
    : ,
    : "Welcome to Acme",
    : `Hi ${}, thanks for signing up.`,
  });

  if () {
    .(., ., .);
    return .({ : "Could not send the email" }, { : 502 });
  }

  return .({ : ., : . });
}

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

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

app/contact/actions.ts
"use server";

import {  } from "coss";

const  = new ();

export type  = { : boolean; : string } | null;

export async function (
  : ,
  : ,
): <> {
  const  = (.("email"));
  const  = (.("message"));

  const {  } = await ..({
    : "Acme website <website@acme.com>",
    : "support@acme.com",
    : ,
    : `Message from ${}`,
    : ,
  });

  if () return { : false, : "Your message couldn't be sent. Try again." };
  return { : true, : "Thanks, we'll be in touch." };
}
app/contact/contact-form.tsx
"use client";

import {  } from "react";

export function () {
  const [, , ] = (, null);

  return (
    < ={}>
      < ="email" ="email"  />
      < ="message"  />
      < ="submit" ={}>Send</>
      { && <>{.}</>}
    </>
  );
}

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:

const { ,  } = await ..({
  : "Acme <hello@acme.com>",
  : "ada@example.com",
  : "Your receipt",
  : "Thanks for your order.",
});

if (?. === "validation_error") {
  for (const  of . ?? []) .(., .);
} else if () {
  .(., ., .);
}

The SDK already retries network errors, timeouts, 409, 429 and 5xx responses. See errors and retries for every error type.

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.

await ..(
  {
    : "Acme <orders@acme.com>",
    : .,
    : `Order ${.} confirmed`,
    : "<p>Your order is confirmed.</p>",
  },
  { : `order-confirmation-${.}` },
);

Send React Email components

Pass a 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:

npm install @react-email/render
app/api/welcome/route.tsx
const { ,  } = await ..({
  : "Acme <hello@acme.com>",
  : "ada@example.com",
  : "Welcome to Acme",
  : < ="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 with template_id and variables.

Follow delivery with webhooks

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

app/api/webhooks/coss/route.ts
import { ,  } from "coss";

export async function (: ) {
  try {
    const  = await (
      await .(),
      .,
      ..!,
    );

    if (. === "email.bounced") {
      .("Bounced:", ..);
    }
    return new ("ok");
  } catch () {
    if ( instanceof ) {
      return new ("invalid signature", { : 400 });
    }
    throw ;
  }
}

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).

Next steps

Last updated