Next.js send email API: route handlers and server actions

Updated

There is no Next.js-specific Inboxili package. Use the official Node SDK (@inboxili/node) from server-only code, as shown below.

In Next.js the rule is simple: the Inboxili API key lives in server-only code. Browsers call your route handler or server action, and that code calls Inboxili.

Environment

.env.local (never prefix with NEXT_PUBLIC_):

INBOXILI_API_KEY=ik_live_...

Install the SDK and create a server-only helper

npm install @inboxili/node server-only

lib/inboxili.ts:

import "server-only";
import { Inboxili } from "@inboxili/node";

export const inboxili = new Inboxili({ apiKey: process.env.INBOXILI_API_KEY! });
export { InboxiliError } from "@inboxili/node";

The server-only import makes the build fail if a client component ever imports this file, so the key cannot leak into the browser bundle. See the Node.js integration for the SDK's full options and error types.

A route handler

app/api/contact/route.ts:

import { NextResponse } from "next/server";
import { inboxili, InboxiliError } from "@/lib/inboxili";

const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

export async function POST(req: Request) {
  const { name, email, message } = await req.json();
  if (typeof email !== "string" || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email) || typeof message !== "string" || message.length > 5000) {
    return NextResponse.json({ error: "Invalid input" }, { status: 400 });
  }

  try {
    await inboxili.emails.send({
      to: "support@yourdomain.com",
      fromEmail: "website@yourdomain.com",
      fromName: "Website",
      subject: "New contact message",
      htmlBody: "<p><strong>{{name}}</strong> ({{email}}) wrote:</p><p>{{message}}</p>",
      templateData: { name: esc(String(name ?? "")), email: esc(email), message: esc(message) },
    });
    return NextResponse.json({ ok: true });
  } catch (err) {
    if (err instanceof InboxiliError && err.status === 429) {
      return NextResponse.json({ error: "Busy, try again shortly" }, { status: 503 });
    }
    console.error("inboxili send failed", err);
    return NextResponse.json({ error: "Could not send" }, { status: 502 });
  }
}

Everything that comes from the visitor is escaped before it goes into the HTML. This also stops a visitor from using your form to send arbitrary email: the recipient and sender are fixed in code.

Rate-limit public forms

A public contact form that triggers an API call is an abuse target, and each key delivers 100 emails a minute, so an abused form quickly builds a queue of emails you did not want to send. Add per-IP limiting (for example Upstash Ratelimit or middleware) in front of any route that sends mail.

Server action variant

"use server";
import { inboxili } from "@/lib/inboxili";

export async function requestLoginCode(email: string) {
  const code = String(crypto.getRandomValues(new Uint32Array(1))[0] % 1_000_000).padStart(6, "0");
  // store a hash of `code` with an expiry, then:
  await inboxili.emails.send({
    to: email,
    fromEmail: "security@yourdomain.com",
    subject: "Your code",
    htmlBody: "<p>Your code is <strong>{{code}}</strong></p>",
    textBody: `Your code is ${code}`,
    templateData: { code },
  });
}

See the OTP workflow for storing and checking the code.

Testing

Mock the helper in your unit tests with your test runner's module mocking, and keep a single manual end-to-end check against a real verified domain in staging.

Production notes

  • Add INBOXILI_API_KEY as a secret in your hosting provider, not in the repo.
  • Route handlers on serverless platforms have execution limits. Keep the call to one request and return quickly.
  • A timeout does not tell you whether the email went out. The API has no idempotency key.

Troubleshooting

| Symptom | Cause | Fix | |---|---|---| | INBOXILI_API_KEY is undefined in production | Variable not set on the host, or set after the build for a build-time read | Add it in your hosting provider's environment settings and redeploy. It is read at request time on the server. | | Build error "This module cannot be imported from a Client Component" | A client component imports lib/inboxili.ts | Call a route handler or server action from the client instead. | | 401 unauthorized | Wrong or revoked key | Create a new key in Settings, Developer. | | 422 sender_not_verified | fromEmail is not on a verified domain | Verify the domain and add the sender. | | Works locally, times out on the host | Serverless function limit too low or outbound blocked | Keep the handler to one request and check the function timeout. | | Contact form abused to send spam | Public route with no limiting | Add per-IP rate limiting and a challenge in front of it. |

Frequently asked questions

Can I call the API from a client component?
No. The API key would be exposed to every visitor. Call it from a route handler, server action or server component only.

Official SDKs

Build with Inboxili

Create a workspace, verify a domain, and make your first API call.

Related