What you'll build
- A typed receipt template and a welcome template built with React Email components
- A live preview server that reloads as you edit
- A server-only helper that renders HTML and plain text and sends them
- A receipt email sent from a Server Action after checkout
Before you start
- Node.js 20.19 or newer
- A Next.js 16 app using the App Router
- A free CloudHike.dev account with Email deployed (see How to Send Email from Next.js)
Why build emails with React?
Email HTML is stuck in the past. Mail clients ignore most modern CSS, Outlook still renders with Word, and styles must be inline. Writing that by hand in template strings gets messy fast.
| Approach | Good | Watch out for |
|---|---|---|
| HTML in template strings | No dependencies | Hard to read, easy to forget escaping, no preview |
| MJML | Mature, responsive by default | Its own markup language and build step |
| React Email | Components, props and TypeScript you already know, a live preview, and text output for free | One more dependency in your server bundle |
React Email gives you components like Button, Row and Column that turn into table-based, inline-styled HTML that works across clients. React also escapes every value you pass as a prop or child, so a customer's name can't inject markup into your email.
Step 1: Install React Email
Since React Email 6, the components and the render function ship in one package, react-email. The preview server lives in @react-email/ui, which you only need in development.
npm install react-email server-only
npm install -D @react-email/uiOlder tutorials install @react-email/components and @react-email/render. Those still work on older versions, but React Email 6 deprecates @react-email/components. Import everything from react-email instead. The code is otherwise the same.
Tell Next.js to load React Email from node_modules at runtime instead of bundling it. Rendering then uses Node's normal React server runtime, which avoids errors about react-dom/server in App Router code.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
serverExternalPackages: ["react-email"],
};
export default nextConfig;Add a script for the preview server. It reads templates from the emails folder and runs on port 3001, so it doesn't clash with next dev.
{
"scripts": {
"dev": "next dev",
"email:dev": "email dev --dir emails --port 3001"
}
}Step 2: Write a receipt template
A template is a React component that returns <Html>. Keep it pure: data comes in as props, nothing is fetched inside. That makes it easy to preview and to test.
import { Body, Button, Column, Container, Head, Heading, Hr, Html, Preview, Row, Section, Text } from "react-email";
export type ReceiptProps = {
customerName: string;
orderId: string;
date: string; // already formatted, e.g. "Nov 18, 2026"
currency: string; // "USD"
items: { name: string; quantity: number; amountCents: number }[];
orderUrl: string;
};
const money = (cents: number, currency: string) =>
new Intl.NumberFormat("en-US", { style: "currency", currency }).format(cents / 100);
export default function Receipt({ customerName, orderId, date, currency, items, orderUrl }: ReceiptProps) {
const total = items.reduce((sum, item) => sum + item.amountCents * item.quantity, 0);
return (
<Html lang="en">
<Head />
<Preview>{`Your receipt for order ${orderId}: ${money(total, currency)}`}</Preview>
<Body style={{ backgroundColor: "#f4f4f5", fontFamily: "Helvetica, Arial, sans-serif", margin: 0, padding: "24px 0" }}>
<Container style={{ backgroundColor: "#ffffff", borderRadius: 8, maxWidth: 560, padding: 32 }}>
<Heading as="h1" style={{ fontSize: 22, margin: "0 0 8px" }}>
Thanks for your order, {customerName}!
</Heading>
<Text style={{ color: "#52525b", margin: 0 }}>
Order {orderId} · {date}
</Text>
<Hr style={{ borderColor: "#e4e4e7", margin: "24px 0" }} />
<Section>
{items.map((item) => (
<Row key={item.name} style={{ marginBottom: 8 }}>
<Column>
<Text style={{ margin: 0 }}>
{item.name} × {item.quantity}
</Text>
</Column>
<Column align="right">
<Text style={{ margin: 0 }}>{money(item.amountCents * item.quantity, currency)}</Text>
</Column>
</Row>
))}
</Section>
<Hr style={{ borderColor: "#e4e4e7", margin: "24px 0" }} />
<Row>
<Column>
<Text style={{ fontWeight: 700, margin: 0 }}>Total</Text>
</Column>
<Column align="right">
<Text style={{ fontWeight: 700, margin: 0 }}>{money(total, currency)}</Text>
</Column>
</Row>
<Section style={{ marginTop: 32, textAlign: "center" }}>
<Button
href={orderUrl}
style={{ backgroundColor: "#18181b", borderRadius: 6, color: "#ffffff", fontWeight: 600, padding: "12px 20px" }}
>
View your order
</Button>
</Section>
<Text style={{ color: "#71717a", fontSize: 13, marginTop: 32 }}>
Questions? Just reply to this email.
</Text>
</Container>
</Body>
</Html>
);
}
// Sample data for the preview server only.
Receipt.PreviewProps = {
customerName: "Ada",
orderId: "A-1042",
date: "Nov 18, 2026",
currency: "USD",
items: [
{ name: "Pro plan (monthly)", quantity: 1, amountCents: 2000 },
{ name: "Extra seat", quantity: 2, amountCents: 500 },
],
orderUrl: "https://example.com/orders/A-1042",
} satisfies ReceiptProps;Previewsets the grey snippet that inboxes show next to the subject. Make it useful, not a repeat of the subject.RowandColumnbecome tables, the only layout every client agrees on. Avoid flexbox and grid in email.Buttonrenders a link styled as a button that also works in Outlook.- Inline
styleobjects are fine. React Email writes them as inline styles, which is what mail clients need.
A welcome email follows the same shape. Keep it short and give one clear next step:
import { Body, Button, Container, Head, Heading, Html, Preview, Text } from "react-email";
export type WelcomeProps = { name: string; dashboardUrl: string };
export default function Welcome({ name, dashboardUrl }: WelcomeProps) {
return (
<Html lang="en">
<Head />
<Preview>Your account is ready. Here is where to start.</Preview>
<Body style={{ backgroundColor: "#f4f4f5", fontFamily: "Helvetica, Arial, sans-serif", padding: "24px 0" }}>
<Container style={{ backgroundColor: "#ffffff", borderRadius: 8, maxWidth: 560, padding: 32 }}>
<Heading as="h1" style={{ fontSize: 22 }}>Welcome, {name}!</Heading>
<Text>Thanks for signing up. Your account is ready to use.</Text>
<Button href={dashboardUrl} style={{ backgroundColor: "#18181b", borderRadius: 6, color: "#ffffff", padding: "12px 20px" }}>
Open your dashboard
</Button>
<Text style={{ color: "#71717a", fontSize: 13 }}>Reply to this email if you get stuck. A real person reads it.</Text>
</Container>
</Body>
</Html>
);
}
Welcome.PreviewProps = { name: "Ada", dashboardUrl: "https://example.com/dashboard" } satisfies WelcomeProps;Step 3: Preview your emails while you edit
npm run email:devOpen http://localhost:3001. Every file in emails/ shows up in the sidebar, rendered with its PreviewProps. Save a file and the preview reloads. You can switch between desktop and mobile widths, view the HTML source and the plain-text version, and see warnings for CSS that some mail clients don't support.
Images must use absolute https:// URLs in the real email, because mail clients can't load paths relative to your site. A common setup is to put them in public/email/ and build the URL from your site's origin.
The preview is a good first check, not the last one. Before launch, send a test to Gmail, Outlook and Apple Mail and look at them on a phone too. Dark mode can invert your colors, so avoid white text on images and transparent logos on dark backgrounds.
Step 4: Render HTML and plain text
render turns a React element into an HTML string. In current versions it is always async, so remember the await. Pass { plainText: true } to get a text version from the same template, which spam filters and text-only clients like to see.
import "server-only";
type Email = {
to: string | string[];
subject: string;
html?: string;
text?: string;
replyTo?: string;
fromName?: string;
from?: 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 }[] };
}Then add one small file that renders a template and sends it. It's a .tsx file because it uses JSX.
import "server-only";
import type { ReactElement } from "react";
import { render } from "react-email";
import Receipt, { type ReceiptProps } from "@/emails/receipt";
import Welcome, { type WelcomeProps } from "@/emails/welcome";
import { sendEmail } from "@/lib/email";
async function renderBoth(element: ReactElement) {
const [html, text] = await Promise.all([render(element), render(element, { plainText: true })]);
return { html, text };
}
export async function sendReceipt(to: string, props: ReceiptProps) {
const { html, text } = await renderBoth(<Receipt {...props} />);
return sendEmail({
to,
subject: `Your receipt for order ${props.orderId}`,
html,
text,
fromName: "Acme",
replyTo: "support@example.com",
});
}
export async function sendWelcome(to: string, props: WelcomeProps) {
const { html, text } = await renderBoth(<Welcome {...props} />);
return sendEmail({ to, subject: `Welcome, ${props.name}!`, html, text, replyTo: "support@example.com" });
}React escapes text, but it does not check URLs. Never pass a link a user typed straight into href. Build links yourself from your own origin and IDs you control.
Step 5: Send the receipt from a Server Action
Call the helper wherever the order is confirmed. Here it runs inside a Server Action after the order is saved. after() sends the email once the response has gone out, so the user isn't kept waiting on it.
"use server";
import { after } from "next/server";
import { redirect } from "next/navigation";
import { sendReceipt } from "@/lib/transactional";
export async function completeOrder(form: FormData) {
const email = String(form.get("email") ?? "").trim();
const name = String(form.get("name") ?? "").trim() || "there";
// ...charge the card and save the order in your database here...
const order = {
id: "A-1042",
currency: "USD",
items: [{ name: "Pro plan (monthly)", quantity: 1, amountCents: 2000 }],
};
after(async () => {
try {
await sendReceipt(email, {
customerName: name,
orderId: order.id,
date: new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }),
currency: order.currency,
items: order.items,
orderUrl: `${process.env.APP_URL}/orders/${encodeURIComponent(order.id)}`,
});
} catch (err) {
// Log it, and let the order page offer "Email me my receipt" as a fallback.
console.error("Receipt email failed", order.id, err);
}
});
redirect(`/orders/${encodeURIComponent(order.id)}`);
}If you take payments with Stripe, the best place to send the receipt is the webhook that confirms the payment, not the checkout page. Webhooks are retried, so record that you sent the receipt for that payment and skip it the second time.
Open the Logs tab on the project's Email page to see each message and whether it was delivered. CloudHike doesn't store message bodies, so keep the rendered HTML in your own logs if you need a copy.
Production checklist
- Add
EMAIL_API_URL,EMAIL_API_KEYandAPP_URLto your host's environment variables. Never prefix them withNEXT_PUBLIC_. - Keep
@react-email/uiindevDependencies. Production only needsreact-email. - Send from your own verified domain with
from, so the sender matches your brand. - Always send
textalong withhtml.render(element, { plainText: true })makes it for you. - Use absolute image URLs and test in Gmail, Outlook, Apple Mail and on a phone, in light and dark mode.
- Handle
429from the API by readingRetry-After. Check the email limits for your plan. - Only send transactional mail: receipts, welcomes, resets and alerts. React Email makes newsletters easy, but they don't belong on a transactional sender.
Frequently asked questions
Should I use @react-email/components or react-email?
On React Email 6 and newer, install react-email and import components and render from it. @react-email/components is deprecated there. If you are on an older version, @react-email/components still works with the same component names.
Is the React Email render function async?
Yes. render returns a Promise of a string, so you must await it. Older versions had a separate renderAsync function, which was deprecated when render itself became async.
Can I use Tailwind CSS in React Email templates?
Yes. Wrap your template in the Tailwind component from react-email and use className. It converts the classes to inline styles at render time. Stick to simple utilities, since mail clients ignore many modern CSS features.
Does React Email send emails?
No. React Email only builds the HTML and text. You still need an email API or SMTP server to deliver it. This guide sends the rendered output with one HTTP call to CloudHike Email.
Why does my React Email template look different in Outlook?
Desktop Outlook renders email with Word's engine, which ignores things like rounded corners, background images and some padding. Use Row and Column for layout, keep styles simple, and test in Outlook before launch.
