From the course: Next.js 14 from Scratch: Build a Real-World Project Using Next.js 14 and MongoDB
Unlock this course with a free trial
Join today to access over 25,200 courses taught by industry experts.
Save user to database and session - Next.js Tutorial
From the course: Next.js 14 from Scratch: Build a Real-World Project Using Next.js 14 and MongoDB
Save user to database and session
In the last video, we set our button and we connected it to the Google provider, which works. But when they log in, we need to do a couple of things on our side. We need to check if the user's in the database. If it's not, we need to save it. And we also need to assign the user ID from the database to the session. So we're going to do that in our auth options file, which is in the Utils folder. We already have the steps numbered here. So let's bring in up at the top. So first, we want to import our ConnectDB. And then we're going to be working with the user model. So let's say import user from app models user. And then we'll go down to our sign-in. Let's connect to the database. That's simple. We just need to do await and then ConnectDB. Then we want to check if the user exists. So let's create a variable called user exists. And we'll set that to await, use the user model, and then find one. And what we're going to do is find the user by the email, which we now have access to through…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.