Connect Google Provider to Database - Next Auth

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up YouTube my name is Brett and today I'm going to show you guys how to use the Google provider inside of next auth so you could take that user and then store that user inside of a mongodb database using Mongoose okay so let's just jump right into the coding so what I did here was I opened up my terminal on my computer and I created a next app at latest which is a next js13 application as you can see that's what I answered for all the questions that asked when you create a project and then it just initializes the project installs the dependencies and then it creates this boilerplate index.js13 application so now we're here and we have app folder and the first thing I want to do when we want to use next auth and mongodb is I like creating the database first so we have that out of the way so like we said in the title we are using mongodb so all you have to do is go to your browser go to google.com you could type in mongodb and then it should be the first option and then after that you're going to sign in you could either sign in with your Google account your GitHub account or with an email address I'm just going to use my Google foreign in you should be on a page something similar to this and you could create your database by either clicking the right here that says create or you can go right here to the top left where all of your projects are and then click new project and then after you click new project we have to give the project a name so what we could do here is we could just do next auth and mongodb so after that is done we will click create project and then it is going to ask you to build a database so we're going to build a database and we are going to use the free version and this is for Learning and exploring mongodb in a cloud environment we are going to use the AWS provider your region it should be whatever the recommended region is with the star and then your cluster name really doesn't matter but it says you cannot change the name of the cluster once it's created we will keep it as is which is cluster zero so then you click right here at the bottom and then we have to have a username and password so this step is very important this is how we're going to be able to connect the URI to our application so I'm just going to put the username as B Westwood 11 you could do whatever name you want I'll keep the auto generated password that they gave me I'm going to copy it and then store it in my notepad so I have it for later so here it is and then when you click create user it's going to hide your password so don't click it until you actually know what your password is so after you do that as you can see we created a username and email I mean username and password now we are just going to use the local environment and then you could add your IP address right here or you could put 0.0.0.0 forward slash zero I will write that on the screen so you guys can do that and that means you could use this database from any IP address so after you do that we click finish and close go to databases and ours was instant there are databases created instantly because we see the green right here that says status is active sometimes it takes a few minutes but other than that you have successfully created your mongodb database for use and to connect it all we're going to do is we can go to the connect here we go go to our drivers which is the first option and then it says we need an installer driver which is mongodb and then we have to add the connection string into our application code so let's copy this application string or you can just press copy here and then we are just going to X minimize this page now we were on our code let's create on the root layout of the whole code a DOT env.local so this is we're going to keep our environment variables we can name this underscore URI equals and then you paste your code that you just had this is the connection string and then where it says password right here we have to replace that password with the password that we got inside of the username and password we created so in that notepad that I saved we could take this password and then paste it in right here so now we've replaced that password with password and now we have a connection string that now we could actually connect mongodb to our application let's install a few packages that we need to install to ensure that the process works so I'm going to open up my terminal down here and we're going to say npm install in the first package to get out of the way is next Dash auth that's allowsing us to use next auth next one will be Mongoose this is going to allow us to connect mongodb to our actual application and then we're going to install mongodb which is the driver allowing us to use that URI right here on the screen so we are going to press enter and then if you want to see the versions I have for the specific project I'll go my package Json and I have version 5.6 for mongodb 7.3.1 for Mongoose and version 4.22.1 for next auth so all them successfully have um downloaded now let's make a file that allows Mongoose to make this connection to our application so to do that inside the root we can create another folder and we will call this utils and then inside I like creating a file called database dot JS you could name it db.js that's short for database by just like typing out the full word we're going to import the package Mongoose from mongoose and we are just going to have a function in here that we're going to export so we're going to say export cons and we could call this whatever we want um we could say connect DB so database this is going to be an asynchronous function and inside of this we could have a try catch block so as you can see this Auto completion code for me this is a GitHub copilot I know I've had a few people ask me what it is so if you're wondering that's what it is I'll just you can search GitHub go Pilots about ten dollars a month and I think it's worth it for sure so right here we just have a try catch block and inside of the try we are going to await a mongoose connection and we have to wait it because it is asynchronous and it will take time and we are going to be able to access the environment variables by saying process.env underscore URI and then we could pass a few options if we want and as you can see my um Gap copilot is telling me uh recommendations that I could do so we could do a used URL parser true we could use unified topology as true and we could create a database name so database name and this was what's going to show up inside of our database the name and we could just say user um you could just do a user DB whatever you want I'm just going to say user so that's going to be our database name right there and then if that connection Works let's just do a console.log saying mongodb connected and then if we get an error let's just console log the error.ms console log the error okay so we have this and now all we have to do is we are actually exporting it so now we could use this file anywhere inside that we want to connect to our database just by calling the connectdb function now I want to quickly test out to make sure our connection on mongodb is actually working so to do that we have to actually invoke this function and what I'm going to do is I'm going to go to the page.js inside of the root file of the app which is the home page I'm going to remove everything inside of the return we could just put a section tag and then inside it we could just say H1 of home page and then what I want to do is I am going to remove this import of image mark this as a used client just for now and then I am going to import connect DB from that utils folder inside the database file and then we can just say cons DB equals connect to DB and then what we could do here is if your server isn't running you say npn rundev npm run Dev and then when you open up localhost 3000 like I just did control click local 3000 we should get a message in the server right here in the console that says mongodb connected because if it didn't connect inside we'll get the catch error and it'll be the console.log error instead of mongodb connected so our mongodb connection string is working and everything is good to go now we need to create a user schema so this is a model that allows us to Define the types that we're going to send to our database and what the property names are going to be so to do that we create another folder inside the root called models like that and then the file inside of that should just be the name of the model you're creating to keep everything pretty consistent so ours could be user.js it doesn't have to be jsx and inside of this like I said we are defining the types and we have to import a few things so the things we have to import are and curly braces the schema the model and the models and this is going to be from mongoose just like that so what we are going to do here is we are going to say user schema we could do this capitals user schema and it's going to equal a new schema and it's going to pass through an object and inside this object we are going to define the properties and the types that we're going to send back to mongodb database so the first one we can have will be a email and actually before I even do this I want to show you exactly why I am doing these properties so I'm not even going to do the schema yet let's start working on the next auth so to do that the reason why I'm doing the next auth like I said I want to show you the properties and why I'm passing these properties into this user schema so to create your next auth and start your next auth you can watch my full tutorial on the ultimate guide next auth I will link it up at the top so you guys could click that and go to that video other than that we are going to create a folder inside of app called API and then inside that folder we're going to have another folder called auth and then inside of that folder we're going to have a catch all folder which is going to be next auth and brackets and it's dot dot dot dot dot dot next auth and brackets and then we have a route dot JS file and then inside of this this is our entry code into next auth so this is how we're connecting next auth so we have to import next auth from forward slash next as you see at the top and then we must import the provider we want to use as well so we're going to say Google provider and it's from next Dash auth forward slash providers forward slash Google and then we will also be importing our user schema model and we have to import the database connection because we have to connect to the database every time we run a function for Mongoose or mongodb okay so we're going to add one more import later but those three are good for now so we have to define a Handler and this Handler is going to equal next auth object and we're going to pass in a few options into the next auth function right here so the first one is going to be the providers we have to say what providers we're using so we're using the Google provider and then it's going to pass in a few options and it's going to pass in the client ID and the client Seeker so what I could do here is to is we could copy this Google ID put it in the EnV logo and we are going to paste because we're going to get a value for that we go back to our route and we have a Google secret as well and we're going to copy we're going to go back in the EnV local and then we're going to have a Google secret as well then you can put equal signs and equal signs and what we can do here next is we can actually go inside of the Google Cloud console and get those specific values which is the client ID and client secret so on Google all you have to do is type in Google Cloud console inside it should be the first option and then when you land on page like this and if you don't it's because you're not logged into your Gmail account which I am here at the top and what you can do here is you can go click this button it's like a down click and you could click new project and then we can name the project wherever we want we can name this next auth video Tut you could keep the organization as is an organization and then it is going to create the project here as you can see it's loading and then if you're inside of the project you will know because whatever you named it it should be popping up right here so I'm going to click select project and use as you can see there's my project we are going to go to API and services inside of API and services the first screen we want is the oauth consent screen this allows us to use the Google services to log into our Google account and so we don't have to create a username and password so we're going to click the oauth consent strain you could click external because this allows any user to test with the Google account we need an app name what we can name it here is we can name it um we can name it anything we want we can name it like test our support email is going to be da Westwood gmail.com that's my email and then you have to do your email again down here and then we're just going to click save and continue you don't need to fill out any of the other fields and you could always come back to these options to fill them out we're going to add three Scopes we're going to add the first three one two three click update and then just we don't need any test user so we're going to click save and continue and then it's just a summary of everything you did so after that we are set with the oauth consent screen and now we need the credentials so the credentials allows us to actually use the auth consent string and it gives us these values that we're looking for so we are going to create credentials for the oauth client ID what we're going to do is we're going to click web application I'm just going to keep the name as web client one you should change it and then we have authorize redirect URI and this has to be localhost 3000 forward slash API forward slash auth forward slash callback forward slash Google and then if you're using a different provider you just replace Google whatever with whatever provider you're using and obviously if you're not using Google you're not going to be using this specific service of Google Cloud so this should be the specific redirect URI that you need to use and if you don't you're going to get an error thrown at you so we're going to click create and after we click that we get the client ID and the client secret and that's what we need so we're going to copy the client ID go back to our um project and we're going to paste the ID there and then we're going to go back and we're going to get the secret we're going to go back to the project and then we're going to paste the secret here perfect so now we have our values and we are done with the Google Cloud console so what we can do here is we could just close this up and we can leave the mongodb database up and we can minimize it go back into our code editor and let's go back to our catch all route which is this Google provider so now we've said that we are using the Google provider and then after that an option that we're going to use is we are going to use callbacks so if you look at the docs of next auth these are pretty much asynchronous functions that allow us to do a certain uh reaction or interaction when a specific callback is called so we are going to be using two of them and the first one we are going to use is we are going to use the session so it's like that and it is passing in the session as a pram and then for now we are just going to return the session because we'll work on this code in a little bit because we have to finish a few other things up so after that we have a comma after this and the other callback function we are doing is the sign in like that and then we are passing in the profile so the profile we're passing it as a pram so we can access it inside of this sign in function and the profile is going to be the Google profile of whatever account you log into so I'll show you exactly the properties that we get from the profile so what we could do here is we can console log the profile so you can see what it is when we actually log in so I have that for now and then what we are going to have here is we can have we are going to await the connect DB because we have to actually connect to the database and then what we could do here is we could check to see if the user exists in the database and then if not we're going to have to create a new user in the database so what we could do here is I want to show you the properties before we even continue so this is going to return true because if it returns true that means it was successful and if it returns false that means it's not successful so what we can do here is Right Above This we could add a try catch because we do want to return false because that would actually give us an error message so I'm going to put this aside to try and then we'll have a catch error and then we'll have a console log of error returning false okay we will come back to this code right here but like I said I want us to actually log in to the Google provider and show you exactly how the profile properties and parameters look so what I'm gonna do here is first I'm gonna go in the global CSS remove lines 5 through 27 make it look a lot cleaner we will go inside of the page.js which is the home page remove this connection and the use client that we just did earlier and what we are going to do here is we can actually keep this as a used client because we're going to actually access the use session hook so we're going to have the use session hook which is going to allow us to actually see the session of the user and make sure we're logged in and this is from forward slash react we are also going to have the sign in function which allows to sign in and then we're going to have the sign out as well because we do want to sign out and so the sign and decide on functions are very easy to use what we can have here is we could have um an H2 that's a sign in with with Google and then below that we could have a button that says sign in and the button is going to have an on click with the anonymous function that is going to have the sign in function like that and then we are going to pass in a string called Google because that is the ID of what we're trying to log in with which is Google if it's GitHub you're going to put GitHub if it's credentials you'll pull credentials if it's whatever the provider is that is the name you'll put inside of a string so what we could do here is we have um we're not tracking the session here which is not a big deal we are going to sign in with Google and then when we sign in it should call these callback functions here and we should be able to get the profile and we're going to console log the profile and the console log should pop up inside of our vs code editor since it is a server-side page so I'm going to move localhost 3000 over we are going to click sign in with Google and it should redirect us to a oauth consent stream which allows us to log in with our Google accounts and if that doesn't work we could obviously troubleshoot it so we click sign in and it says there is an error so we do have some errors here there is no HTTP methods exported inside of our catch-all route so that would help so we do inside of the route I actually didn't finish at all pretty much jumping the gun there and what we have to do is we have to export the Handler because we have no access to it and the way you export this Handler since it is a catch-all is we are exporting the Handler as a get request and the Handler as a post request because those are the two htc HTTP methods that this specific catch all route uses okay so now let's try it again so we're going to go to localhost 3000 nothing is styled here like you see it's pretty bland so we're going to click sign in which is technically a button and as you can see it redirect us to this oauth consensus ring I'm going to press my Google account and then we are back to the home page perfect so now I'm going to go back to our console log right here inside of our server and as you can see here is our profile and our profile has a bunch of different properties like email name picture family underscore name give an underscore name we have the email underscore verified true we have it issued at an expiration token and we have saying in mongodb is connected so this is what we're gonna have to do we are going to have to now create that user schema that I was talking about because inside of the user schema we are going to get some of these properties because we want to get these properties and then store them in a database to keep the user secure in our database so the properties we want to pass to our database from the profile the Google profile that you see here is going to be the email which is my email right here we want to pass in the name and then we also want to pass in the picture because the picture is going to be it could be used as an avatar if you have a user logging into a specific application on your project so those are going to be the three properties that we're going to get so what we can do here is I'm gonna minimize the terminal real quick and inside the models and then the user.js we can actually start completing the schema so we can um say the types and the properties we want to our database so we're going to call this a user schema and it's going to equal a new schema and then like I said it's going to pass in objects with a few properties and the properties are going to be the profile on props that we saw just right now so the first one is going to be email and the type is going to be a string and we will have it as unique because we only want one email per account that is going to be our unique identifier also with the ID so we're going to have true that has to be unique and then we could have a string that says email already exists if it becomes false another one is we could have it required as true and then we can say email is required so that is our email schema right there property inside of the user schema now we're going to have a name and the name is going to be like that Brett Westwood and we're going to have a type as a string and it's going to be required true and it's going to say the name is required if it's false we're going to have another comma and we're going to have the image in the image is all it is is a string like a JPEG so whatever the full URL is dot jpeg.png whatever the image is it's a string so now let's close this schema by going like this semicolon and then we are going to say cons user and this is going to create a models.user well no this is going to store the user inside of the models.user or if there is no models.user then we are going to create a user model using the user schema function up there so that's what this line of code means so either we're going to create the models.user using the second uh parameter right here or we're just going to store it in the models.user if it already exists and then we just have to export default the user okay so now we start using methods that Mongoose allows us to use all throughout application because we exported this file so now we want to go inside of our route and at the top we are going to import would that name a user with a capital u from at four slash models forward slash user and now we can actually start using methods to create users to find them in our database and etc etc so what we are going to do is first we can actually work on the sign in asynchronous function here so we console log the profile and that's what we got earlier so after we console log it inside of the try we are connecting to the database with this line of code then next we can say cons user exist user exist equals a weight and then we're using the method user.find1 and like I said we are going to look for the email so the email we're gonna have to use the profile that we're passing into this function so it's going to be profile dot email just like that so now if we find one of these that means we have a user and the user exists and we're just going to store it in this variable and then if the user doesn't exist we're going to say if the user doesn't exist we're going to create a new user so we're going to say user equals await and then it's a user.create and then we're going to get the email and all of these properties here on the left of the semicolon they have to match up with your schema so they have to be email name and image and then like I said we are getting the email name and image from the profile the profile object right here so this is going to be profile dot email which is that Google email next one is going to be name so it's going to be profile.name and then the image is going to be profile dot picture reason why is if you see right here the property is called picture and not image and it gives us that string right there so that's why it's profile.picture we're going to close the user and then we are going to close this again and then we we return true up here just making a code a little cleaner there we go and then we could keep the catch section the same everything is good to go and now we can actually test out to make sure we are sending a user to our database inside of the user models so we tested out that our Google sign in works because we wouldn't have gotten this information from the profile if it didn't now we are going to test out to see if the storing and the database works so what we are going to do here is I am going to go back into the home page real quick and I'm going to add another buy-in because I want us to be able to sign out so we can test this out so we're going to say sign out with the capital O we're not passing anything into the sign out function from nexauth and what we're going to do here is just to sign in it's called sign out and then we're just going to sign out you're not gonna be able to tell you signed out unless you console log um a few things but we are technically signed out now and what I want to do is I want to open up that mongodb database so I'm going to drag it here and we are going to sign back in and we should be able to send this Google provider profile to our database so we're clicking sign in we're signing in with our Google provider click Diego Westwood and now let's check our database so I would refresh the database and then we could browse the collection and then we have a user with the user and as as you can see we have those properties we defined in our schema in here and we matched it up with the profile properties so we have my email name and image so that is how you successfully push a user from the next auth Google provider into your mongodb database and the final step is I want to show and attach an ID to that user because it could be very useful to have an ID on a user because using Dynamic data you do want to make sure you find a unique property you can use the email but a lot of people like using ID so I'm going to show you how to do that so if you go back inside of your route which is your catch-all route and inside of the Callback and then inside of the session asynchronous function we are going to right above the return session we are going to start writing some code so we're going to call a session user and this is going to be a weight and we're going to do user.find1 and we're going to get the session.user.email and you want to know why I'm using session.user.email I will show you because I feel like a lot of people don't show the properties and people could get confused because you might just push session.email and you'll get an error so let's go to our home page and let's use the use session hook now so to use the use session Hook is the easiest way to get a session data and show it in the front end so all you have to do is pass in a curly brace and we're getting the data but we're just going to rename it as session and then what we can do here is we can console.log the session so we can see what it is and I am actually getting an error because before you can actually use the use session hook you have to wrap the whole application in a provider so we have to create a new folder called components and inside of components I'm gonna have a new file called provider Dot jsx and what we can do here is we can Define the provider and you can Define the provider and the layout uh JS file which wraps the whole application on the root layout but it is a used client file and you want to keep your layout as a server side rendered page so that's why I'm creating the provider in a separate file because I'm going to mark this as a used client and then what I'm going to do here is I am going to import the session provider and this is going to be from next Dash auth forward slash react and then what we're going to do here is we're going to say cons provider is going to take in the children and is also going to take in the session and what we're going to do here is we are going to re have a return inside of the return we're going to wrap everything in the session provider and passing in the session as well as you see there we're going to wrap all the children and then we're going to close the session provider let's end these curly brace off and then let's export this file as well export default provider now we can go inside the layout.js and we can import that at the top so we're going to import provider from at components forward slash provider then we are just going to wrap all the children with that as well so now we could use that use session hook so provider wrapping it like that and we could just put the children right in between and now we wrapped our whole application with the session provider allowing us to use the use session hook which is right here and we are going to get the session inside of our client-side console so I'm going to open up localhost 3000 again and what I'm going to do is I'm going to refresh the page we should be signed in I'm going to console log and I'm going to make this a little bigger and as you see we can object and in the object we get an expires and then we get a user and then with the email image and name so we get those three properties and then inside of the three properties that's surrounding it we have a user so as you can see here inside of our route that's why it's session dot user dot email because if you look at the console that is the way it's set up and that is how you'll be able to access the email so we are going to find a unique user inside of our database that's what we're saying here with that specific user I mean that email and then we're going to store it inside of the session user so now we have access to the user that's logged in and all we are going to do is we're going to say session.user.id and it's going to equal the sessionuser dot underscore ID and the reason why it's dot underscore ID is because if you go to the database in mongodb that is how they Define their IDs in there and then we're just storing inside of this session.user.id so now if we save this I might have to sign out but let me refresh this page go back and then let's see the properties and as you can see now I added the ID now to our session provider so now we can use the ID if we need to and this ID right here is going to match up to the ID inside of your mongodb database and then you could click sign out and as you can see here it says undefine a null so now our Google provider is working we're able to send our user to our mongodb database and we're able to successively pretty much extract all the properties we need to use them in a useful way for application so if you have any questions or anything was very confusing leave a comment down below this video and I'll come help you also we do have a Discord so if you do want to join that I'm going to have the link in the description as well I do usually answer comments within 24 hours or less and I do have a lot of other videos about next.js next auth session providers stripe whatever you need that's front and back in react you should subscribe to this Channel and also like this video for more content like this other than that have a good day and happy coding
Info
Channel: Brett Westwood - Software Engineer
Views: 384
Rating: undefined out of 5
Keywords: Next Auth, next auth google provider, next auth google sign in, Next Auth MongoDB, Next.js authentication, next js authentication tutorial, next.js 13 tutorial, next auth tutorial, next auth google, mongoose Mongodb, connect mongodb with mongoose, connect mongodb with reactjs, how to use next auth, reactjs tutorial, authentication next 13, next js authentication and authorization, authentication nextjs app router, mongodb tutorial, google auth provider, react tutorial
Id: I_YCC_nFt70
Channel Id: undefined
Length: 39min 59sec (2399 seconds)
Published: Wed Jun 28 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.