Website Change Alerts in a Next.js Route Handler
Receive AyeWatch website change alerts in a Next.js App Router route handler. Read the raw body, verify the HMAC, store each update_id once in Postgres and run slow work with after().
By AyeWatch Team4 min read
Short answer: To receive website change alerts in Next.js, add app/api/ayewatch/route.ts with a POST function that reads await request.arrayBuffer(), verifies X-AyeWatch-Signature with timingSafeEqual, inserts the update_id with ON CONFLICT DO NOTHING, and returns 200. Put slow follow-ups in after() so the reply stays inside AyeWatch's 10 seconds.
Why a route handler, and the one rule
If your product already runs on Next.js, the alert can land in the same codebase and database as everything else: a route handler is a POST function exported from app/api/.../route.ts. Route handlers run on the Node.js runtime by default, so node:crypto is available.
The one rule: read the body as bytes. request.json() parses the body, and once it is parsed you cannot get the exact bytes back. Read request.arrayBuffer(), verify, then parse.
The route
Sample rule: Alert me when Fieldstone Software's pricing page changes a plan price, a seat limit or the free tier. Ignore testimonials and FAQ edits.
// app/api/ayewatch/route.ts
import crypto from "node:crypto";
import { after } from "next/server";
import { Pool } from "pg";
type Alert = {
update_id: number;
topic_id: number;
topic_name: string;
headline?: string;
content?: string;
created_at: string;
};
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export async function POST(request: Request) {
// 1. Raw body
const raw = Buffer.from(await request.arrayBuffer());
// 2. Signature, compared in constant time
const expected = Buffer.from(
"sha256=" + crypto.createHmac("sha256", process.env.AYEWATCH_SECRET!).update(raw).digest("hex")
);
const got = Buffer.from(request.headers.get("x-ayewatch-signature") ?? "");
if (got.length !== expected.length || !crypto.timingSafeEqual(got, expected)) {
return new Response("Bad signature", { status: 401 });
}
// 3. Dedupe and store: the primary key turns a retry into a no-op
const alert = JSON.parse(raw.toString("utf8")) as Alert;
const result = await pool.query(
"INSERT INTO ayewatch_alerts (update_id, topic_id, topic_name, headline, content, created_at) " +
"VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (update_id) DO NOTHING",
[alert.update_id, alert.topic_id, alert.topic_name, alert.headline ?? null, alert.content ?? null, alert.created_at]
);
if (result.rowCount === 0) return new Response("Already handled");
// 5. Slow follow-ups run after the reply
after(() => openTicket(alert));
// 4. Answer well inside 10 seconds
return new Response("ok");
}
async function openTicket(alert: Alert) {
await fetch(process.env.HELPDESK_URL!, {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: "Bearer " + process.env.HELPDESK_TOKEN },
body: JSON.stringify({ subject: alert.headline ?? alert.topic_name, body: alert.content ?? "" }),
});
}
The table:
CREATE TABLE ayewatch_alerts (
update_id bigint PRIMARY KEY,
topic_id bigint NOT NULL,
topic_name text NOT NULL,
headline text,
content text,
created_at timestamptz NOT NULL,
received_at timestamptz NOT NULL DEFAULT now()
);
The insert is the main action, and it doubles as the dedupe. Your app reads the table for an in-product feed, a dashboard or a nightly report.
What after() does here
after from next/server has been stable since Next.js 15.1 and works in route handlers. It runs the callback once the response is sent. On serverless hosts it keeps the function alive for the callback, up to the route's maximum duration, which you can raise with export const maxDuration where your host allows it.
The trade-off: AyeWatch already has its 200, so if openTicket fails, AyeWatch will not retry. The row is stored, though. Add a ticketed_at column and a small job that picks up rows where it is still empty if the ticket must exist.
Redirects: the silent failure
AyeWatch never follows a redirect, and a 3xx fails the delivery at once with no retry. Next.js apps produce redirects in three common places:
- Auth middleware or proxy. A matcher that sends signed-out requests to
/logincatches the webhook too. Exclude/api/ayewatchfrom the matcher. trailingSlash: trueinnext.config. Requests without the slash get a 308. Paste the URL with the trailing slash.- Domain redirects. If the host sends
example.comtowww.example.com, paste thewwwaddress.
Test the exact URL with curl -i -X POST before you save it. Without a valid signature you should see 401. A 3xx means AyeWatch will fail too.
Limits and cost
- Connection pools on serverless. Each instance opens its own pool. Use your database's pooler URL for
DATABASE_URL. - One webhook per account. Branch on
topic_idinside the route if monitors need different handling. - Edge runtime. This route uses
node:cryptoandpg, so keep it on the default Node.js runtime. - Public pages only. AyeWatch reads public pages and cannot sign in.
AyeWatch Pro is $9/mo with 50 topics and hourly checks; Pro+ is $19/mo with 200 topics and ASAP mode. Every plan starts with a 7-day free trial. Ten competitor pricing pages, in separate web page monitors checked daily, use 10 × 30 = 300 credits a month on Pro.
Ship it
- Create the table and add
app/api/ayewatch/route.tsfrom above. - Set
DATABASE_URL,HELPDESK_URLandHELPDESK_TOKEN, then deploy. - Run
curl -i -X POST https://www.yourapp.example/api/ayewatchand confirm a 401, not a 3xx. - In AyeWatch, open Notification settings, Webhook, paste the URL and select Save Webhook. Reveal and copy the signing secret.
- Set
AYEWATCH_SECRETand redeploy. - Wait for a real update and check that a row appears.
| Step | Next.js code | Note |
|---|---|---|
| Raw body | await request.arrayBuffer() | Not request.json() |
| Signature | createHmac plus timingSafeEqual | Check lengths first |
| Dedupe | INSERT ... ON CONFLICT DO NOTHING | rowCount 0 means a repeat |
| Reply | return new Response("ok") | Inside 10 seconds |
| Slow work | after(() => ...) | Not retried by AyeWatch if it fails |
Start a monitor in under a minute
Describe a topic or paste a URL. Cancel before the trial ends and you pay nothing.
Try it free for 7 daysThe bottom line
One route file, one table, and AyeWatch alerts live next to the rest of your product's data. Check the URL for redirects before you save it, and keep anything slow in after().
FAQ
How do I get the raw request body in a Next.js route handler?
Call await request.arrayBuffer() and wrap it in Buffer.from. Do not call request.json() first, because the parsed body cannot give back the exact bytes the signature covers.
Why does my Next.js webhook return 307 or 308?
Usually middleware redirecting signed-out requests, trailingSlash in next.config, or a domain redirect. Exclude the route from the matcher and paste the final URL.
Can I use after() in a route handler?
Yes. after from next/server is stable since Next.js 15.1 and runs its callback once the response is sent, within the route's maximum duration.
How do I avoid processing the same webhook twice?
Make update_id the primary key and insert with ON CONFLICT DO NOTHING. A rowCount of 0 means you already stored that alert.
Does this work on the Edge runtime?
Not as written. It uses node:crypto and pg. On the Edge runtime, use the Web Crypto check from the Cloudflare Workers guide and an HTTP-based database client.