Next.js
Send an email from a Next.js route handler or server action with notix-js.
Send an email from a Next.js App Router route handler or server action with notix-js. The key stays on the server, so it never reaches the browser.
Prerequisites
- An API key.
- A verified domain to send from.
Install the SDK
npm install notix-jspnpm add notix-jsyarn add notix-jsbun add notix-jsSet your API key
Add the key to
.env.local. Do not prefix it withNEXT_PUBLIC_, or Next.js ships it to the browser.NOTIX_API_KEY=notix_12345Send from a route handler
The route only sends to the signed-in customer, about their own order.
authandgetOrderstand for your app's own sign-in and database code.import { Notix } from "notix-js"; import { auth } from "@/lib/auth"; // your sign-in library import { getOrder } from "@/lib/orders"; // your database code const notix = new Notix(process.env.NOTIX_API_KEY); export async function POST(request: Request) { // Anyone can call this URL. Check who is calling before you send anything. const session = await auth(); if (!session?.user) return new Response("Sign in first", { status: 401 }); const { orderId } = (await request.json()) as { orderId?: string }; const order = orderId ? await getOrder(orderId) : null; if (!order || order.userId !== session.user.id) return new Response("Order not found", { status: 404 }); const { data, error } = await notix.emails.send({ from: "Acme <receipts@acme.com>", to: session.user.email, // from the session, never from the request body subject: `Your receipt for order ${order.number}`, html: "<p>Thanks for your order.</p>", }); if (error) return Response.json({ error: "Could not send the receipt" }, { status: 502 }); return Response.json({ emailId: data?.emailId }); }Or send from a server action
A server action is a public endpoint. Check who is calling and never take the recipient straight from the client.
"use server"; import { Notix } from "notix-js"; import { auth } from "@/lib/auth"; // your sign-in library import { getOrder } from "@/lib/orders"; // your database code const notix = new Notix(process.env.NOTIX_API_KEY); export async function sendReceipt(orderId: string) { const session = await auth(); if (!session?.user) throw new Error("Sign in first"); const order = await getOrder(orderId); if (!order || order.userId !== session.user.id) throw new Error("Order not found"); const { data, error } = await notix.emails.send({ from: "Acme <receipts@acme.com>", to: session.user.email, // looked up on the server subject: `Your receipt for order ${order.number}`, html: "<p>Thanks for your order.</p>", }); if (error) throw new Error("Could not send the receipt"); return data?.emailId; }
Building the email with React? notix.emails.send also takes a react field and renders it to HTML for you. See React Email.
Next steps
- Send many emails at once with batch sending.
- Add files with attachments.
- Make retries safe with idempotency keys.
- Receive delivery events in a route handler with webhooks.