# Send a welcome email from a Next.js app

> Send a welcome email from Next.js using the @vibiz/app SDK and one server-side API call, with aligned DKIM, SPF, and DMARC out of the box.

**To send a welcome email from a Next.js app, add the email resource to your project and call `vibiz.email.send()` from a server action or route handler using `@vibiz/app`.** thelastapi provides an aligned sending domain automatically, so you can deliver welcome emails immediately without configuring custom DNS records first. If you prefer to send from your company domain, you can verify your DNS records and route replies directly to your mailbox.

Here is how to set up the email resource, write the Next.js server code, handle errors, and decide between a single transactional email and an automated welcome sequence.

## Adding the email resource to your project

Every project on thelastapi can include an email resource. This gives your project a dedicated mail domain at `<slug>.vibiz.app` where DKIM, SPF, and DMARC authentication records are already aligned.

If you are initializing a new project:

```bash
vibiz init acme-app --resources email
```

If you already have a project running, add email directly:

```bash
vibiz add email
```

The domain status starts as `pending` and switches to `verified` within a few minutes. Any sending attempt made while the domain is still verifying returns a `409 dependency_not_ready` error.

To test sending right away from your terminal:

```bash
vibiz send --to ana@example.com --subject "Welcome to Acme" --text "Hi Ana, welcome aboard!" --from hello
```

Your project sends transactional emails as `<mailbox>@<slug>.vibiz.app` (`info@<slug>.vibiz.app` by default). The mail domain does not receive incoming messages, so pass a `reply_to` address that points to an active inbox you monitor.

For full technical specifications on mailboxes and parameters, check the [Email documentation](https://thelastapi.dev/docs/email).

## Sending a welcome email from a Next.js Route Handler

Install the client SDK in your Next.js project:

```bash
npm install @vibiz/app
```

The SDK uses `VIBIZ_APP_KEY`, which the CLI writes to `.env.development.local` during local development with `vibiz dev`. Because email sending requires your app key, make sure you call it only in server-side code: Route Handlers, Server Actions, or server components.

Here is a standard Next.js App Router route handler (`app/api/auth/welcome/route.ts`) that accepts user details and sends a welcome message:

```ts
import { NextResponse } from 'next/server';
import { vibiz } from '@vibiz/app';

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

    if (!email || typeof email !== 'string') {
      return NextResponse.json(
        { error: 'A valid email is required' },
        { status: 400 }
      );
    }

    const result = await vibiz.email.send({
      to: email,
      subject: 'Welcome to Acme!',
      from: 'hello',
      from_name: 'Acme Team',
      reply_to: 'support@example.com',
      text: `Hi ${name || 'there'},\n\nWelcome to Acme. We are glad to have you here.\n\nReply to this email if you need anything.`,
      html: `<p>Hi ${name || 'there'},</p><p>Welcome to <strong>Acme</strong>. We are glad to have you here.</p><p>Reply to this email if you need anything.</p>`,
    });

    return NextResponse.json({ ok: true, data: result });
  } catch (error: any) {
    return NextResponse.json(
      { error: error.message || 'Failed to send welcome email' },
      { status: 500 }
    );
  }
}
```

If you store users in a database when they sign up, run your database insert first, then trigger the welcome email. For pairing this workflow with database models, read how to [use Postgres from Next.js with Drizzle or Prisma](https://thelastapi.dev/blog/postgres-nextjs-drizzle-prisma).

## Sending from a Server Action on user registration

In modern Next.js applications, form submissions often run through Server Actions. You can execute the user creation and email trigger inside one server-side action without creating an extra public HTTP endpoint.

Here is an example action (`app/actions/signup.ts`):

```ts
'use server';

import { vibiz } from '@vibiz/app';

interface SignupState {
  success: boolean;
  message?: string;
}

export async function registerUser(
  prevState: SignupState,
  formData: FormData
): Promise<SignupState> {
  const email = formData.get('email')?.toString();
  const firstName = formData.get('firstName')?.toString() || 'friend';

  if (!email || !email.includes('@')) {
    return { success: false, message: 'Please provide a valid email address.' };
  }

  // 1. Insert user record into your database here...

  // 2. Dispatch welcome email
  try {
    await vibiz.email.send({
      to: email,
      subject: 'Welcome to our platform',
      from: 'welcome',
      from_name: 'Founder at Acme',
      reply_to: 'founder@example.com',
      text: `Hi ${firstName},\n\nThanks for signing up. Let us know if you run into any questions getting started.`,
    });

    return { success: true };
  } catch (err: any) {
    // If rate-limited or pending, log it without failing registration
    console.error('Email failed to send:', err);
    return { success: true, message: 'Account created, welcome email pending.' };
  }
}
```

This pattern keeps keys secure on the server while giving the user immediate feedback.

## Transactional welcome email vs. an automated welcome series

A single transactional email is best when you only need an instant notification confirming account registration. If your goal is an onboarding sequence that tracks user actions over several days, you should use contacts and marketing automations instead.

thelastapi separates marketing email from transactional mail. Marketing automations run on their own address (`hello@news.<slug>.vibiz.app`), protect your transactional reputation, and require a physical postal address in the footer to meet legal standards.

| Feature | `vibiz.email.send` (Transactional) | Marketing Automations (`contacts`) |
| --- | --- | --- |
| Best for | Account confirmations, password resets, simple welcomes | Multi-step onboarding, drip sequences, feature tips |
| Limits | 50 emails per project per UTC day | 500 first day, doubling daily up to 100,000 |
| Pricing | ~$0.00013 per sent email | $0.001 per contact sent |
| Setup | `vibiz add email` | `vibiz email setup` and postal address configuration |
| Sending address | `<name>@<slug>.vibiz.app` | `hello@news.<slug>.vibiz.app` |

To trigger a multi-day onboarding series instead of a single message, add the user as a contact:

```ts
import { vibiz } from '@vibiz/app';

await vibiz.contacts.upsert({
  email: user.email,
  first_name: user.firstName,
  lists: ['Users'],
  properties: { plan: 'free', signed_up_at: new Date().toISOString() },
  consent: { method: 'app_signup', text: 'Account registration' },
});
```

To dive deeper into setting up triggers, conditions, and branch logic across days, see our guide on [email automations: a welcome series triggered by events](https://thelastapi.dev/blog/email-automation-welcome-series).

## Sending from your own domain

Sending from `<slug>.vibiz.app` lets you build immediately without editing DNS records. For production brands, you can send as `hello@yourcompany.com` by adding a mailbox to your domain.

Add the mailbox with the CLI:

```bash
vibiz email mailbox add hello@yourcompany.com --name "Acme Support"
```

Verify the records needed for your domain:

```bash
vibiz email dns yourcompany.com --check
```

The CLI shows the records needed:

- **MX (`@`)**: Routes incoming mail to your project inbox.
- **CNAME (`<token>._domainkey`)**: Three records establishing domain ownership and DKIM signing.
- **MX and TXT (`bounce`)**: Sets SPF alignment so sender authentication passes clean checks.
- **TXT (`_dmarc`)**: Recommends `v=DMARC1; p=none;` if no DMARC record exists.

If you purchased your domain through thelastapi (`vibiz domains buy yourcompany.com`), these records are written automatically. Once verified, mailboxes can send up to 200 messages per UTC day (1,000 per account per day). If you do not want to configure your custom domain right away, see how to [send transactional email from your app without touching DNS](https://thelastapi.dev/blog/send-transactional-email-no-dns).

## Handling errors and daily limits

When sending welcome emails from your Next.js application, account for common API responses:

1. **`429 rate_limited`**: Transactional email allows 50 messages per project per UTC day across all mailboxes. The API response returns `details.resets_at` indicating when the quota resets. Failed sends do not count toward this limit.
2. **`409 dependency_not_ready`**: The email resource was added recently, and the domain is still validating (`pending`). Wait two to three minutes before retrying.
3. **`403 sending_paused`**: Sending halts if bounce rates or spam complaints exceed acceptable thresholds.
4. **`400 invalid_request`**: Check that the `to` field contains a single address and that either `text` or `html` is provided.

For direct HTTP requests, you can supply an `Idempotency-Key` header so network retries never send duplicate welcome emails:

```bash
curl https://thelastapi.dev/v1/projects/prj_123/actions/email.send \
  -H "Authorization: Bearer $VIBIZ_API_KEY" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: welcome-u_123" \
  -d '{"input":{"to":"ana@example.com","subject":"Welcome","text":"Hi Ana","from":"hello"}}'
```

Next, read how to [import a newsletter list from CSV, safely](https://thelastapi.dev/blog/import-newsletter-list-csv) if you are migrating existing users to your new setup.

## Frequently asked questions

### Can I send HTML welcome emails from Next.js with thelastapi?

Yes. Pass your markup to the `html` property in `vibiz.email.send({ to, subject, html })`. You must provide at least one of `text` or `html`.

### What are the daily sending limits for transactional emails?

A project can send up to 50 transactional emails per UTC day across all its mailboxes. Failed sends do not count against this daily quota.

### Can my Next.js app receive replies sent to the welcome email?

The default `<slug>.vibiz.app` domain does not receive incoming email, so you should pass a monitored inbox to `reply_to`. If you configure a custom domain mailbox via `vibiz email mailbox add`, you can read and reply to incoming threads in the console or CLI.

### How much does sending a transactional email cost?

Each sent email costs a fraction of a cent from your account credits (about $0.00013: $0.0001 plus 30%). Failed sends record no charge.

---

Published 2026-11-15 · https://thelastapi.dev/blog/welcome-email-nextjs
