# Next.js

> Send your first email from a Next.js Route Handler with the official mailblastr SDK.

Send your first email from a Next.js app with the official [`mailblastr`](https://www.mailblastr.com/docs/resources/sdks) SDK. Install it, create a client with your API key, and call `mb.emails.send(...)` from server-side code — a Route Handler, a Server Action, or any API route.

```sh
npm install mailblastr
```

## Prerequisites

Before you start, you will need:

- A MailBlastr [API key](https://www.mailblastr.com/docs/api-keys/overview).
- A [verified domain](https://www.mailblastr.com/docs/domains/managing) to send from.

## 1. Set your API key

Store your API key in an environment variable in your project's `.env.local`. Never hardcode the key in source.

**.env.local**

```sh
MAILBLASTR_API_KEY=mb_xxxxxxxxx
```

## 2. Send an email from a Route Handler

Create a route file under `app/api/send/route.ts` (App Router). It reads the key from `process.env`, sends with the SDK, and returns the created email's `id`.

**App Router**

```ts
// app/api/send/route.ts
import { MailBlastr } from 'mailblastr';

const mb = new MailBlastr(process.env.MAILBLASTR_API_KEY);

export async function POST() {
  const { data, error } = await mb.emails.send({
    from: 'Acme <onboarding@yourdomain.com>',
    to: ['delivered@example.com'],
    subject: 'Hello world',
    html: '<strong>It works!</strong>',
  });

  if (error) return Response.json({ error }, { status: 400 });
  return Response.json(data);
}
```

**Pages Router**

```ts
// pages/api/send.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { MailBlastr } from 'mailblastr';

const mb = new MailBlastr(process.env.MAILBLASTR_API_KEY);

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const { data, error } = await mb.emails.send({
    from: 'Acme <onboarding@yourdomain.com>',
    to: ['delivered@example.com'],
    subject: 'Hello world',
    html: '<strong>It works!</strong>',
  });

  if (error) return res.status(400).json({ error });
  return res.status(200).json(data);
}
```

> **Warning:** Only call the MailBlastr API from server-side code (Route Handlers, Server Actions, API routes). Never ship your API key to the browser.

## 3. Response

A successful send returns the created email's `id`. Retrieve it later with [GET /emails/:id](https://www.mailblastr.com/docs/api/emails-get).

```json
{
  "id": "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"
}
```

> **Note:** See the full request body — `cc`, `bcc`, `reply_to`, `attachments`, `tags`, `scheduled_at` — in the [Send an email](https://www.mailblastr.com/docs/api/emails-send) reference.
