Next.js 14+ Authentication with Clerk and How to Connect Clerk Users with Mongo Database

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi guys welcome back to another video on next js14 I'm going to be using clerk authentication tutorial which I've already created and I've been getting requests from multiple users that how we can connect clerk authentication users which are stored in clerk database and how to store these users in other external databases because in real application we have users models and we have other data it can be the users products users notes user settings analytics so we have to store this user data in our external database because other data in our application will be stored in our external databases and it can be the mongodb database it can be the SQL post database or any other databases so I will be expanding the same application which I have already created let me show you this is the second video you can see which I've already created authentication with clerk login sign up and forget password this is almost 1 hour long video if you want to learn all about clerk authentication protecting routes protecting uh client components server component protecting with middleware you can watch this video but if you have an understanding of clerk authentication uh and want to know that how we can store these users in our external databases then this is the video for you guys so this is the application which I have already created in this particular video the second video and uh you can see that I can click on the login or the sign up if I'll click on it let me see if my application is running uh okay yeah it's running so this is the login page and here I can click on this uh continue with Google from here I can select any of my email ID and after user is logged in it will be redirected to this/ profile page which I have set in my uh this EnV local file this is where I have set all right so now let's get started and configure our database and I will be showing you how we can connect with the mongodb creating users in the mongodb and also once the user is created in the clerk dashboard it should automatically trigger a web hook and that should store the data in the mongod DB so before moving further let me show you all the videos which I've already created on nextjs 1314 using App directory and you can learn pretty much every topic if you want to become a good nextjs developer so you can see I'm putting a lot of effort building these videos for you guys so do subscribe my channel and like this video this particular playlist contains 23 video but if I go back uh you will see that I have multiple videos on nextjs 13 as well along with tips and tricks of JavaScript as well as AI related videos and also Docker tutorials with cicd so this is the same project which I finished in my previous clerk authentication video using NEX js14 so first of all we need to configure mongodb uh in this project so let's go ahead and open up the cloud. mongod db.com I've already created multiple projects so for you guys I'm going to be creating a new project just click on that and click on new project and I will be naming my project and then I will be connecting my mongodb with this particular uh NEX js14 project so here I first need to give uh the project name so let's say clerk next 14 okay so here you don't need to add anything and I'm going to go and click on the next I will keep project owner as it is click on the create a project so here I have this Source folder and I have this app folder so first of all I'm going to be creating a new folder inside this Source folder so let's create that and this is going to be lib and inside this lib I'm going to be creating db. TS file all right and in this particular file I will be connecting my project with the mongodb so here you can see that my project is created and I'm going to click on the create and this is going to create a cluster and in this particular page we need will need to select some region so I'm going to go with the free version let's keep the cluster zero uh let's keep this AWS and uh here I'm going to click on the create deployment okay so here I need to quickly select this all right so it's going to take some time to create my cluster so let's get back and before moving further let me install few packages which uh we'll be needing so I'm going to be installing npmi first of all I will be installing mongus and then I will be installing mongodb all right so here I need to import and then like this from all right so after that um I need to fetch the URL which I will be creating uh over here it's still creating that uh so connect to the cluster choose a connection method so um I will be copying my password first of all and I will be saving it somewhere in my notes so let me save that first of all and uh I'm going to be creating this database user so this has been created now click on the choose connection method and I'm going to be click on the drivers and this is particular URL which I need to copy okay so let's come back and let's open up the EnV Local Host and here I will be creating this particular name so let's say DB code URL equals to this okay so this password is already added and uh this is done so I'm going to go click on the close and uh I'm going to just close all of these notification and let's verify the network access for accessing this database quickly uh So currently uh my IP address is set so I can connect this datab I can click on the database and uh from here I will be clicking on the collections where I will be seeing all the data which will be stored in this database all right currently uh you can see that it is showing uh these things okay these are just default users which it has created so we can leave these like this uh other than this uh simple metrix I'm going to be just removing it sample mflex so let's drop this particular database name and now it should show nothing all right so here we will be using this particular URL let's close this EnV file and I'm going to come over here so in this particular file let's fetch that mongodb URL so const mongod dbor URL equals to process. n v. mongod DB URL okay so just so that we don't make any mistake we can copy the name from here directly and paste that over there all right so now I will be let's say let cach because we are using uh nextjs in node express application we don't need to maintain the cacher because in next GS uh to access the database uh before every request we need to connect to the database but uh it will cause an issue uh it will delay the connection if we don't maintain the cach a because if the cache exists uh for the database connection then we will use the cachier to connect to the database rather than regenerate the uh connection with the database so this is going to be like this so let for now add any so global as any do mongus all right and here I'm going to check if uh casade does not exist then I will be creating a cade equals to Global any equals to con null and then the promise null all right and here I will be exporting a function that will be used in other files to connect to this database so like this and if cached dot connection exist then I'm going to return the cached varion of the connection otherwise I'm going to also verify if uh mongodb URL exists uh you don't need to verify but we can check if this particular URL exists or not then we can throw an error but for now we don't need to write this because we know that it exists so cached do promise equals to cashed do promise or Mongo's connect mongodb URL like this and inside it I first need to add the DB name so let's give the DB name uh this is something we can give clerk uh next 14 DB you can write anything inside it let's give the buffer commands equals to false and connect time out equals to 30,000 all right so this is a function which uh we have added and uh here I can add cash shade. connection equals to A wait cashed do promise and then return Cade do connection all right so you can pause the video and copy as it is as I have added over here and uh for this any we can create an interface as well let's quickly add an interface so Mongo's connection and connection uh we can uh get it like uh mongus and then promise uh we can connect promise mongos like this all right and use this particular interface over here uh okay so this is null so we can add null over here because it is saying that it can be null as well so you can see it is gone so let's add null all right so that's pretty much it we need to write in this particular file it will make sure that uh we are connecting to the database properly by creating this new database in the mongodb and also if the cached Varian already exists then we are going to return the cached version rather than reconnecting to the database so I hope it will not throw any issue so let's close this particular file and now in this particular lip folder I'm going to create a new folder and this is going to be models and inside it I will be creating a new user model so user. model. TS if you want to know how to work with models how to create rest apis in nexj 14 uh how to connect with mongodb database separately uh then I've already created all of these videos on my channel so you can check that out and learn pretty much every topic on nextjs 14 so in this particular file I will be using uh model schema to create the different properties for the users properties can include the email username photo first name last name and also we need to maintain the clerk user ID which is being created in the clerk dashboard so in the first line I'm going to be importing schema model and models and this is going to be from and then I need to create a variable let's call it user schema equals to new and then schema I've already explained these things in my rest API creation tutorial on next gs14 you can check that out so here we need to add some properties the first property we we need to add is this clerk ID and uh we are maintaining the clerk ID in the mongodb user creation uh this is helpful when we need to make the relationship with user which is stored in both Clerk and the mongodb so next we need to add email username uh we can have the photo last name and then the first name so let me quickly add these unique means that it cannot be duplicated ID should be unique required is it it is required then we have have the username type string uh first name and then the last name okay so once we have initialized this schema we can export this particular user and before that we need to create models user do user actually or if user does not exist then we are going to create a new model so here we can have user schema which we have created above and then I can write export default user so this is the model that we have created uh let's close this and I'm going to be creating a new folder inside this lib and I'm going to be calling actions I hope that you have an understanding about server actions in nextjs uh 13 nextjs 14 I've already created multiple videos on using the server actions so I will try to explain it over here as well server action means that whatever the code we write inside this particular file file actually runs on the server site and it means that we don't need to create apis to connect to the database we can directly connect to database within the server actions as well so inside it I'm going to be creating useraction dots all right so here uh to make it uh run on the server side we need to write use server at the top within the double quotes Okay and here I'm going to be importing the user model which I have just created and also conect function from the db. TS file which we have created so import and then I will be uh writing a user from art lib and then I will be writing the models sluser model okay and now let's fetch connect from @ lib db. TS all right and then I will be exporting a function this is going to be the create user user and uh we can create an interface as well uh but uh to make this video shorter I'm going to give it any type and let's give a TR catch block quickly and like this so the first thing that we need to do is to connect with our database and this is going to uh be asyn a wait and uh it is not going to move to next line until it uh establish the connection and after that I'm going to be creating a new user user. create and then the user which is coming from this param and then I will be simply returning the response uh json. pars json. stringify and then the new user and inside this I can also write console log error all right there seems an error so let's see like this all right so that's pretty much it we need to write over here so this particular user action I'm not going to use this particular function directly from any of my component from the user interface instead this function is going to be triggered by the clerk because Clerk is going to check if the user is successfully created then the clerk automatically trigger a web hook which I'm just going to create and the web Hook is going to call this function and it is going to create a new user instance in I mongod DB database and this user will be passed from the clerk okay so let's close that and next thing we need to do is inside this app folder we need to create a new folder and this is going to be API and inside it uh we can have uh web hooks um so we can have multiple web hooks so that's why I'm creating this General function General folder actually and inside it we can name the different uh uh functions uh web hook functions that belongs to different platforms so I need to use uh it for the clerk so that's why I've created a new folder I hope that you have an understanding how to create apis um which I've already uh created a video on so we always have to create the API folder inside the app directory and inside this API folder we need to create another folder that refers to the API URL okay and inside it I need to create this file route. TS we cannot change its name if we want to make it an API route okay so here uh I need to import multiple things all right so um in my terminal um let me import those and see if uh there comes any error so uh these are the different things that we need to import so I'm going to be installing svix uh so that the error is gone so where did I got these imports from I'm going to give the link of this particular um article which is from the clerk sync clerk data to your Mac uh back end with web hooks so this is an awesome article it shows how we can connect our clerk with the mongodb or any other databases and if I come down you will see that this is where I got these uh from here and this is showing that we need to install swix package all right and then we need to create uh this particular post function which we need to create over here and above this I also need to import that function which I created so create user from the user action uh so this is how I have created all right so inside this particular thing uh what we need to do is we need to uh add this web hook secret so I'm going to go uh you can create a new uh clerk project as well but I'm going to be using the same project which I've already created uh but I'm going to be uh showing you the step which we need to do the first of all what you need to do is you need to click on is web Hooks and here we need to create a web hook web hook means that for any kind of action that happens in the clerk uh we will be triggering an API that we have created in a project okay so this particular Hook is already created I'm going to show you by creating a new hook as well so I'm going to click on ADD web hook and here I need to add a URL and this URL cannot be the Local Host this URL needs to be a public ID so for that we need to deploy our application so that we got a public uh endpoint URL and which we can add over here all right so before moving further I'm going to leave this page as it is I need to create a new GitHub repository and I'm going to be deploying this application to uh my uh versal okay and then I'll be coming to this page so here I'm going to be creating uh let me first verify if we have we don't have this is not a get repository which we need to add so I'm going to go to the GitHub repository and I'm going to be creating a new uh repo so I'm going to be creating next4 mongod DB Clerk and I'm going to leave it private and click on the create repository so from here I will be pushing this I need to add some code over here which I can do it later but for now to get the web secret uh I first need to deploy my application as it is uh as it's showing uh currently okay so let's go and uh this particular repository is created and uh I need to First initialize it with Git if it's not already initialized and then let me add a first commit first of all let's add get add and then the commit and let's quickly copy all of these commands all right so so our project should be pushed uh to this repository and yes you can see that it is pushed uh now I'm going to go and open up the viral.com so here I'm going to click on this add new button and click on the project I've already added my GitHub repository uh to have access to all the repositories from my account so it's going to show me the recent repository which I've just created next 14 mongodb clerk so let's let's wait for that so I have connected my account and it is showing this first repository which I have just created so I'm going to click on the import and um now inside this EnV local I'm going to copy all of these URLs from here and I'm going to click on the environment variable and paste over here and it's going to add all of these uh environment variables over here for me and uh after this I'm going to click on deploy and it's going to take some time to deploy my application all right so project is deployed you can see that it's showing congratulations I'm going to click on continue to the dashboard and uh it's going to give me the URL where my application is deployed and uh that URL is something that uh we need to paste over here uh while creating this web hook endpoint all right so this is the app so I'm going to click on that and it should show me the same kind of UI uh which was showing over here it's showing loading currently all right so let's copy this particular URL which is deployed and I'm going to come over here and let's paste it and I'm going to write API web hooks slash and then I'm going to add clerk because this is the URL that is where I have created this particular API and make sure there is no mistake all right so we don't need to write the description it is optional and these are all the events that we can enable if we want to trigger any API that we have created in our application it can be the any URL API URL that we want to trigger based upon any event triggered from this cler so one thing if I go down uh users we need this user creation event that should be enabled from here and I'm going to click on the create so this web Hook is created and whenever user is going to be created in this particular uh uh clerk dashboard in this application this API is going to get triggered uh so I'm going to click on uh reveal this signing secret let me copy this and I'm going to come over here EnV local and I'm going to add it like this so web hook secret equals to and I'm going to paste it over here all right and I also need to copy this thing let's go over settings off our versal application click on the environment variables and I'm going to create this new environment variable key and click on the save and uh I don't want to redeploy it as of now because uh it not work because I need to write code over here to create our user in mongodb database all right and before moving further if I go over here this particular article um what we need to do is we need to add uh this particular URL to be public this particular API URL I'm going to go to the middleware and uh these are the couple of URL which I have already added so to add that new API URL SL API SL web hooks SL clerk all right so let's save this particular file whenever we are going to redeploy this application this is going to be the public URL the API is going to be the public URL means that anything um it can be the clerk it can be us that we can connect to this API uh from anywhere all right so let's come back to route. TS file inside this post request I'm going to go to this article and I'm going to copy everything inside this post request from this particular article so let me copy everything copy and I'm going to paste it over here all right make sure this web hook secret is matching with the name of your EnV local yes it's matching and uh let's come down here event type event type is going to give us the type of event which is being triggered from that dashboard currently we have set the event type to user. created uh and uh this is something which we need to detect all right so let's come back over here below this event type and let me add create user in mongod B all right so if event type equals to user do created then we are going to fetch all the data uh from this so if we go over here and click on this web Hook reference then we can see that uh we have this data which is being returned for that user you can see whenever this particular user is created this is the data is going to be returned so we can fetch any kind of data from here um but for now I'm going to get ID I'm going to get email addresses I'm going to get image URL I'm going to add the first name uh I'm actually matching uh uh with few things uh which are added in the user model which I have created using the mongus so these are the properties for that so last name um and then I have also created the username in Mongo's model and then I can add EVT do data all right so after this uh let's create an object for the user so I'm just going to add that particular object this is the user and you can see that I'm setting up the clerk ID using that ID being returned from the event typ from clerk I'm getting an email address from email addresses uh because email addresses uh comes with this array of email addresses all right so username is going to be the username we can append both first name last name sometimes username gets null that's why I've added this exclamation mark after that and photo is going to be the image URL and these are the six properties which I added in this model uh this is the photo which I have set over here here all right so once this is Set uh we can log let me log this user as well to debug if there is any issue and then new user equals to await create user and then the user all right so this is going to create a new user in the mongodb database this is the function added in this action is going to connect to the database it's going to create uh an entry in the mongodb database and after that what we can do is is uh we can actually uh create a check if new user is created new user exists then I'm going to set the metadata in the cler uh this is beneficial when we want to add relationship between users and organizations and the permission within the clerk dashboard so I can write clerk client. users. update user metadata with an ID and then the data so public metadata and then I can write the user ID column new user doore ID all right so after this is set we can simply return the next response so next response uh do Json and then I can write uh message new user created user colum new user all right so I think uh we are pretty much done with this web hook uh the purpose is that whenever the clerk uh user is created it should create an entry in the mongodb database uh so first of all what I need to do is I need to deploy my application again I've have already set the environment variable I've already set uh this middleware made it a public URL and now I'm going to deploy this application again and the way versalis works is uh whenever there's a new deployment in the GitHub repository it auto triggers the new deployment so I can uh deploy git push origin Main and it's going to redeploy all the new changes which I have added uh if I I go over the deployment and it should be rebuilding yes it is rebuilding the project because uh this has been updated again let me verify quickly and U yes you can see that it's showing now because that's why uh we have uh set this out within the source folder um so let's wait for this and once it's going to gets deployed we are going to test this out but once uh meanwhile it is getting getting deployed I'm going to go to the databases for this particular database and there should be no user over here and also I'm going to delete all the users exist in this particular clerk dashboard uh before moving further so that we can test it properly so I've deleted all the users and uh this is deployed as well let's open the application on the URL which it has given to us and now I will try to log in with the user so let's click on the login and I'm going to go with the GitHub for this time and I'm going to click on authorize clerk so let's see if it goes to the profile URL all right so we are successfully logged in and we are navigated to this profile uh this homepage and I can click on the profile and we are successfully logged in and now I'm going to go over here and let's refresh this clerk dashboard and see if the new user is created over here and yes the new user is just created and uh I'm going to go to the web hooks all right so this is the end point I actually deleted the previous uh Endo uh which I showed you before so let's click on that and click on the event log uh I can click on the logs uh so these are the recent ones uh you can see uh you can ignore the the the last three four months I was actually testing this uh so but the user is successfully created um over here and uh if I go over here uh actually see the logs this was the deployment and we can see the logs uh what happened so here you can see that uh there is no error when triggering the/ API SL web hooks SL Clerk and uh this was actually returned from that web hook which we added over here from this response new user uh created all right and now let's go over here and I'm going to uh click on the browse collection and see if the user is created or not all right so the user is created with the same data that was used to create the user in this clerk um and one thing more that uh if you see such kind of error uh like this task timed out and uh there seems that the DB connection is not getting successful uh let me show you that uh you need to before actually log in with the new user you need to go to the network access in the mongolas and you need to add a new IP address and enable uh actually uh include your IP address and add 0.0.0 and make it active so that this particular datab base can be accessed from everywhere okay if you don't do this there might be a chance that you will see such kind of errors all right um I have addit that and uh now the error is gone and here uh you will see in the database the user is created and if I go to this go to the web hook actually go to the users go over click on the user and uh come below and this is the metadata which shows the user ID and this this is the user ID which is showing over here and this user ID uh let's see 1 f78 let's go over here let's click on the Bros collection and it should be matching with the user uh created over here you can see 1 f78 and this is because we added this metadata over here with the user ID with new user andore ID all right so we have successfully integrated our clerk authentication connection with the mongodb database and now uh we can uh add relationship with more mongus models along with this user whenever the user is being logged in uh with clerk uh you can add authentication and add relationship uh by adding more models it can be notes products settings analytics and you can build your own application uh so that's pretty much it for this particular tutorial I hope that you have got an idea how to do these things thank you so much for watching guys don't forget to subscribe my channel and don't forget to like this video I'm going to create more videos on nextjs and building more applications using nextjs so stay tuned thank you so much for watching see you in the next video
Info
Channel: Programming with Umair
Views: 324
Rating: undefined out of 5
Keywords: connect clerk auth with database, nextjs, next.js, web development, next.js 14 auth with clerk, what is webhook, clerk auth webhooks, connect mongodb with clerk auth, next.js 14 tutorial with mongodb, how to connect to mongodb, protect routes in next.js 14, route protection in next.js 14, deploy next.js 14 app, vercel deployment, mongo atlas tutorial
Id: 7xNObOK3AH0
Channel Id: undefined
Length: 37min 36sec (2256 seconds)
Published: Mon Mar 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.