How to sync Clerk authenticated users with your own database in NextJS 13?! | Clerk Pt. 2
Вставка
- Опубліковано 7 вер 2024
- In this video, we'll be looking at how to sync your Clerk authenticated users with your own database.
Clerk | Sync data to your backend: clerk.com/docs...
Clerk Example using NextJS (Pre v13): github.com/cle...
Svix webhook verification: docs.svix.com/...
Starting Code: github.com/kav...
Final Code: github.com/kav...
---
Website: kavin.me
Blog: livecode247.com
Github: github.com/kav...
#nextjs #reactjs #frontend #webdevelopment #javascript #typescript #authentication #clerk
Such an incredible tutorial and love the fact you incorporated this to the new route syntax. You are very dedicated and knowledgeable. I can't thank you enough. It was very generous of you to respond to my request.
Everyone, Let's show our support and help this amazing creator reach more people!
Thank you! That's very kind of you
I agree, I think he’s the only one currently (to my knowledge) to cover that topic.
Thank you!
💪💪💪
Thanks bro. I can't believe I learning from a kid who isn't old enough to vote. Big ups. Good jobs. Your parents must be proud of you. I would avoid using multiple branches for demos. It's too complicated to download.
Haha. Thank you! Noted your point as well. Thank you for the input :)
Incredible video! I was wondering how to do exactly this.
Glad you liked it!
i will implement this in my nestjs backend with my nextjs frontend, awesome tutorial. appreciate it 🙏🙏
Glad it was helpful!
Thank you for this, this video was great and I have been trying for so long to do authentication on NextJs without using NextAuthJS.
Thank you so much!
Excelent video. Thanks for sharing!
This tutorial was great and it worked for me. Can you make a video on JWT template which they have? It will be super helpful if you can upload that soon as there is no tutorial on that.
Thanks for that brother! Exactly what i was looking for. Amazing!
good work bro but why your channel is so underated? btw u just got a new subscriber
Thanks for the sub! Working on building my way up 💪
wc
@@livecode247
Now how to Authentication and Role-Based Access Control in Next.js using clerk ... I mean when you have a different role like admin and user and make middleware to handle it using clerk, would you make a video tutorial about it?
I think there's not yet video about it
I'm using nextjs and nestjs (as an api). I wish to verify that requests made to the api have authority to do so.
When I made a full stack app using express, I used passport to control everything on front-end and backend. It prevented someone from making unauthorized CRUD.
Would I need to maintain users in my database, sessions, and verify JWT to be safe? I can't see how you wouldn't sign in a user on the backend to verify their authorization to CRUD and issue a JWT.
After some digging, I think I found the appropriate solution for this situation. Apparently, I should use passport-jwt on my nestjs to interface with clerk in a secure manner so that I can validate backend calls with the correct jwt.
This is a simplification and implementation is a little more involved. I'm using a YT video on next.js, nestjs, and clerk. Plus nestjs documentation on passport.
I dont know why but i get an error
HTTP RESPONSE CODE
401
RESPONSE
"ERROR":{1 item
"message":string"src property must be a valid json object"
}
is it because the payload is not getting loaded properly? do you have any ideas?
This helped me... copy and paste from a different comment so you see it.
I had this problem... it turns out it was a middleware issue. Code below made it work for me. The problem? export const config was not registering my publicRoute or ignoredRoutes. Very weird issue but got it working now.
import { authMiddleware } from "@clerk/nextjs";
export default authMiddleware({
// IF THESE ARE IN CONFIG, CLERK THROWS A FIT
ignoredRoutes: ["/((?!api|trpc))(_next|.+\..+)(.*)"], // use this to ignore routes
publicRoutes: ["/api/webhooks/user/route"],
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
is it possible connect clerk with mariadb? Thanks
Getting 401 unauthorised..
Error message:- src property must be a valid json object
Hi good video as usual, could you try update the clerk user object Metadata and see if it on sync with the user metadata get back from currentUser() or auth() function on the server component page?
x2!
Hope
This works if i remember correctly. I tried this on a project a few days ago while integrating stripe with clerk. I used the clerkClient.users.updateUser method and then called clerkClient.users.getUser method at another place to get the stripe creds.
Hey there, I was wondering if anyone could help me.
I am trying to use this code and didn't realize it was for Next 13's app directory and I am still on the pages directory.
It says the headers are for server components only. How can I go about using this code with the pages directory + T3 Stack? I have routers and the server folder.
He linked an example in the description that uses the pages directory. I'm doing it in a similar way to that but keep receiving the error message in Clerk "src property must be a valid json object", so not sure.
Really useful. Thanks
Glad it was helpful!
Bhai kya hum phpmysql ko clerk api se integrate kar sakte hain 😢😢
Thanks, that's a great explanation. I'm currently learning to build a my website with Next.js and using Clerk Auth. From your video, I noticed you store all attributes in JSON format. I wanted to ask, what if I only want to store `emailAddress` in separate database columns?
Hey! I just did that for the tutorial purposes. In the real world scenario you would probably store the columns separately. You can basically get back the required column from `evt.data` and then separately insert it into the database instead of what I did with the attributes object at 35:32.
Do I still need this Svix workaround with 13.4? I feel like there's an easier way now with the router.
Hmmm, might have to look into this now. Thanks for the feedback!
did you find the answer for your question ?
@@livecode247 How about a video on doing this with a Python / FastAPI backend? Would love that
@@coolnickq Hey man! I try to stick my content to NextJS and React and stuff revolving around it, but ya sure if that's what's needed, I'd be open to it given it wouldn't divert the main course of the channel :)
I am just wondering if we can use middleware proxy for this and sync out database with the data we are sending to clerk server, correct me if am wrong
I tried to implement this in my t3 stack and i cant add a user. help
have you find the solution? webhook send request successfully but it will not create user and I can not fetch data in console.log
Great video.
What if I want to add extra field for role based Auth during registration? What I mean is, if I have multiple user types, say Teacher and Student, how do I include this field during registration so user can select a user type?
You might want to look into custom flows for that: clerk.com/docs/custom-flows/use-sign-up
Teacher great video, I have a question, such as customizing the login screen and registering in my local language; In my country, we do not use the English language.
You can use clerk localizations to make that. Once you've imported it you pass a prop in the ClerkProvider component that's named localization and then set the language you need (how to install and import clerk localizations is in their documentation, the language code is also in their documentation). For instance if you want to set spanish as clerk's language you'd have to do:
Look at how you use the prop localization. Now the translation on those tend to not be that good so you may want to make a pull request to enhance the translation to your language.
hey great video man, can you make one for firebase please I have a project using openai gtp to create a simple chatbot but I can't save the conversations between bot and the user that is logged in so when the user again logs is he can see his old conversation with the chat I wanted to do that using firebase but I dont know how to intregrate firebase using clerck if you could make a video for that it would be helpful
I dont know what I am doing wrong. I am using mongo as my database. I have hosted my site on vercel and added the endpoint in clerk but i dont get any response or errors. What i just get is clerk webhooks not showing any attempted calls and no data saved in mongo. What could be the problem
I'm facing the same problem
@@alpha7s708 Here is how I solved my problem. First of all make sure that you are sending the correct payload to clerk. Just messing up one field, eg: username, could potentially cause errors to occur. If you have added username for example in your payload, make sure you have activated the username option in clerk dashboard. Next, use ngrok to expose your app, don't use vercel.
Amazing!! What happens when you can to create a table with a relation to the user? Do you have it reference the externalId?
Well since we're storing it in our own database, just use a foreign key
thank you so much dude
You're welcome!
you saved me 👌👌❤❤ Thank you
Glad it helped!
Awesome explanation,
is it possible to add a user role as well?
Yes, you can make use of the metadata api. This is on my video todo list!
Can you tell me how to do the same thing using firebase as my backend. Please that would be helpful
You could just use firebase auth in that case, in my opinion
Hello friend, could you make an example with roles for CLERK... I want to make an application for administration and only authorized people could enter and an application for users who enter if they register in the application.... I appreciate your comment... If you can't make the video, at least guidance to try to do it... thanks... Greetings from Venezuela your friend Jose Grillo
Hey man! Will be down to make this video in the future but am a little occupied with some content I've thought about rn. In a nutshell, what you would want to do is manage a role in the user's publicMetadata. I was using this in an application earlier, where I was setting the stripe credentials. It's very similar to that. Just check the role from the metadata, wherever you want to check it for authorization.
To get the privateMetadata, you can do this:
_const user = await clerkClient.users.getUser(userId)
const userData = user.publicMetadata_
To set it, you can do this:
_const user = await clerkClient.users.updateUser(userId, {
publicMetadata: {
role: "admin"
},
})_
Hope this makes sense.
Docs Reference: clerk.com/docs/users/user-metadata
Nice video bro. Can I ask how to make clerk to accept microsoft email from one domain only?
I haven't tried this but you could take a look at this: clerk.com/docs/authentication/configuration/restrictions
@@livecode247 thanks, I have found it, the only issue is that its not include in the free tier.
Brother I need help " i have been stuck on an error of 401 while webhook connection with mongodb since 1week...
I checked :-
1 environment variable ✅
2 routes inside app as api/webhooks ✅
3 in middleware I also added /api/webhooks in public and ignored routes both
4 deployment is good✅
Idk where the problem is ... please help... it's just showing 401 in vercel in my deployment logs( it's just indicating that it's an authentication problem but idk where) please help
Bro I am also facing the same problem....did u get any solution?
@@abhijeetsingh4190 yes bro, go to the auth settings in clerk and turn it off that was turned on as default and just by turning it off everything will work fine
Bro what do I have to turn off?
@@abhijeetsingh4190 go to organisation settings and turn the first one off
@@abhijeetsingh4190 in your clerk dashboard, organisation settings
Thanks!
Really good!
Thank you!
hey, how can I implement user role using clerk any idea?
You can store it in the user metadata and then access it in the middlewarw
@@livecode247 can you help me with it do you have discord?
Hi, Thanks for your great video. I'm trying to implement your method in t3 stack. I use your suggested github repo as a reference. webhook in clerk website sends the request successfully and it contains my user data, but on the client side nothing comes through I even console.log("x") anywhere in webhook file but nothing shows in my console! Do you have any suggestion?
Oh ok, let me check! I got a query from a few people saying that the webhook api isn't working as expected. Will look into it ASAP
thanks a lot @@livecode247
is there any chance in which you've looked at this problem?@@livecode247
@@livecode247 I had this problem... it turns out it was a middleware issue. Code below made it work for me. The problem? export const config was not registering my publicRoute or ignoredRoutes. Very weird issue but got it working now.
import { authMiddleware } from "@clerk/nextjs";
export default authMiddleware({
// IF THESE ARE IN CONFIG, CLERK THROWS A FIT
ignoredRoutes: ["/((?!api|trpc))(_next|.+\..+)(.*)"], // use this to ignore routes
publicRoutes: ["/api/webhooks/user/route"],
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
@@livecode247 hey! found any solution for this? setup looks like it works but im not receiving nothing on the server logs
Are the usernames unique? I want to each user to have a unique name for the slug dose clerk offer that?
Haven't exactly tried this but the "User & Authentication" tab in your app's dashboard has the "Username" option
thanks a lot
You're welcome!
thanks bro
Any time!
Anyone running into an issue where ngrok shows a temporary redirect when clerk calls your webhook
/api/webhooks/user 307 Temporary Redirect
Dont forget to add your API to your middleware public routes
import { authMiddleware } from '@clerk/nextjs'
export default authMiddleware({
publicRoutes: [
'/api(.*)',
],
...
})
Hello , can i get some help with this where can i contact you?
Hey! You can email me at mail@kavin.me
Greetings... I am already subscribed..... you have Discord....??
if you don't have it yet I invite you to do it.... It looks like this channel is going to take off soon... Congratulations you explain very well
Greetings Jose Grillo from Venezuela
Hey! Thank you so much! I do have a discord user(kavinvalli) but don't have a server. I don't think my making a server right now, makes a lot of sense lol, since I don't have that much traffic yet, but hopefully that day will come soon!
@@livecode247 OK I understand .... I can only tell you
A journey of a thousand miles begins with a first step.
A thousand blessings and the best of success you deserve it.
Thank you so much! Means a lot ❤️!