Skip to content

Send transactional email from Next.js

Add password resets, receipts, and other operational email to a Next.js app with the Loops SDK. The examples run on the server and cover contact sync, environment variables, and password reset sends.

Who this is for

You have a Next.js app that needs to send operational email: password resets, verifications, receipts. Loops can also run campaigns and workflows from the same audience when you need them, and transactional-only recipients can stay outside it. See how transactional email works on Loops.

💡

Tested on November 18, 2026

Next.js 16.4.6, App Router: route handlers and server actions
React 19.3.1
Node.js 24.13.0
loops 7.5.0, the official JavaScript SDK, released November 10, 2026
TypeScript 7.0.2, strict mode

Next.js 16.4.6 needs Node.js 20.9 or later, and the loops package needs 18 or later.

The example project passed strict npx tsc --noEmit and npx next build, plus 13 server-side tests against a stubbed fetch with no calls to the Loops API. The browser form and the shell commands weren’t run as tests.

💡

Tested on November 18, 2026

Next.js 16.4.6, App Router: route handlers and server actions
React 19.3.1
Node.js 24.13.0
loops 7.5.0, the official JavaScript SDK, released November 10, 2026
TypeScript 7.0.2, strict mode

Next.js 16.4.6 needs Node.js 20.9 or later, and the loops package needs 18 or later.

The example project passed strict npx tsc --noEmit and npx next build, plus 13 server-side tests against a stubbed fetch with no calls to the Loops API. The browser form and the shell commands weren’t run as tests.

Choosing an email API for Next.js

For a password reset, compare where the API key lives, where the template lives, what your app sends and what happens when a request is retried. Check these before you pick an email API.

  • Server-side sending. Every call should run in trusted server code, such as a route handler, a server action or a worker, with the key in an environment variable that never reaches the client. The Loops API doesn’t accept cross-origin requests from browser JavaScript.

  • An SDK with TypeScript types. TypeScript checks SDK parameter names and value types before anything ships, though it can’t check your template’s variable names. The official loops package on npm has full TypeScript support and needs Node 18 or later.

  • Templates you can keep in code. Check where templates live and whether your code and your coding agent can edit them. Loops emails can be written in LMX, the Loops markup, created and edited through the API or CLI, and kept in Git next to your app. Your code sends a transactionalId with data variables, and your team can still edit the same email in the Loops editor without a deploy.

  • Rate limits and retries. Find the limit and what a rejected request looks like. Loops sends and events have a baseline of 10 requests per second per team and return a 429 above that. The SDK throws RateLimitExceededError, so you can back off and retry.

  • Idempotency. A retried request shouldn’t send a second email. Loops takes an Idempotency-Key header (up to 100 characters) on transactional sends and events, and returns a 409 if the same key was used in the previous 24 hours.

  • Webhooks. Delivery and bounce events should come back to your app. Loops signs webhook events and makes up to eight delivery attempts over about 28 hours. Transactional events cover sends, deliveries, bounces and spam reports, and open and click events are available for marketing email. The docs include a Next.js route handler that verifies the signature.

  • SMTP fallback. Some tools send through SMTP settings, such as Supabase Auth’s custom SMTP option or Nodemailer’s SMTP transport. Loops runs an SMTP server for transactional email (smtp.loops.so, port 587, an API key as the password). The message body is the same JSON as an API send, so it still uses a Loops template.

  • Marketing and transactional in one place. If onboarding sequences, product updates or newsletters come later, check whether they can use the same contacts. Loops sends transactional, marketing and lifecycle email from one contact record, transactional-only recipients can stay outside your audience, and sendEvent starts a workflow from your app.

  • Pricing model. Check whether you pay per send, per contact or per seat. Loops prices by subscribed contacts, with no per-send charges or seat fees, and transactional sends are included on paid plans. The free plan stores unlimited contacts and includes 4,000 marketing and transactional sends every rolling 30 days to your first 1,000 contacts.

  • Works with your coding agent. Check whether an agent can set it up for you. Loops has an MCP server and a CLI with agent skills, so an agent like Claude Code or Codex can create and edit emails, campaigns and workflows, and wire sends into your app.

If your team writes email in code, keep Loops templates as LMX in Git with the LMX workflow, and connect your coding agent through the MCP server or the CLI and skills. The rest of this guide sets up server-side sending with the SDK.

What a Loops send puts on the wire

Your app doesn’t send the email. Each attempt is one SDK call: a JSON body with transactionalId, email and dataVariables, plus an Idempotency-Key header. Loops fills the variables into the published template, builds the email and sends it.

What we measured for this example:

  • Request body: 163 bytes. The JSON the loops SDK passed to fetch: a 15-character recipient address, the template ID and a 58-character reset URL. 157 bytes with gzip -9.

  • Rendered HTML: 26,166 bytes. The matching template rendered locally with the Loops renderer from October 19, 2026, with the same URL filled in and no footer. 4,057 bytes with gzip -9.

These numbers compare the request body with the rendered markup, not bytes on the network, and they change with the template and its inputs. The template is the password reset example from the LMX docs, with its link variable renamed to resetUrl. What stays out of your app is the HTML: it sends the template ID and the values, and never generates or uploads that markup.

Copy changes don’t need a deploy either, as long as the data variables stay the same. Edit the email in Loops and republish it, and the previous version keeps sending until you do. A new required variable needs a release of the code that sends it. If you’d rather review email changes in pull requests, keep the template as LMX in Git and push it with the API or the CLI.

Give this to your agent

Using Claude Code, Cursor, or Codex? Use this prompt to start the integration, then review and test the result.

Install Loops (loops.so) in this Next.js app: npm install loops, create
lib/loops.ts exporting a server-only LoopsClient reading LOOPS_API_KEY,
upsert a contact with updateContact only after the user opts in to
marketing, and send password resets from a background job with
sendTransactionalEmail, a transactionalId from the Loops dashboard and a
stored Idempotency-Key. Docs: https://loops.so/docs/sdks/javascript and
https://loops.so/docs/transactional

Set up Loops before you write code

Do these four things in the Loops dashboard first.

  • Verify a sending domain. In Settings > Domain, add the domain you’ll send from, copy the SPF, DKIM and MX records into your DNS, then click verify. Loops recommends a subdomain such as mail.yourcompany.com. A hosting subdomain like yourapp.vercel.app won’t work, because you can’t add DNS records to it. Domain setup docs.

  • Create an API key. In Settings > API, generate a key and copy it right away. Loops won’t show it again.

  • Create the transactional email. On the Transactional page, create the email and add a data variable named resetUrl as the reset button’s link.

  • Publish it and copy the transactionalId. Click Next to see the API details and an example payload, then click Publish. The transactional ID is on the publish page.

💡

The template and the request must match

Published
Only published transactional emails send. Editing creates a draft, and the published version keeps sending until you republish.

Variables
Include every data variable that isn’t marked optional. A missing one fails the send with a 400.

Names
Case sensitive: resetUrl and resetURL are different variables. Use letters, numbers, underscores and dashes.

Values
Strings, numbers, or arrays of objects with string or number values. Booleans and null don’t work, and the SDK’s types reject them at compile time.

💡

The template and the request must match

Published
Only published transactional emails send. Editing creates a draft, and the published version keeps sending until you republish.

Variables
Include every data variable that isn’t marked optional. A missing one fails the send with a 400.

Names
Case sensitive: resetUrl and resetURL are different variables. Use letters, numbers, underscores and dashes.

Values
Strings, numbers, or arrays of objects with string or number values. Booleans and null don’t work, and the SDK’s types reject them at compile time.

Install the SDK and keep the key on the server

npm install loops

The package is loops on npm. Its source is the loops-so/loops-js repository on GitHub. Add your key and the transactional ID to .env.local:

# .env.local (server side only: no NEXT_PUBLIC_ prefix)
LOOPS_API_KEY=            # Settings -> API
LOOPS_PASSWORD_RESET_ID=  # the transactional email's Publish page
LOOPS_SIGNING_SECRET=     # Settings -> Webhooks

Then create one server-only client:

// lib/loops.ts
import "server-only";
import { LoopsClient } from "loops";

let client: LoopsClient | undefined;

export function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`${name} is not set`);
  return value;
}

export function getLoops(): LoopsClient {
  client ??= new LoopsClient(requireEnv("LOOPS_API_KEY"));
  return client;
}

import “server-only” makes next build fail if a Client Component imports this file, so the key can’t reach the browser bundle. We checked: importing lib/loops.ts from a “use client” page stopped the build. Next.js handles that import itself, so there’s nothing extra to install.

The client is created on first use, not when the file loads. next build passes on a machine without LOOPS_API_KEY, and a call without it throws “LOOPS_API_KEY is not set” before any request goes out.

💡

Never expose the API key

No NEXT_PUBLIC_ prefix
At build time, Next.js inlines the NEXT_PUBLIC_ variables your code references into the JavaScript it sends to the browser. Variables without the prefix stay on the server.

Full access
Anyone with the key gets read and write access to your Loops account data.

Server only
The Loops API doesn’t accept cross-origin requests from client-side JavaScript. Call it from trusted server code: route handlers, server actions or workers.

Never commit it
create-next-app adds .env files to .gitignore, and production keys belong in your host’s environment settings.

💡

Never expose the API key

No NEXT_PUBLIC_ prefix
At build time, Next.js inlines the NEXT_PUBLIC_ variables your code references into the JavaScript it sends to the browser. Variables without the prefix stay on the server.

Full access
Anyone with the key gets read and write access to your Loops account data.

Server only
The Loops API doesn’t accept cross-origin requests from client-side JavaScript. Call it from trusted server code: route handlers, server actions or workers.

Never commit it
create-next-app adds .env files to .gitignore, and production keys belong in your host’s environment settings.

Accept reset requests in a route handler

Don’t send a password reset from inside the request. If the response waits for the account lookup and the Loops call, a known address answers slower than an unknown one, and a failed send has nowhere to go. The request only validates, rate-limits and queues the job. A worker looks up the account and sends.

The route handler and the server action share one intake function:

// lib/reset-intake.ts
import "server-only";
import { enqueue } from "@/lib/jobs";
import { allow } from "@/lib/rate-limit";

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export type IntakeResult = "queued" | "invalid" | "limited" | "failed";

// Shared by the route handler and the server action. It never looks up the
// account, so known and unknown addresses take the same path and time.
export async function queuePasswordReset(input: unknown, source: string): Promise<IntakeResult> {
  if (typeof input !== "string") return "invalid";
  const email = input.trim();
  if (email.length > 254 || !EMAIL.test(email)) return "invalid";
  if (!allow(`reset:email:${email.toLowerCase()}`, 3) || !allow(`reset:source:${source}`, 20)) {
    return "limited";
  }
  try {
    await enqueue("password-reset", { email, idempotencyKey: crypto.randomUUID() });
    return "queued";
  } catch (error) {
    console.error("Could not queue password reset", error);
    return "failed";
  }
}

enqueue stands in for your job queue, such as a database table, a hosted queue or a workflow engine. Each job stores one random UUID as its Idempotency-Key, and every retry of that job reuses it. Two separate requests get two keys. The limits, 3 requests per address and 20 per source per hour, come from this example limiter:

// lib/rate-limit.ts
// Example only: an in-memory fixed window that works on a single server.
// In production, keep these counters in your database or cache.
const hits = new Map<string, { count: number; resetAt: number }>();

export function allow(key: string, limit: number, windowMs = 60 * 60 * 1000): boolean {
  const now = Date.now();
  const entry = hits.get(key);
  if (!entry || entry.resetAt <= now) {
    hits.set(key, { count: 1, resetAt: now + windowMs });
    return true;
  }
  entry.count += 1;
  return entry.count <= limit;
}

It keeps counts in memory, so it only works on a single server. In production, keep the counters in your database or cache, or use the limits your auth system already has.

The route handler turns each result into a status:

// app/api/password-reset/route.ts
import { queuePasswordReset } from "@/lib/reset-intake";

export async function POST(request: Request) {
  const body = (await request.json().catch(() => null)) as { email?: unknown } | null;
  const source = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
  const result = await queuePasswordReset(body?.email, source);

  if (result === "invalid") {
    return Response.json({ error: "Enter a valid email address" }, { status: 400 });
  }
  if (result === "limited") {
    return Response.json({ error: "Too many requests" }, { status: 429 });
  }
  if (result === "failed") {
    return Response.json({ error: "Try again in a minute" }, { status: 503 });
  }
  // Same response for known and unknown addresses: the lookup happens in the worker.
  return Response.json({ ok: true });
}

Known and unknown addresses get the same 200 at the same speed, because nothing in the request depends on the account. Read the client IP the way your host documents it: a client can set x-forwarded-for itself unless your proxy overwrites it.

Send the email from a background job

The worker looks up the account and sends:

// lib/emails.ts
import "server-only";
import { getLoops, requireEnv } from "@/lib/loops";
import { createPasswordReset } from "@/lib/password-reset";
import { sendWithRetry, type SendOutcome } from "@/lib/send-with-retry";

// Runs in your job worker, never in the request. Record the result. If it
// throws, let the queue retry the same job (same key), and alert on the last failure.
export async function processPasswordReset(job: {
  email: string;
  idempotencyKey: string;
}): Promise<SendOutcome | "no-account"> {
  const reset = await createPasswordReset(job.email);
  if (!reset) return "no-account";
  return sendWithRetry(() =>
    getLoops().sendTransactionalEmail({
      transactionalId: requireEnv("LOOPS_PASSWORD_RESET_ID"),
      email: job.email,
      dataVariables: { resetUrl: reset.url },
      headers: { "Idempotency-Key": job.idempotencyKey },
    }),
  );
}

createPasswordReset stands in for your token code. It should issue a random, expiring, single-use token and return null when no account matches. sendWithRetry is in the retries section below.

  • accepted means Loops accepted the request. Delivery shows up later in webhooks.

  • duplicate-key means the key was used in the last 24 hours. Check your send record before you treat the reset as sent.

  • A thrown error means the send failed or its outcome is unknown. Let the queue retry the job with the same key, and alert when it gives up. If an earlier attempt did go through, the retry gets a 409 instead of sending a second email.

Accept reset requests in a server action

If the request comes from a form, a server action can replace the route handler. It reads the source address from the request headers and calls the same intake:

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

import { headers } from "next/headers";
import { queuePasswordReset, type IntakeResult } from "@/lib/reset-intake";

export type ResetState = { message: string } | null;

const MESSAGES: Record<IntakeResult, string> = {
  queued: "If an account exists for that address, we will email reset instructions.",
  invalid: "Enter a valid email address.",
  limited: "Too many requests. Try again later.",
  failed: "Something went wrong. Try again in a minute.",
};

export async function requestPasswordReset(
  _previous: ResetState,
  formData: FormData,
): Promise<ResetState> {
  const source = (await headers()).get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
  const result = await queuePasswordReset(formData.get("email"), source);
  return { message: MESSAGES[result] };
}

The form is a Client Component. useActionState gives it the action’s return value and a pending flag, and lib/loops.ts never reaches the browser:

// app/reset-password/reset-form.tsx
"use client";

import { useActionState } from "react";
import { requestPasswordReset } from "@/app/actions";

export function ResetForm() {
  const [state, formAction, pending] = useActionState(requestPasswordReset, null);

  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" required />
      <button type="submit" disabled={pending}>
        {pending ? "Sending..." : "Send reset link"}
      </button>
      {state && <p role="status">{state.message}</p>}
    </form>
  );
}

Anyone can call a server action with a direct POST request, not only your form. That’s why validation and the limits live in queuePasswordReset, which both entry points share.

Create or update the contact at signup

You can send transactional email without creating a contact. By default the recipient isn’t added to your audience and adds no subscribed-contact charge. Sends still count toward the free plan’s email allowance, and suppressed addresses don’t receive mail. Create a contact when the user has agreed to campaigns and workflows:

// lib/contacts.ts
import "server-only";
import { getLoops } from "@/lib/loops";

export async function syncContact(user: {
  id: string;
  email: string;
  plan: string;
  createdAt: Date;
  marketingConsent: boolean;
}) {
  // New contacts are subscribed, so only sync users who agreed to marketing email.
  if (!user.marketingConsent) return;
  await getLoops().updateContact({
    email: user.email,
    userId: user.id,
    properties: { plan: user.plan, signedUpAt: user.createdAt.toISOString() },
  });
}

updateContact creates the contact when nothing matches and updates it otherwise, so calling it twice doesn’t make a duplicate. Pass userId, your own ID for the user, so you can change the contact’s email address later. The SDK sends properties as top-level fields. Create custom properties like plan and signedUpAt in Loops before you send them. signedUpAt comes from the stored account creation date, so a repeat sync doesn’t change it.

💡

New contacts get marketing email

Subscribed by default
A new contact can receive campaigns and workflows. The helper skips users without marketing consent.

Updates
Leave subscribed out unless you mean to change it. Setting it to true re-subscribes someone who opted out.

Double opt-in
Covers Loops forms only. To require confirmation, turn it on in Settings > Sending and add the contact through a Loops form. The Create contact and Update contact API skip that step. Double opt-in docs.

💡

New contacts get marketing email

Subscribed by default
A new contact can receive campaigns and workflows. The helper skips users without marketing consent.

Updates
Leave subscribed out unless you mean to change it. Setting it to true re-subscribes someone who opted out.

Double opt-in
Covers Loops forms only. To require confirmation, turn it on in Settings > Sending and add the contact through a Loops form. The Create contact and Update contact API skip that step. Double opt-in docs.

Start a workflow with sendEvent

Workflows are automated email sequences. Create one in Loops with the Event received trigger and an event name, publish it, then send that event from your app for users who opted in:

// lib/events.ts
import "server-only";
import { getLoops } from "@/lib/loops";
import { sendWithRetry, type SendOutcome } from "@/lib/send-with-retry";

export async function trackCompletedOnboarding(user: {
  id: string;
  email: string;
  marketingConsent: boolean;
  onboardingCompletedAt: Date;
}): Promise<SendOutcome | "skipped"> {
  // sendEvent creates the contact if it does not exist, and new contacts are subscribed.
  if (!user.marketingConsent) return "skipped";
  const completedAt = user.onboardingCompletedAt.toISOString();
  return sendWithRetry(() =>
    getLoops().sendEvent({
      email: user.email,
      userId: user.id,
      eventName: "completedOnboarding",
      eventProperties: { completedAt },
      headers: { "Idempotency-Key": `completed-onboarding-${user.id}` },
    }),
  );
}

sendEvent creates the contact if it doesn’t exist, and new contacts are subscribed, so the helper checks consent first. completedAt comes from the stored completion time, so a retry sends the same body. The key includes the user ID, so if your job runs twice within 24 hours, Loops accepts the event once. Keep the whole key within 100 characters. sendEvent needs an email or a userId, and the SDK throws ValidationError without making a request if both are missing.

Handle rate limits, retries and duplicates

On a normal success, the send methods resolve with the parsed JSON body. On failure they throw:

  • RateLimitExceededError for a 429. It carries limit and remaining from the x-ratelimit-limit and x-ratelimit-remaining headers, and both fall back to 10 when a header is missing.

  • APIError for other HTTP errors, with statusCode, json (the parsed body, or null) and rawBody when the body isn’t JSON.

  • ValidationError before any request, for example when updateContact or sendEvent gets neither email nor userId.

  • A network failure passes through as whatever fetch threw, usually a TypeError.

RateLimitExceededError doesn’t extend APIError, so a catch that only checks instanceof APIError misses 429s. This helper retries 429s with exponential backoff and reports a 409 as duplicate-key instead of success:

// lib/send-with-retry.ts
import { APIError, RateLimitExceededError } from "loops";

export type SendOutcome = "accepted" | "duplicate-key";

const MAX_ATTEMPTS = 4;

export async function sendWithRetry(send: () => Promise<unknown>): Promise<SendOutcome> {
  for (let attempt = 1; ; attempt++) {
    try {
      await send();
      return "accepted";
    } catch (error) {
      // 409: this Idempotency-Key was used in the last 24 hours. That alone does
      // not prove the earlier attempt sent, so check your own send record.
      if (error instanceof APIError && error.statusCode === 409) return "duplicate-key";
      if (!(error instanceof RateLimitExceededError) || attempt === MAX_ATTEMPTS) {
        throw error;
      }
      // 429: wait 0.5s, 1s, 2s, then give up and let the caller decide.
      await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** (attempt - 1)));
    }
  }
}

Against a stubbed fetch, two 429s and then a 200 made three requests with the same Idempotency-Key and waited 1.5 seconds in total. Four 429s in a row threw RateLimitExceededError, and a 409 returned duplicate-key.

💡

Rate limits

Sends and events
A shared baseline of 10 requests per second per team. Above that, the API returns 429 Too Many Requests, and Loops recommends retrying with exponential backoff.

Content API
A separate baseline of 60 requests per 60 seconds per team, for calls such as campaigns, email messages and transactional email management.

Per team
Every server and job using your team’s keys shares the limit.

Need more?
Contact Loops support about a higher limit.

💡

Rate limits

Sends and events
A shared baseline of 10 requests per second per team. Above that, the API returns 429 Too Many Requests, and Loops recommends retrying with exponential backoff.

Content API
A separate baseline of 60 requests per 60 seconds per team, for calls such as campaigns, email messages and transactional email management.

Per team
Every server and job using your team’s keys shares the limit.

Need more?
Contact Loops support about a higher limit.

💡

Idempotency keys last 24 hours

The header
Send an Idempotency-Key of up to 100 characters with sendTransactionalEmail or sendEvent. Reusing a key within 24 hours returns 409 Conflict.

After a 429 or a timeout
Back off and retry the same send with its original key.

After a 409
The key was used, but that doesn’t mean the earlier attempt sent. Check your own send record before you issue a new key.

After a 400 or 404
Read the message and fix the cause, then send the corrected request as a new attempt with a new key.

Storage
Store the key with the job’s payload, so every retry reuses both.

💡

Idempotency keys last 24 hours

The header
Send an Idempotency-Key of up to 100 characters with sendTransactionalEmail or sendEvent. Reusing a key within 24 hours returns 409 Conflict.

After a 429 or a timeout
Back off and retry the same send with its original key.

After a 409
The key was used, but that doesn’t mean the earlier attempt sent. Check your own send record before you issue a new key.

After a 400 or 404
Read the message and fix the cause, then send the corrected request as a new attempt with a new key.

Storage
Store the key with the job’s payload, so every retry reuses both.

Receive webhooks

Loops can POST events to your app for sends, deliveries, bounces, spam reports and contact changes. In Settings > Webhooks, enter your endpoint URL, save the signing secret as LOOPS_SIGNING_SECRET, and turn on the events you want. Each Loops account has one webhook endpoint.

This is the verification function from the Loops webhook docs, unchanged. It reads the webhook-id, webhook-timestamp and webhook-signature headers, rejects timestamps more than 5 minutes off, and compares an HMAC-SHA256 of the ID, timestamp and raw body with each v1 signature:

import crypto from 'node:crypto';

const SECRET_PREFIX = 'whsec_';
const TOLERANCE_SECONDS = 300;

export class WebhookVerificationError extends Error {
  constructor(
    message: string,
    readonly code:
      | 'MISSING_HEADERS'
      | 'MISSING_SECRET'
      | 'INVALID_TIMESTAMP'
      | 'INVALID_SIGNATURE',
  ) {
    super(message);
    this.name = 'WebhookVerificationError';
  }
}

function timingSafeEqual(a: string, b: string): boolean {
  const left = Buffer.from(a);
  const right = Buffer.from(b);
  if (left.length !== right.length) return false;
  return crypto.timingSafeEqual(left, right);
}

export function verifyWebhook({
  headers,
  rawBody,
  secret = process.env.LOOPS_SIGNING_SECRET,
}: {
  headers: Headers;
  rawBody: string;
  secret?: string;
}): void {
  if (!secret) {
    throw new WebhookVerificationError(
      'Missing LOOPS_SIGNING_SECRET environment variable',
      'MISSING_SECRET',
    );
  }

  const id = headers.get('webhook-id');
  const timestamp = headers.get('webhook-timestamp');
  const signatureHeader = headers.get('webhook-signature');

  if (!id || !timestamp || !signatureHeader) {
    throw new WebhookVerificationError(
      'Missing webhook-id, webhook-timestamp, or webhook-signature header',
      'MISSING_HEADERS',
    );
  }

  const ts = Number(timestamp);
  if (!Number.isFinite(ts)) {
    throw new WebhookVerificationError(
      'webhook-timestamp is not a valid number',
      'INVALID_TIMESTAMP',
    );
  }

  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - ts) > TOLERANCE_SECONDS) {
    throw new WebhookVerificationError(
      'webhook-timestamp is outside the allowed tolerance',
      'INVALID_TIMESTAMP',
    );
  }

  const encoded = secret.startsWith(SECRET_PREFIX)
    ? secret.slice(SECRET_PREFIX.length)
    : secret;
  const key = Buffer.from(encoded, 'base64');

  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.${rawBody}`)
    .digest('base64');

  const matched = signatureHeader.split(/\s+/).some((entry) => {
    const comma = entry.indexOf(',');
    if (comma === -1) return false;
    const version = entry.slice(0, comma);
    const value = entry.slice(comma + 1);
    return version === 'v1' && timingSafeEqual(value, expected);
  });

  if (!matched) {
    throw new WebhookVerificationError('Invalid signature', 'INVALID_SIGNATURE');
  }
}

The route handler from the same page goes in app/api/webhooks/route.ts:

import { NextRequest, NextResponse } from 'next/server';
import { verifyWebhook, WebhookVerificationError } from '@/lib/verify-webhook';

export async function POST(req: NextRequest) {
  const rawBody = await req.text();

  try {
    verifyWebhook({ headers: req.headers, rawBody });
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      const status =
        error.code === 'MISSING_SECRET'
          ? 500
          : error.code === 'INVALID_SIGNATURE' || error.code === 'INVALID_TIMESTAMP'
            ? 401
            : 400;
      return NextResponse.json({ message: error.message }, { status });
    }
    throw error;
  }

  const event = JSON.parse(rawBody);
  // process event...
  return NextResponse.json({ ok: true, eventName: event.eventName });
}

Your code goes where the route has the // process event comment. Write the event to durable storage with webhook-id as a unique key before the route returns 2xx, and return an error if the write fails, so Loops tries again.

For transactional email you’ll get transactional.email.sent, email.delivered, email.softBounced, email.hardBounced and email.spamReported. Loops doesn’t track opens or clicks on transactional email, so those events only fire for campaigns and workflows. Handle email.hardBounced on its own: Loops can also send contact.unsubscribed when a hard bounce unsubscribes a subscribed contact.

💡

Save the event, then answer

Verify before you parse
The signature covers the raw body, which is why the route reads it with req.text().

Save, then return 2xx
Save the event with webhook-id as a unique key, then return a 2xx within 15 seconds. If the save fails, return an error.

Retries
Anything other than 2xx counts as a failure. Loops makes up to eight attempts over about 28 hours.

Duplicates
The same event can arrive more than once. The unique key turns a repeat delivery into a no-op.

Shutoff
If every attempt fails for 5 days, Loops turns the endpoint off.

Secret rotation
After you roll the signing secret, the old one stays valid for 24 hours.

💡

Save the event, then answer

Verify before you parse
The signature covers the raw body, which is why the route reads it with req.text().

Save, then return 2xx
Save the event with webhook-id as a unique key, then return a 2xx within 15 seconds. If the save fails, return an error.

Retries
Anything other than 2xx counts as a failure. Loops makes up to eight attempts over about 28 hours.

Duplicates
The same event can arrive more than once. The unique key turns a repeat delivery into a no-op.

Shutoff
If every attempt fails for 5 days, Loops turns the endpoint off.

Secret rotation
After you roll the signing secret, the old one stays valid for 24 hours.

When to use SMTP instead

Use the SDK in code you write. Use SMTP when another tool sends the email through SMTP settings, such as Supabase Auth’s custom SMTP option or Nodemailer’s SMTP transport:

  • Host: smtp.loops.so

  • Port: 587

  • Username: loops

  • Password: a Loops API key

The message body isn’t HTML. It’s the same JSON as an API send, with transactionalId, email and dataVariables, converted to a string. Loops builds the email from your template.

💡

SMTP needs a transactional email too

Every email sent through Loops SMTP needs a transactional email set up in Loops, referenced by the transactionalId in the body. The template and data variable rules above still apply.

💡

SMTP needs a transactional email too

Every email sent through Loops SMTP needs a transactional email set up in Loops, referenced by the transactionalId in the body. The template and data variable rules above still apply.

Test without sending real email

  • Send to addresses at example.com or test.com. Loops returns normal success responses but delivers nothing, so you can run the whole flow without touching your domain’s sending reputation. A success here proves the API path, not inbox delivery.

  • Use a separate Loops team for each environment. Loops has no sandbox, so give development and staging their own team, domain and API key. getLoops().testApiKey() returns the team name for the key in use.

  • Send a test webhook from Settings > Webhooks. It arrives as testing.testEvent, so you can check the signature code end to end.

  • Type-check and build before you deploy:

npx next typegen
npx tsc --noEmit
npx next build

Run next typegen first on a clean checkout. It writes next-env.d.ts, which gives TypeScript the types for import “server-only”. Without that file, tsc 7.0.2 stopped with error TS2882 on the import in our test project.

To test retries without calling the API, replace globalThis.fetch with a stub that returns 429 or 409. That’s how the server-side snippets in this guide were run.

Deploy on Vercel or any Node.js host

Keep these routes on the Node.js runtime, the default for route handlers. The webhook verifier imports node:crypto and uses Buffer, and the Next.js docs mark the Edge runtime as deprecated, so leave out export const runtime. A static export can’t host server actions, so this setup needs a Next.js server.

Give each environment, such as Vercel’s Development, Preview and Production, the API key, transactional ID and signing secret of its own Loops team. On Vercel, a changed environment variable only applies to new deployments, so redeploy after you add or rotate one. Run the job worker wherever your queue runs, with the same variables. Then point each team’s webhook endpoint at that environment’s URL.

Common failure modes

  • Calling Loops from the browser. The request fails on CORS and puts the key in the bundle. Call Loops from trusted server code: route handlers, server actions or workers.

  • 400 or 404 on send. Read the message in the response. Check the key’s team, the transactionalId, that the email is published, the sending domain and the required data variables. A 404 can also mean the ID has no published version.

  • Data variable names. resetUrl and resetURL are different variables. In LMX the reference is {data.resetUrl}.

  • 401 Invalid API key. Loops rejected the key it received. If your logs say LOOPS_API_KEY is not set instead, the request never reached Loops: fix the server environment first.

  • A catch that misses 429s. RateLimitExceededError isn’t an APIError. Check for it first.

  • A 409 you didn’t expect. The key was used in the last 24 hours. Check whether the first attempt sent before you retry with a new key.

  • Webhook signature fails. Verify the raw body from req.text() before parsing, and check that LOOPS_SIGNING_SECRET matches Settings > Webhooks.

  • Wrong package. Install loops, the official package.

Keep going

Trigger onboarding sequences and trial nudges from product events with sendEvent, or point your coding agent at the Loops agents page. For the bigger picture, see transactional email on Loops.

Common questions

Is the Loops API safe to call from the browser?

No. Calls belong in trusted server code with the API key in a LOOPS_API_KEY environment variable. At build time, Next.js inlines any NEXT_PUBLIC_ variable your code references into the browser bundle, so never give the key that prefix.

Why isn’t my transactional email sending?

The usual causes: the template isn’t published (drafts can’t send), a data variable name doesn’t match exactly (they are case sensitive), or your sending domain isn’t verified yet.

Does updateContact create duplicate contacts?

No. updateContact upserts, so it creates a missing contact and updates a matching one. That makes it duplicate-safe, not consent-safe: API updates are not gated by double opt-in, and setting subscribed to true can re-subscribe someone who opted out. Only sync an Audience contact when the signup flow supports it, and omit subscribed to preserve an existing preference.

Does updateContact trigger double opt-in?

No. Loops double opt-in currently applies to Loops forms, not to Create contact or Update contact API calls. When a new marketing contact must confirm first, turn on double opt-in in Settings > Sending and add the contact through a Loops form.

What's next

More on sending transactional email.

See all guides