Back to Integrations
Webhook Quarantine

Clerk Auth Integration

Quarantine automated bots, revoke sessions, and protect your free-tier AI token balance when using Clerk hosted components.

The Hosted Component Challenge

When using Clerk's hosted <SignUp /> component, user records are created on Clerk's infrastructure before your backend server receives a request. Malicious actors leverage this to immediately call your downstream APIs and drain complimentary GPU credits.

SiftlyAPI resolves this with an Automated Quarantine Webhook: whenever Clerk fires user.created, your server evaluates the signup risk. If the user is malicious, your server immediately deletes or bans the user and revokes their session before any free credits are provisioned.

1

Install Clerk & Svix Packages

Install the Clerk Backend SDK and Svix (for cryptographic webhook verification):

Terminal
npm install @clerk/backend svix
2

Configure Environment Variables

Add your Clerk Secret Key, Webhook Signing Secret, and SiftlyAPI Key to your .env.local:

.env.local
CLERK_SECRET_KEY=sk_live_...
CLERK_WEBHOOK_SECRET=whsec_...
SIFTLYAPI_KEY=sk_live_...
3

Create the Webhook Route

Create an App Router webhook route at app/api/webhooks/clerk/route.ts:

app/api/webhooks/clerk/route.ts
1import { Webhook } from "svix";
2import { headers } from "next/headers";
3import { NextResponse } from "next/server";
4import { createClerkClient } from "@clerk/backend";
5  
6const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY });
7  
8export async function POST(req: Request) {
9 const headerPayload = await headers();
10 const svix_id = headerPayload.get("svix-id");
11 const svix_timestamp = headerPayload.get("svix-timestamp");
12 const svix_signature = headerPayload.get("svix-signature");
13  
14 if (!svix_id || !svix_timestamp || !svix_signature) {
15 return new NextResponse("Error: Missing svix headers", { status: 400 });
16 }
17  
18 const payload = await req.json();
19 const body = JSON.stringify(payload);
20  
21 // 1. Verify Svix signature
22 const wh = new Webhook(process.env.CLERK_WEBHOOK_SECRET || "");
23 let evt: any;
24 try {
25 evt = wh.verify(body, {
26 "svix-id": svix_id,
27 "svix-timestamp": svix_timestamp,
28 "svix-signature": svix_signature,
29 });
30 } catch (err) {
31 console.error("Webhook signature verification failed:", err);
32 return new NextResponse("Error: Invalid signature", { status: 400 });
33 }
34  
35 // 2. Intercept user.created event
36 if (evt.type === "user.created") {
37 const userId = evt.data.id;
38 const email = evt.data.email_addresses?.[0]?.email_address;
39 // Clerk surfaces the signup IP/UA at the event_attributes root, not on the user object
40 const ip = evt.event_attributes?.http_request?.client_ip;
41 const userAgent = evt.event_attributes?.http_request?.user_agent || "";
42  
43 if (!email) {
44 return NextResponse.json({ success: true, skipped: true });
45 }
46  
47 // Skip scoring when Clerk does not surface the client IP. Evaluating a loopback
48 // (127.0.0.1) placeholder would be classified bogon_ip -> action: "block",
49 // quarantining every signup. Mirrors the fail-open convention.
50 if (!ip) {
51 console.warn("No client IP in Clerk webhook event, skipping trust scoring", { userId });
52 return NextResponse.json({ success: true, skipped: true });
53 }
54  
55 try {
56 // 3. Evaluate risk in SiftlyAPI (10-40ms)
57 const siftlyapiRes = await fetch("https://api.siftlyapi.com/v1/score-signup", {
58 method: "POST",
59 headers: {
60 "Content-Type": "application/json",
61 "X-API-Key": process.env.SIFTLYAPI_KEY!,
62 },
63 body: JSON.stringify({
64 email,
65 ip_address: ip,
66 user_agent: userAgent,
67 }),
68 signal: AbortSignal.timeout(3000),
69 });
70  
71 if (siftlyapiRes.ok) {
72 const result = await siftlyapiRes.json();
73  
74 // 4. If malicious, quarantine immediately
75 if (result.action === "block") {
76 console.warn(`Quarantining fraudulent Clerk user ${userId} (${email}) - Reason: ${result.reasons?.[0]?.reason_code}`);
77  
78 // Ban or delete the user from Clerk to kill all active sessions
79 await clerkClient.users.deleteUser(userId);
80  
81 // Return 200 to acknowledge webhook receipt
82 return NextResponse.json({
83 success: true,
84 quarantined: true,
85 action: "block",
86 reason: result.reasons?.[0]?.reason_code,
87 });
88 }
89  
90 // If step-up verification needed, tag private metadata
91 if (result.action === "challenge") {
92 await clerkClient.users.updateUserMetadata(userId, {
93 privateMetadata: {
94 requiresVerification: true,
95 },
96 });
97 }
98 }
99 } catch (err) {
100 // Fail-open: do not disrupt registration on network timeout
101 console.error("SiftlyAPI evaluation failed, failing open:", err);
102 }
103 }
104  
105 return NextResponse.json({ success: true });
106}
4

Register Webhook in Clerk Dashboard

  1. 1. Navigate to your Clerk Dashboard → Webhooks.
  2. 2. Click Add Endpoint.
  3. 3. Enter your webhook endpoint URL: https://yourdomain.com/api/webhooks/clerk.
  4. 4. In Message Filtering, select the user.created event.
  5. 5. Copy the Signing Secret and paste it as CLERK_WEBHOOK_SECRET in your production environment.
Free Trial Credit Provisioning Safety
Always place your free trial credit provisioning (such as granting OpenAI/Anthropic API credits or Stripe trial subscriptions) inside or after the SiftlyAPI quarantine check. Never provision credits synchronously on the initial frontend callback.