Send with your stack

Send emails with Next.js

Send email from a Next.js Route Handler or Server Action using the mailblastr SDK — your API key stays on the server.

In Next.js you should call MailBlastr from server-only code — a Route Handler (app/api/.../route.ts) or a Server Action — never from a Client Component. That keeps your mb_ API key out of the browser bundle.

Install the SDK (npm install mailblastr) and import it in your server files. This guide adds a POST /api/send Route Handler and shows the equivalent Server Action.

Prerequisites

  1. A verified domain for your from address. (guide)
  2. An API key stored as an environment variable (e.g. MAILBLASTR_API_KEY in .env.local). (Authentication)
  3. A Next.js 13.4+ App Router project (Route Handlers / Server Actions) and npm install mailblastr.

Route Handler

Create app/api/send/route.ts. Because the file runs only on the server, process.env.MAILBLASTR_API_KEY is never exposed to the client.

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 <hello@yourdomain.com>',
    to: ['delivered@example.com'],
    subject: 'Hello from Next.js',
    html: '<p>Sent from a Route Handler.</p>',
  });

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

  return Response.json(data);
}

Or a Server Action

If you are submitting a form, a Server Action keeps the key server-side too. The 'use server' directive guarantees the function never ships to the client.

app/actions.ts
'use server';

import { MailBlastr } from 'mailblastr';

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

export async function sendEmail(formData: FormData) {
  const { data, error } = await mb.emails.send({
    from: 'Acme <hello@yourdomain.com>',
    to: [String(formData.get('email'))],
    subject: 'Thanks for signing up',
    html: '<p>Welcome aboard!</p>',
  });

  if (error) {
    throw new Error(error.message);
  }

  return data.id;
}

Handling the response

Every SDK call returns { data, error }. On success data.id is the created email's ID; on failure error is set and data is null. The examples above relay a clean error to the client without leaking the key. Use the id to retrieve the email or correlate webhook events.

Only reference MAILBLASTR_API_KEY in server files (Route Handlers, Server Actions, getServerSideProps). Never prefix it with NEXT_PUBLIC_ and never read it in a Client Component — that would inline the secret into the browser bundle.

Next steps