brackt/app/routes/api/webhooks/clerk.ts
Chris Parsons 09b9b9bdad
Optimize user data fetching with batch queries and centralize display name logic (#176)
* Fall back to displayName when username is null for Discord webhook

Users who sign up via OAuth (Google, GitHub, etc.) without setting a
Clerk username have a null `username` field but always have a `displayName`
(computed from firstName+lastName or email). Previously, `usernameByClerkId`
was filtered to only include users with a non-null username, causing those
owners to appear without any identifier in Discord standings messages
(e.g. "Liverpool def. Galatasaray" instead of "Liverpool def. Galatasaray (Madmike)").

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

* Extract getUserDisplayName helper and use consistently throughout

Add a single getUserDisplayName(user) function to app/models/user.ts that
encapsulates the username → displayName fallback logic. Replace 9 scattered
inline expressions across the codebase (owner-map, scoring-calculator,
league routes, settings, invite flow, draft API, Clerk webhook) with calls
to the shared helper.

No behaviour change — all existing logic preserved, just centralised.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

* Fix N+1 user queries in league loader and settings loader

Add findUsersByClerkIds() batch function to the user model and replace two
separate Promise.all+findUserByClerkId loops (one for owners, one for
commissioners) with a single inArray query in both $leagueId.server.ts and
$leagueId.settings.tsx. The merged query covers both owner and commissioner
IDs in one round-trip.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

* Fix N+1 user queries in buildOwnerMap

Replace the Promise.all+findUserByClerkId loop with a single
findUsersByClerkIds batch query, consistent with the league loader
and settings loader fixes.

https://claude.ai/code/session_01VAkeDDVZMYS1DweQnUrRnH

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-18 16:46:07 -07:00

96 lines
2.9 KiB
TypeScript

import { Webhook } from "svix";
import type { Route } from "./+types/clerk";
import { findOrCreateUser, getUserDisplayName } from "~/models/user";
export async function action({ request }: Route.ActionArgs) {
// Get the webhook secret from environment
const WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) {
throw new Error("Please add CLERK_WEBHOOK_SECRET to your .env file");
}
// Get the headers
const svix_id = request.headers.get("svix-id");
const svix_timestamp = request.headers.get("svix-timestamp");
const svix_signature = request.headers.get("svix-signature");
// If there are no headers, error out
if (!svix_id || !svix_timestamp || !svix_signature) {
return new Response("Error: Missing svix headers", { status: 400 });
}
// Get the body
const payload = await request.text();
// Create a new Svix instance with your webhook secret
const wh = new Webhook(WEBHOOK_SECRET);
let evt: any;
// Verify the webhook
try {
evt = wh.verify(payload, {
"svix-id": svix_id,
"svix-timestamp": svix_timestamp,
"svix-signature": svix_signature,
});
} catch (err) {
console.error("Error verifying webhook:", err);
return new Response("Error: Verification failed", { status: 400 });
}
// Handle the webhook
const eventType = evt.type;
console.log(`Webhook received: ${eventType}`);
if (eventType === "user.created" || eventType === "user.updated") {
const { id, email_addresses, username, first_name, last_name, image_url } = evt.data;
try {
if (eventType === "user.created") {
// Create new user
const user = await findOrCreateUser({
id,
emailAddresses:
email_addresses?.map((e: any) => ({
emailAddress: e.email_address,
})) || [],
username,
firstName: first_name,
lastName: last_name,
imageUrl: image_url,
});
console.log(
`User created in database: ${user.id} (${getUserDisplayName(user)})`
);
} else {
// Update existing user (or create if doesn't exist)
const user = await findOrCreateUser({
id,
emailAddresses:
email_addresses?.map((e: any) => ({
emailAddress: e.email_address,
})) || [],
username,
firstName: first_name,
lastName: last_name,
imageUrl: image_url,
});
console.log(
`User updated in database: ${user.id} (${getUserDisplayName(user)})`
);
}
} catch (error) {
console.error(`Error handling ${eventType}:`, error);
return new Response(
`Error: Failed to ${eventType === "user.created" ? "create" : "update"} user`,
{
status: 500,
}
);
}
}
return new Response("Webhook processed successfully", { status: 200 });
}