Skip to content
Email guide

How to Send Email from Next.js (App Router + Server Actions)

Build a working contact form and a welcome email in a Next.js App Router app, with the API key kept on the server and no SMTP setup.

15 min Beginner Markdown for AI

What you'll build

  • A contact form that emails you through a Server Action
  • A reusable sendEmail() helper that only runs on the server
  • A welcome email sent when a user signs up
  • Friendly errors for bad input and rate limits

Before you start

  • Node.js 20 or newer
  • A Next.js 16 app using the App Router (npx create-next-app@latest)
  • A free CloudHike.dev account

Your options for sending email from Next.js

Next.js has no built-in mailer, so every app picks one of three routes. All of them must run on the server: the credentials that send mail can never reach the browser.

OptionGoodWatch out for
SMTP with NodemailerWorks with any mailbox providerSMTP passwords, connection limits on serverless, and you handle deliverability
An email API (Resend, Postmark, SES)One HTTP call, good deliverabilityAnother vendor, account and bill next to your database
CloudHike EmailOne HTTP call, same project and .env as your database, auth and storageTransactional mail only, no newsletters

This guide uses CloudHike Email because it needs no SMTP or DNS work to start, but the code shape (a server-only helper called from a Server Action) is the same for any HTTP email API.

Step 1: Get an email API key

  1. Sign in at cloudhike.dev and create a project.
  2. On the Email card, tick the box to accept the email policy and click Deploy.
  3. Click Copy as .env and paste the values into .env.local at the root of your Next.js app.
.env.local
Shell
EMAIL_API_URL=https://...
EMAIL_API_KEY=...
# Where contact form messages should land
CONTACT_INBOX=you@example.com

Never prefix these with NEXT_PUBLIC_. That would bundle the key into browser JavaScript, and anyone could send mail as your project.

Step 2: Write a server-only sendEmail helper

Put the API call in one file. The server-only import makes the build fail if a Client Component ever imports it, which is a cheap guard against leaking the key.

Shell
npm install server-only
lib/email.ts
TypeScript
import "server-only";

type Email = {
  to: string | string[];
  subject: string;
  html?: string;
  text?: string;
  replyTo?: string;
  fromName?: string;
};

export class EmailError extends Error {
  constructor(message: string, public status: number, public retryAfter?: number) {
    super(message);
  }
}

export async function sendEmail(email: Email) {
  const res = await fetch(`${process.env.EMAIL_API_URL}/send`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.EMAIL_API_KEY!,
    },
    body: JSON.stringify(email),
  });

  if (!res.ok) {
    const retryAfter = Number(res.headers.get("retry-after")) || undefined;
    const { message } = await res.json().catch(() => ({ message: res.statusText }));
    throw new EmailError(message ?? "Email failed", res.status, retryAfter);
  }
  return (await res.json()) as { results: { to: string; id: string; status: string }[] };
}

Send text along with html whenever you can. Some mail clients show only plain text, and spam filters trust messages that include both.

Step 3: Build a contact form with a Server Action

A Server Action is an async function that runs on the server but can be passed straight to a form's action. There's no API route to write, and the form still works before JavaScript loads.

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

import { EmailError, sendEmail } from "@/lib/email";

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

const escape = (s: string) =>
  s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);

export async function sendContact(_prev: ContactState, form: FormData): Promise<ContactState> {
  const name = String(form.get("name") ?? "").trim();
  const email = String(form.get("email") ?? "").trim();
  const message = String(form.get("message") ?? "").trim();

  if (!name || !/^\S+@\S+\.\S+$/.test(email) || message.length < 10) {
    return { ok: false, message: "Please fill in your name, a valid email and a message." };
  }

  try {
    await sendEmail({
      to: process.env.CONTACT_INBOX!,
      replyTo: email, // hitting Reply answers the visitor
      fromName: "Website contact form",
      subject: `New message from ${name}`.slice(0, 200),
      text: `${name} <${email}> wrote:\n\n${message}`,
      html: `<p><strong>${escape(name)}</strong> &lt;${escape(email)}&gt; wrote:</p><p>${escape(message).replace(/\n/g, "<br>")}</p>`,
    });
    return { ok: true, message: "Thanks! We'll get back to you soon." };
  } catch (err) {
    if (err instanceof EmailError && err.status === 429) {
      return { ok: false, message: "Too many messages right now. Please try again in a minute." };
    }
    console.error(err);
    return { ok: false, message: "Something went wrong. Please try again." };
  }
}

Always escape what visitors type before putting it into HTML. Otherwise someone can inject links or markup into the email you receive.

app/contact/page.tsx
TSX
"use client";

import { useActionState } from "react";
import { sendContact } from "./actions";

export default function ContactPage() {
  const [state, action, pending] = useActionState(sendContact, null);

  return (
    <form action={action} className="mx-auto grid max-w-md gap-3 p-8">
      <input name="name" placeholder="Your name" required />
      <input name="email" type="email" placeholder="you@example.com" required />
      <textarea name="message" rows={5} placeholder="How can we help?" required minLength={10} />
      <button disabled={pending}>{pending ? "Sending…" : "Send message"}</button>
      {state && <p role="status" style={{ color: state.ok ? "green" : "crimson" }}>{state.message}</p>}
    </form>
  );
}

Run npm run dev, open http://localhost:3000/contact and send yourself a message. It shows up in your inbox and in the Logs tab of the Email page in your CloudHike dashboard.

Step 4: Send a welcome email on sign-up

Most apps send mail in response to something the user did. Call the same helper wherever that happens, for example right after you create the user:

app/signup/actions.ts
TypeScript
"use server";

import { after } from "next/server";
import { sendEmail } from "@/lib/email";

export async function signUp(form: FormData) {
  const email = String(form.get("email"));
  const name = String(form.get("name"));

  // ...create the user in your database or auth service here...

  // after() runs once the response is sent, so a slow email
  // never makes the sign-up feel slow.
  after(() =>
    sendEmail({
      to: email,
      subject: `Welcome, ${name}!`,
      text: `Hi ${name},\n\nThanks for signing up. Reply to this email if you need anything.`,
      html: `<p>Hi ${name},</p><p>Thanks for signing up. Reply to this email if you need anything.</p>`,
      replyTo: "support@example.com",
    }).catch(console.error),
  );
}

after() is a good fit for an email that is nice to have. For mail the user is waiting on, such as a sign-in code, await the call and show an error if it fails. If you need to retry over minutes or hours, move the send into a background job.

Step 5: Send from your own domain

Out of the box, mail comes from <project>@cloudhike.dev, which is fine while you build. Before launch, send from your own domain so people recognise and trust the sender.

  1. On the project's Email page, open Domains and add a subdomain such as mail.example.com.
  2. Add the DKIM, SPF and DMARC records it shows at your DNS provider.
  3. When the domain shows Verified, add from: "hello@mail.example.com" to your sendEmail() calls.

The Email docs list every record and what it does.

Production checklist

  • Add EMAIL_API_URL, EMAIL_API_KEY and CONTACT_INBOX to your host's environment variables (Vercel: Project → Settings → Environment Variables).
  • Protect public forms from bots with a hidden honeypot field or a Redis rate limit.
  • Handle 429 responses: the API sends a Retry-After header with how many seconds to wait.
  • Only send transactional mail (receipts, resets, alerts). Marketing blasts hurt your sender reputation.
  • Check the bounce and complaint rates on the Email overview after launch.

Frequently asked questions

Can I send email from a Next.js Client Component?

No. Sending email needs a secret API key, and anything in a Client Component is shipped to the browser. Call a Server Action or a Route Handler from the client instead, and send the email there.

Should I use a Server Action or an API route to send email?

For forms in your own Next.js app, a Server Action is simpler: no fetch call, no JSON parsing, and the form works without JavaScript. Use a Route Handler (app/api/.../route.ts) when something outside your app, such as a mobile app or a webhook, needs to trigger the email.

Does Nodemailer work with Next.js?

Yes, in server code with the Node.js runtime. But SMTP opens a connection per send, which is slow on serverless hosts, and you manage the mailbox credentials and deliverability yourself. An HTTP email API avoids both.

Why are my emails going to spam?

Usually the sending domain is not verified. Add the DKIM, SPF and DMARC records for your domain, send both a text and HTML version, and keep a real reply-to address.

How much does it cost to send email from CloudHike?

The free plan includes a daily and monthly email allowance at no cost. On Pro a monthly allowance per project is included, then you pay per 1,000 emails. See the pricing page for current numbers.