← back to Govarbitrage
src/app/api/newsletter/unsubscribe/route.ts
34 lines
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { buildUnsubscribeNoticeEmail, sendNewsletterEmail } from "@/lib/newsletter";
import { resultPage } from "../result-page";
export const dynamic = "force-dynamic";
// CAN-SPAM: single-click, no login, effective immediately.
export async function GET(req: NextRequest) {
const token = req.nextUrl.searchParams.get("token") || "";
if (!token) {
return resultPage(400, "Missing link", "This unsubscribe link is incomplete. Please use the link from your email.");
}
const sub = await prisma.subscriber.findUnique({ where: { unsubscribeToken: token } });
if (!sub) {
return resultPage(404, "Link not recognized", "This unsubscribe link is invalid. If you keep receiving emails, reply to any digest and we'll remove you manually.");
}
if (sub.status !== "UNSUBSCRIBED") {
await prisma.subscriber.update({
where: { id: sub.id },
data: { status: "UNSUBSCRIBED", unsubscribedAt: new Date() },
});
await sendNewsletterEmail(buildUnsubscribeNoticeEmail(sub.email));
}
return resultPage(
200,
"You're unsubscribed",
"You will receive no further digests. This took effect immediately. Changed your mind? You can re-subscribe any time at /newsletter.",
);
}