Skip to main content
Tutorials

Microsoft Safe Links is unsubscribing your readers before they ever click

If your unsubscribe page acts on load, corporate mail scanners empty your list. How to get it right in Next.js 16 with Resend and RFC 8058.

Israel Palma Sebastià

This blog belongs to CREA.MBA, a Next.js boilerplate with auth, payments and an admin panel already set up. See what's included

One of your subscribers works at a company on Microsoft 365. Your newsletter lands in their inbox, they never open it, and the next day they're gone from your list. Your dashboard says they unsubscribed. They didn't do anything.

Odds are a bot "clicked" your unsubscribe link. If your /unsubscribe page unsubscribes people the moment it loads, anything that follows links can remove your subscribers: their company's mail filter, a security product, a browser that prefetches pages.

CREA.MBA's unsubscribe page worked exactly like that until version 2.1.4 of the boilerplate, released on November 2. Here's what we changed and how to get it right in Next.js 16 with Resend.

Microsoft Defender for Office 365 ships Safe Links, and in licensed organizations it's on by default: the Built-in protection preset policy covers every mailbox that isn't in another policy. Microsoft's docs say two things that matter here:

  • As long as Safe Links is on, URLs are scanned before the message is delivered, whether they're rewritten or not.
  • URLs without a valid reputation are "detonated asynchronously in the background". In other words, they get visited.

An unsubscribe link with a per-subscriber token is the textbook URL with no reputation. And Microsoft isn't alone: other corporate mail gateways and some clients that build link previews do the same. None of them tell you, because from your server's point of view that visit is just another GET.

The one-click standard itself admits it. RFC 8058 (January 2017) exists because mail software sometimes fetches the URLs in mail headers and unsubscribes people by accident, and the sender has no way to tell that request from a human one.

The rule: a GET never unsubscribes

The fix is simple to state: opening the page changes nothing. Unsubscribing takes a POST, and that POST only happens after a deliberate action.

There are two ways to reach that POST, and you want both:

  1. The footer link. It goes to a page that asks "Unsubscribe from X's newsletter?" and shows a button. The button sends the POST. A scanner that opens the link only sees the question.
  2. The mail client's one-click unsubscribe (RFC 8058). Gmail and other clients show an "Unsubscribe" option next to the sender. When the reader uses it, the client itself POSTs to a URL you put in the message headers. There's no confirmation step here: the RFC says it has to work without a landing page, because the mail client isn't going to read one.

Scanners don't trigger the second path because it isn't a link to follow. It's a header the client uses to send a POST, and the RFC forbids doing so without the user's consent.

It's also not optional at volume. Resend's docs point out that Gmail and Yahoo require one-click unsubscribe from anyone sending more than 5,000 messages a day to their users, and that the unsubscribe has to take effect within 48 hours.

What RFC 8058 asks for

The rules first, because there aren't many and they're strict:

  • List-Unsubscribe must contain one HTTPS URL, in angle brackets.
  • List-Unsubscribe-Post must contain exactly List-Unsubscribe=One-Click.
  • The message must carry a DKIM signature that covers both headers.
  • The POST arrives with no cookies and no auth. Whatever you need to know who's unsubscribing has to be in the URL.
  • The response must not be a redirect.

In practice: the header URL carries the email address and a signed token. With only the email, anyone could unsubscribe anyone else with a single curl.

Step 1: the token

An HMAC of the email with a server-side secret. Nothing to store in the database.

// lib/unsubscribe.ts
import { createHmac, timingSafeEqual } from 'node:crypto';

const secret = process.env.UNSUBSCRIBE_SECRET ?? '';

export function unsubscribeToken(email: string): string {
  return createHmac('sha256', secret).update(email).digest('hex');
}

export function verifyUnsubscribeToken(email: string, token: string): boolean {
  if (!secret) return false; // with an empty key, anyone can compute the HMAC
  const expected = unsubscribeToken(email);
  if (expected.length !== token.length) return false;
  return timingSafeEqual(Buffer.from(expected), Buffer.from(token));
}

export function unsubscribeLinks(email: string, locale: string) {
  const base = process.env.NEXT_PUBLIC_SITE_URL;
  const query = new URLSearchParams({ email, token: unsubscribeToken(email) });
  return {
    pageUrl: `${base}/${locale}/unsubscribe?${query}`,
    oneClickUrl: `${base}/api/unsubscribe?${query}`,
  };
}

Two details. timingSafeEqual keeps the token from being guessed by measuring response times. And the if (!secret) line isn't paranoia: an HMAC with an empty key is something anyone can compute, so without a secret no token is trusted. The boilerplate had exactly that hole until 2.1.3.

Step 2: headers when sending with Resend

resend.emails.send() takes a headers object for custom headers:

import { Resend } from 'resend';
import { unsubscribeLinks } from '@/lib/unsubscribe';

const resend = new Resend(process.env.RESEND_API_KEY);

export async function sendNewsletter(email: string, locale: string) {
  const { pageUrl, oneClickUrl } = unsubscribeLinks(email, locale);

  return resend.emails.send({
    from: 'YourApp ',
    to: email,
    subject: "What's new this month",
    react: NewsletterEmail({ unsubscribeUrl: pageUrl }),
    headers: {
      'List-Unsubscribe': `<${oneClickUrl}>`,
      'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
    },
  });
}

Note the two different URLs. The footer points to the page (pageUrl), which asks. The header points to the endpoint (oneClickUrl), which only accepts POST. Use the same URL for both and either the page unsubscribes on GET (back to square one) or the one-click request gets an HTML page.

The angle brackets aren't decoration either: RFC 2369, which defines List-Unsubscribe, wraps the URLs in them.

Step 3: the one-click endpoint

A route handler that only exports POST:

// app/api/unsubscribe/route.ts
import { NextRequest } from 'next/server';
import { verifyUnsubscribeToken } from '@/lib/unsubscribe';
import { unsubscribe } from '@/lib/newsletter';

export async function POST(request: NextRequest) {
  const email = request.nextUrl.searchParams.get('email');
  const token = request.nextUrl.searchParams.get('token');

  if (!email || !token || !verifyUnsubscribeToken(email, token)) {
    return new Response(null, { status: 403 });
  }

  await unsubscribe(email);
  return new Response(null, { status: 200 });
}

With no GET export, Next.js answers 405 Method Not Allowed to anything that opens the URL. A scanner gets nowhere.

The email and token come from the query string, not the body. The mail client sends List-Unsubscribe=One-Click as the body and nothing else, so everything else has to live in the URL.

This has to be a route handler, not a Server Action. Server Actions can only be called from your own app: they use Next.js's own protocol and check the Origin header against Host. Gmail sends neither. For the same reason, if your proxy.ts (formerly middleware) validates the origin of POST requests, exempt this route; the token is the proof here. We had to do it in the boilerplate, because in production the proxy was rejecting one-click POSTs with a 403.

Step 4: the page that asks

The page checks the token when it renders, but writes nothing. The unsubscribe happens in a Server Action bound to the form:

// app/[locale]/unsubscribe/page.tsx
import { verifyUnsubscribeToken } from '@/lib/unsubscribe';
import { confirmUnsubscribe } from './actions';

type Props = {
  params: Promise<{ locale: string }>;
  searchParams: Promise<{ email?: string; token?: string; done?: string }>;
};

export default async function UnsubscribePage({ params, searchParams }: Props) {
  const { locale } = await params;
  const { email, token, done } = await searchParams;

  if (done) return <p>Done. You won't get any more newsletter emails.</p>;

  if (!email || !token || !verifyUnsubscribeToken(email, token)) {
    return <p>This link isn't valid.</p>;
  }

  const confirm = confirmUnsubscribe.bind(null, locale, email, token);

  return (
    
      <h1>Unsubscribe from the newsletter?</h1>
      <p>You'll stop receiving emails at {email}.</p>
      Confirm unsubscribe
    
  );
}

If you have cacheComponents turned on, like the boilerplate does, add a loading.tsx to that folder: the page reads searchParams, so Next requires a `` boundary above it.

// app/[locale]/unsubscribe/actions.ts
'use server';

import { redirect } from 'next/navigation';
import { verifyUnsubscribeToken } from '@/lib/unsubscribe';
import { unsubscribe } from '@/lib/newsletter';

export async function confirmUnsubscribe(locale: string, email: string, token: string) {
  if (!verifyUnsubscribeToken(email, token)) return;
  await unsubscribe(email);
  redirect(`/${locale}/unsubscribe?done=1`);
}

Three things that are easy to skip:

  • The action checks the token again. The Next.js docs are explicit: Server Functions can be reached with a direct POST, not just through your UI. The page having checked it doesn't protect you.
  • bind instead of hidden inputs. Per the docs, it works in Server Components and supports progressive enhancement, so the button works even with JavaScript off.
  • No side effects during render. The Next.js 16 data security guide uses this as its "don't" example: a mutation triggered as a side effect of rendering. An unsubscribe page that unsubscribes on load is exactly that.

Could a scanner press the button? Link-following scanners send GETs; they don't submit forms. A more aggressive sandbox might, which is why the action never fires on load, not even from client-side JavaScript. It's the same line the RFC draws: automation doesn't unsubscribe anyone; a person pressing something does.

How to check it

  • curl -i on your one-click URL should return 405. With -X POST, a 200.
  • Open the footer link in a private window and reload a few times. The subscriber should still be on the list until you press the button.
  • In Gmail, open the message with Show original and find the DKIM-Signature header. Its h= field lists the signed headers, and List-Unsubscribe and List-Unsubscribe-Post need to be there. If they're missing, you're not RFC-compliant even though the headers arrive.

What the boilerplate already handles

CREA.MBA has shipped all of this since 2.1.4: the HMAC token, the confirmation page, the one-click endpoint exempt from the proxy's origin check, and the headers on the newsletter welcome email, all built by a single buildUnsubscribeLinks(). The endpoint also caps failed attempts at 10 per hour per IP, but never blocks a valid token: mail providers send every one-click request from a handful of shared IPs, and a per-IP limit would end up refusing real unsubscribes. There are tests for the three behaviors that matter: opening the page doesn't unsubscribe, the button does, and the mail client's POST works without confirmation.

If your project already has an unsubscribe page, try this today: open it with a valid link and check whether the subscriber is still on the list. Are they?

EmailResendNext.jsNewsletterSecurity

Enjoyed this article?

Subscribe for more tutorials and tips on building products with AI