Using Clerk Auth, I have a working login/sign-up flow with Next.js 13 middleware.
When a user signs up, I want to add a row to my DB's Users table.
The problem with middleware is that it runs on every single request and I don't want to make a call to my database to check if the user exists so I can create a record.
Does Clerk return any data that I can use to differentiate a sign-up vs a normal request?
So I ended up going another route because I didn't want to create webhooks for my specific case (although I believe in most cases, that's what you'd want to do).
For me, I ended up using Clerk's metadata system. Basically you can attach metadata to a user on their system, see here.
import { NextResponse } from 'next/server';
import { clerkClient } from "@clerk/nextjs";
export async function POST() {
const { stripeId, userId } = await body.json();
await clerkClient.users.updateUserMetadata(userId, {
privateMetadata: {
stripeId: stripeId
}
});
return NextResponse.json({ success: true });
}
In my case, I attach my own system's user UUID to Clerk's user. Then, in my middleware, I check if this exists (it's in the session data, so it won't make a request to Clerk's servers), if it doesn't exist, I know it's a new year and I run the signup flow, otherwise carry on with normal operations.
I'll set the other answer as the correct answer, but I'll leave this answer here for anyone with a similar use case trying to avoid webhooks.
I think you might need to create webhooks that listen to user.created. See
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With