# Send Scheduled Emails and Reminders from Next.js

Schedule one-off reminders like "your trial ends in 2 days", cancel them when plans change, and send a daily digest to users who opted in, from a recurring job that calls a signed Next.js route.

*Intermediate · 30 min · Updated Nov 18, 2026*

## What you'll build

- A trial-ending reminder scheduled days ahead with one API call
- Cancelling that reminder when the user upgrades
- A daily digest sent by a recurring job to users who opted in
- A route handler that checks the job's signature, survives retries and handles 429s
- A one-click way to turn the digest off

## Before you start

- A Next.js 16 app using the App Router, deployed at a public URL
- A Postgres `users` table with Drizzle, as in [Postgres with Next.js and Drizzle](https://cloudhike.dev/guides/postgres-nextjs-drizzle)
- The `sendEmail()` helper from [How to Send Email from Next.js](https://cloudhike.dev/guides/send-email-nextjs)

## One-off reminders vs. recurring emails

Next.js has no built-in scheduler, and serverless functions stop when the request ends. So "send this later" has to live somewhere else. CloudHike gives you two tools for it:

| Need | Use | Why |
| --- | --- | --- |
| One email at a known time, such as a trial reminder | `scheduledAt` on Email `/send` | One call now. Cancel it by id if plans change. Up to 7 days ahead. |
| The same work every day or hour, such as a digest | A Jobs **schedule** that calls your route | Cron syntax, time zones, signed requests and retries |
| Slow work started by a user | A Jobs **run** | See [Background Jobs in Next.js](https://cloudhike.dev/guides/background-jobs-nextjs) |

> **Warning:** CloudHike Email is for transactional mail only. A trial reminder or a digest the user turned on is fine. A promo blast to everyone on your list is not. Send digests only to people who opted in, include a way to turn them off, and skip users with nothing new. See the [email policy and limits](https://cloudhike.dev/docs/email#how-it-works).

## Step 1: Deploy Email and Jobs, and add columns

1. In your CloudHike project, deploy **Email** (accept the email policy) and **Jobs**.
2. Click **Copy as .env** and paste the values into `.env.local`.
3. Add `APP_URL` and a random `UNSUBSCRIBE_SECRET` (`openssl rand -hex 32`).

*.env.local*

```bash
EMAIL_API_URL=https://...
EMAIL_API_KEY=...
JOBS_API_URL=https://...
JOBS_API_KEY=...
APP_URL=https://your-app.example.com
UNSUBSCRIBE_SECRET=...
```

Add four columns to your users table: when the trial ends, the id of the scheduled reminder, whether the user wants the digest, and when they last got one.

*db/schema.ts*

```ts
import { boolean, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";

export const users = pgTable("users", {
  id: uuid("id").primaryKey().defaultRandom(),
  email: text("email").notNull().unique(),
  name: text("name").notNull(),
  plan: text("plan").notNull().default("trial"),
  trialEndsAt: timestamp("trial_ends_at", { withTimezone: true }),
  trialReminderEmailId: text("trial_reminder_email_id"),
  digestOptIn: boolean("digest_opt_in").notNull().default(false),
  lastDigestAt: timestamp("last_digest_at", { withTimezone: true }),
});
```

```bash
npx drizzle-kit push
```

## Step 2: Add scheduling and cancelling to the email helper

Add `scheduledAt` to the helper's input, and a `cancelEmail()` function. A scheduled send answers `202`, and each result carries the message `id` you cancel with.

*lib/email.ts*

```ts
import "server-only";

type Email = {
  to: string;
  subject: string;
  html?: string;
  text?: string;
  replyTo?: string;
  fromName?: string;
  scheduledAt?: string; // ISO time, up to 7 days ahead
};

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

const headers = () => ({
  "content-type": "application/json",
  "x-api-key": process.env.EMAIL_API_KEY!,
});

export async function sendEmail(email: Email) {
  const res = await fetch(`${process.env.EMAIL_API_URL}/send`, {
    method: "POST",
    headers: headers(),
    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 }[] };
}

export async function cancelEmail(id: string) {
  const res = await fetch(`${process.env.EMAIL_API_URL}/emails/${encodeURIComponent(id)}/cancel`, {
    method: "POST",
    headers: headers(),
  });
  // Not ok usually means it already went out. Log it rather than failing the caller.
  if (!res.ok) console.warn("Could not cancel email", id, res.status);
  return res.ok;
}

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

The `to` field takes one address here on purpose. Reminders and digests are personal, and each recipient counts as one email anyway. Putting many users in one `to` would also show them each other's addresses.

## Step 3: Schedule a trial-ending reminder

When a 7-day trial starts, schedule the reminder for 2 days before it ends. That is 5 days ahead, inside the 7-day window. Save the returned id so you can cancel it.

*lib/trial-reminder.ts*

```ts
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { users } from "@/db/schema";
import { cancelEmail, escapeHtml, sendEmail } from "@/lib/email";

const DAY = 24 * 60 * 60 * 1000;
const MAX_AHEAD = 7 * DAY - 5 * 60 * 1000; // stay a little inside the 7-day limit

type TrialUser = { id: string; email: string; name: string; trialEndsAt: Date };

export async function scheduleTrialReminder(user: TrialUser) {
  const sendAt = new Date(user.trialEndsAt.getTime() - 2 * DAY);
  const ahead = sendAt.getTime() - Date.now();
  // Too soon to bother, or too far ahead to schedule yet.
  if (ahead < 5 * 60 * 1000 || ahead > MAX_AHEAD) return null;

  const endDate = user.trialEndsAt.toLocaleDateString("en-US", { month: "long", day: "numeric" });
  const upgradeUrl = `${process.env.APP_URL}/billing`;

  const { results } = await sendEmail({
    to: user.email,
    subject: `Your trial ends on ${endDate}`,
    scheduledAt: sendAt.toISOString(),
    replyTo: "support@example.com",
    text: `Hi ${user.name},\n\nYour free trial ends on ${endDate}. Pick a plan to keep your data and settings: ${upgradeUrl}\n\nQuestions? Just reply.`,
    html: `<p>Hi ${escapeHtml(user.name)},</p><p>Your free trial ends on <strong>${endDate}</strong>. Pick a plan to keep your data and settings.</p><p><a href="${upgradeUrl}">Choose a plan</a></p><p>Questions? Just reply.</p>`,
  });

  const id = results[0]?.id ?? null;
  await db.update(users).set({ trialReminderEmailId: id }).where(eq(users.id, user.id));
  return id;
}

export async function cancelTrialReminder(userId: string) {
  const [user] = await db
    .select({ id: users.trialReminderEmailId })
    .from(users)
    .where(eq(users.id, userId));
  if (!user?.id) return;
  await cancelEmail(user.id);
  await db.update(users).set({ trialReminderEmailId: null }).where(eq(users.id, userId));
}
```

Call it right after the user is created. `after()` from `next/server` runs it once the response is sent, so sign-up stays fast:

*app/signup/actions.ts*

```ts
"use server";

import { after } from "next/server";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { users } from "@/db/schema";
import { scheduleTrialReminder } from "@/lib/trial-reminder";

export async function signUp(form: FormData) {
  const email = String(form.get("email") ?? "").trim().toLowerCase();
  const name = String(form.get("name") ?? "").trim() || "there";

  const [user] = await db
    .insert(users)
    .values({ email, name, trialEndsAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) })
    .returning();

  after(() => scheduleTrialReminder({ ...user, trialEndsAt: user.trialEndsAt! }).catch(console.error));
  redirect("/dashboard");
}
```

When the user upgrades, for example in your Stripe webhook, cancel the reminder so they don't get a nag after paying:

*In your upgrade or payment webhook*

```ts
await db.update(users).set({ plan: "pro" }).where(eq(users.id, userId));
await cancelTrialReminder(userId);
```

> **Note:** Longer trial? A 30-day trial can't be scheduled on day one. Let the daily job from the next step look for trials ending within the window that have no `trialReminderEmailId` yet, and schedule them then.

## Step 4: Write the daily digest route

A Jobs schedule calls a URL. Here that URL is a route handler in your app. Every request from Jobs carries an `x-cloudhike-signature` header, so the route first checks it and refuses anyone else.

*lib/jobs-signature.ts*

```ts
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";

// x-cloudhike-signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
export function verifyJobSignature(body: string, header: string | null) {
  const parts = Object.fromEntries((header ?? "").split(",").map((p) => p.split("=")));
  const t = Number(parts.t);
  if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false;
  const expected = createHmac("sha256", process.env.JOBS_API_KEY!).update(`${t}.${body}`).digest("hex");
  return expected.length === parts.v1?.length && timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
}
```

The route then finds opted-in users who haven't had a digest in the last 20 hours. It **claims** each user by setting `lastDigestAt` in the same update that checks it. If Jobs retries the request, or two runs overlap, a user can only be claimed once, so nobody gets two digests.

*app/api/cron/daily-digest/route.ts*

```ts
import { and, eq, isNull, lt, or } from "drizzle-orm";
import { db } from "@/lib/db";
import { users } from "@/db/schema";
import { buildDigest } from "@/lib/digest";
import { EmailError, sendEmail } from "@/lib/email";
import { verifyJobSignature } from "@/lib/jobs-signature";

export const maxDuration = 300; // seconds, if your host supports it

const BATCH = 200;
const BUDGET_MS = 240_000; // stop early and answer before the timeout
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

export async function POST(request: Request) {
  const body = await request.text();
  if (!verifyJobSignature(body, request.headers.get("x-cloudhike-signature"))) {
    return new Response("bad signature", { status: 401 });
  }

  const started = Date.now();
  const cutoff = new Date(started - 20 * 60 * 60 * 1000);
  const notRecent = or(isNull(users.lastDigestAt), lt(users.lastDigestAt, cutoff));

  const due = await db
    .select({ id: users.id, email: users.email, name: users.name, lastDigestAt: users.lastDigestAt })
    .from(users)
    .where(and(eq(users.digestOptIn, true), notRecent))
    .limit(BATCH);

  let sent = 0;
  let empty = 0;
  let stoppedBy: string | null = null;

  for (const user of due) {
    if (Date.now() - started > BUDGET_MS) {
      stoppedBy = "time";
      break;
    }

    // Claim the user. Zero rows back means another run already did.
    const [claimed] = await db
      .update(users)
      .set({ lastDigestAt: new Date() })
      .where(and(eq(users.id, user.id), notRecent))
      .returning({ id: users.id });
    if (!claimed) continue;

    const digest = await buildDigest(user);
    if (!digest) {
      empty++; // nothing new: don't send an empty email
      continue;
    }

    try {
      await sendWithRetry({ to: user.email, ...digest });
      sent++;
    } catch (err) {
      // Give the claim back so a later run tries this user again.
      await db.update(users).set({ lastDigestAt: user.lastDigestAt }).where(eq(users.id, user.id));

      if (err instanceof EmailError && err.status === 429) {
        stoppedBy = "rate-limit"; // still limited: let a later run continue
        break;
      }
      console.error("Digest failed for", user.id, err);
    }
  }

  return Response.json({ due: due.length, sent, empty, stoppedBy });
}

// On a short 429, wait as long as Retry-After says and try once more.
async function sendWithRetry(email: Parameters<typeof sendEmail>[0]) {
  try {
    return await sendEmail(email);
  } catch (err) {
    const wait = err instanceof EmailError && err.status === 429 ? (err.retryAfter ?? 60) : null;
    if (wait === null || wait > 30) throw err;
    await sleep(wait * 1000);
    return sendEmail(email);
  }
}
```

`buildDigest()` is your own logic. Return `null` when there is nothing worth sending:

*lib/digest.ts*

```ts
import "server-only";
import { escapeHtml } from "@/lib/email";
import { unsubscribeUrl } from "@/lib/unsubscribe";

type DigestUser = { id: string; name: string };

export async function buildDigest(user: DigestUser) {
  // Replace with your own query, e.g. new comments or tasks due since yesterday.
  const items: { title: string; url: string }[] = await loadYesterdaysActivity(user.id);
  if (items.length === 0) return null;

  const off = unsubscribeUrl(user.id);
  return {
    subject: `Your daily summary: ${items.length} update${items.length === 1 ? "" : "s"}`,
    text: [
      `Hi ${user.name}, here is what happened yesterday:`,
      ...items.map((i) => `- ${i.title}: ${i.url}`),
      `\nTurn off the daily summary: ${off}`,
    ].join("\n"),
    html: `<p>Hi ${escapeHtml(user.name)}, here is what happened yesterday:</p><ul>${items
      .map((i) => `<li><a href="${i.url}">${escapeHtml(i.title)}</a></li>`)
      .join("")}</ul><p style="color:#71717a;font-size:13px"><a href="${off}">Turn off the daily summary</a></p>`,
  };
}

async function loadYesterdaysActivity(_userId: string): Promise<{ title: string; url: string }[]> {
  return []; // your query here
}
```

> **Warning:** Digests use the same project email allowance as password resets and receipts. If a digest run uses it all up, your critical mail gets `429` too. Keep `BATCH` sensible for your plan, check the [email limits](https://cloudhike.dev/docs/email#limits), and skip users with nothing new.

## Step 5: Create the recurring schedule

You can create the schedule in the dashboard under **Jobs → Manage → Schedules**, or from a one-off script. This one runs every 30 minutes from 8:00 to 10:30 in New York. The first run sends most digests. Later runs pick up anyone left over after a timeout or a `429`, and find nothing left to do on a normal day.

*scripts/create-digest-schedule.ts*

```ts
async function main() {
  const res = await fetch(`${process.env.JOBS_API_URL}/schedules`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.JOBS_API_KEY!,
    },
    body: JSON.stringify({
      name: "Daily digest",
      cron: "*/30 8-10 * * *",
      timezone: "America/New_York",
      url: `${process.env.APP_URL}/api/cron/daily-digest`,
      method: "POST",
      retries: 2,
    }),
  });

  if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
  console.log(await res.json()); // includes the schedule id and nextRunAt
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

```bash
npx tsx --env-file=.env.local scripts/create-digest-schedule.ts
```

- The URL must be public. Jobs refuses `localhost`, so create the schedule after you deploy.
- If the previous run is still going when a time comes due, that time is skipped. Runs can start up to about a minute late.
- Pause it with `PATCH {JOBS_API_URL}/schedules/<id>` and `{ "enabled": false }`. See [Recurring schedules](https://cloudhike.dev/docs/jobs#schedules) for every field.
- Check how often your plan lets a schedule run in the [Jobs limits](https://cloudhike.dev/docs/jobs#limits).

To test locally, sign a request yourself the same way Jobs does and post it to your dev server:

*scripts/trigger-digest.ts*

```ts
import { createHmac } from "node:crypto";

async function main() {
  const body = "";
  const t = Math.floor(Date.now() / 1000);
  const v1 = createHmac("sha256", process.env.JOBS_API_KEY!).update(`${t}.${body}`).digest("hex");

  const res = await fetch("http://localhost:3000/api/cron/daily-digest", {
    method: "POST",
    headers: { "x-cloudhike-signature": `t=${t},v1=${v1}` },
    body,
  });
  console.log(res.status, await res.text());
}

main().catch(console.error);
```

```bash
npx tsx --env-file=.env.local scripts/trigger-digest.ts
```

## Step 6: Let users turn the digest on and off

The digest is off by default and the user turns it on in settings. Each digest also carries a signed link that turns it off in one click, with no sign-in needed.

*lib/unsubscribe.ts*

```ts
import "server-only";
import { createHmac, timingSafeEqual } from "node:crypto";

const sign = (userId: string) =>
  createHmac("sha256", process.env.UNSUBSCRIBE_SECRET!).update(`digest:${userId}`).digest("hex");

export function unsubscribeUrl(userId: string) {
  return `${process.env.APP_URL}/unsubscribe?u=${encodeURIComponent(userId)}&sig=${sign(userId)}`;
}

export function checkUnsubscribe(userId: string, sig: string) {
  const expected = sign(userId);
  return sig.length === expected.length && timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
}
```

Some mail security scanners open every link in an email. So the link shows a page with a button, and only the button's Server Action changes anything:

*app/unsubscribe/page.tsx*

```tsx
import { eq } from "drizzle-orm";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { users } from "@/db/schema";
import { checkUnsubscribe } from "@/lib/unsubscribe";

async function turnOff(form: FormData) {
  "use server";
  const u = String(form.get("u") ?? "");
  const sig = String(form.get("sig") ?? "");
  if (!checkUnsubscribe(u, sig)) throw new Error("Invalid link");
  await db.update(users).set({ digestOptIn: false }).where(eq(users.id, u));
  redirect("/unsubscribe?done=1");
}

export default async function UnsubscribePage({ searchParams }: { searchParams: Promise<{ u?: string; sig?: string; done?: string }> }) {
  const { u = "", sig = "", done } = await searchParams;
  if (done) return <p className="p-8">Done. You won't get the daily summary anymore. You can turn it back on in settings.</p>;
  if (!u || !sig || !checkUnsubscribe(u, sig)) return <p className="p-8">This link is not valid.</p>;

  return (
    <form action={turnOff} className="grid max-w-sm gap-3 p-8">
      <p>Stop sending me the daily summary email?</p>
      <input type="hidden" name="u" value={u} />
      <input type="hidden" name="sig" value={sig} />
      <button>Turn it off</button>
    </form>
  );
}
```

The settings toggle is a plain Server Action that updates `digestOptIn` for the signed-in user. Always read the user id from the session, never from the form.

## Production checklist

- Add all six environment variables to your host, and keep `JOBS_API_KEY` and `EMAIL_API_KEY` server-only.
- Create the schedule only after the route is deployed at its public URL.
- Check the run history under Jobs in the dashboard after the first morning. A `401` there means the signature check failed.
- Send digests only to users who opted in, include the off link in every one, and never send empty digests.
- Handle `429` by reading `Retry-After`, and leave room in your email allowance for resets and receipts. See [Email limits](https://cloudhike.dev/docs/email#limits) and the [pricing page](https://cloudhike.dev/pricing).
- Cancel scheduled reminders when the reason for them goes away: an upgrade, a cancelled account or a deleted user.
- Send from your own [verified domain](https://cloudhike.dev/docs/email#domains) so reminders don't look like spam.

## FAQ

### How do I schedule an email to send later in Next.js?

Next.js can't wait in the background after a request ends, so let the email API hold it. With CloudHike Email, add scheduledAt with an ISO time up to 7 days ahead to your send call. Keep the returned id if you might need to cancel it.

### Can I cancel a scheduled email?

Yes, until it has been sent. Call POST on EMAIL_API_URL/emails/<id>/cancel with your API key, using the id from the original send. Cancelled messages aren't charged.

### How do I run a cron job in Next.js?

Put the work in a route handler, then have an outside scheduler call it. A CloudHike Jobs schedule takes a cron expression and a time zone, calls your URL each time it comes due, and signs each request so your route can refuse anyone else.

### What if my digest job runs twice?

Jobs deliver at least once, and retries can repeat a request. Make the route safe to repeat: claim each user in the same database update that checks when they last got a digest, so a second run finds nothing to do for them.

### Can I send a weekly newsletter with this?

Not on a transactional sender. A digest of activity the user asked for is transactional, but a marketing newsletter to your whole list is not allowed and hurts deliverability. Use a dedicated newsletter tool for that.
