how to extend clerk's users metadata

Im wondering how to extend clerk users model by adding some data about the user's role. I know it can be done but I don't know how I can do it in a way to check once the user sign in it check if the user's email is in a table with a role and add it its correspondent role. Clerk's docs has an example of adding metadata but the example is unclear for me https://clerk.com/docs/users/user-metadata
6 Replies
James Perkins
James Perkins14mo ago
To update a user with metadata from your backend , is just a call to updateUserMetadata and then pick the metadata you need
await clerkClient.users.updateUserMetadata("user_id",{
// Read only on client, Read / Write on the server
publicMetadata:{
"role": "awesome"
},
// Read only on server and Writable on Server
privateMetadata:{
"role": "awesomesauce"
},
// Read / Write anywhere
unsafeMetadata:{
"role": "awesomeawesome"
}
});
await clerkClient.users.updateUserMetadata("user_id",{
// Read only on client, Read / Write on the server
publicMetadata:{
"role": "awesome"
},
// Read only on server and Writable on Server
privateMetadata:{
"role": "awesomesauce"
},
// Read / Write anywhere
unsafeMetadata:{
"role": "awesomeawesome"
}
});
JuaniS
JuaniS14mo ago
perfect, where will it be a good place to write that logic? can the sign up function of clerk have like a middleware
James Perkins
James Perkins14mo ago
If you want it to happen after sign up just use the webhooks we fire one on creation. Otherwise do something like <SignUp> redirect to page -> fires API endpoint to do inserts.
JuaniS
JuaniS13mo ago
Ohhhh amazing, I will try to set up the webhook then! Thank you is there a type for extending the next js req type for the clerk webhook events? In the docs there is one example where it import the type from the node sdk
James Perkins
James Perkins13mo ago
The typing is the same but just "@clerk/nextjs/server" I believe.
JuaniS
JuaniS13mo ago
oh true, for some reason I could auto import it. Thanks!