Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js with Clerk Auth - how to detect if a user just signed up?

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?

like image 265
PGT Avatar asked Jan 28 '26 21:01

PGT


2 Answers

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.

like image 91
PGT Avatar answered Jan 30 '26 12:01

PGT


I think you might need to create webhooks that listen to user.created. See

  • https://clerk.com/docs/users/sync-data-to-your-backend
  • https://reference.clerk.dev/v/master/backend/webhooks
like image 45
erikz Avatar answered Jan 30 '26 12:01

erikz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!