How to Integrate Vercel & MongoDB Step-by-Step

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
getting a mongodb atlas database created and linked to your versailles project has never been easier in this video we'll get everything set up including a starter next js application in just minutes and i'll show you how to properly connect to your database using a serverless function now for this tutorial you are going to need a mongodb atlas account a vircell account and a recent version of node.js everything is completely free and the links are in the description below versailles is a cloud platform for hosting websites and web applications deployment is seamless and scaling is automatic many web frameworks will work with versailles but the most notable is vercell's own nexjs nexjs is a react-based framework and has many cool features like built-in routing image optimization and serverless and edge functions so let's create our starter project and see how it works we'll use the next js mongodb example app to get us started this is going to give us a next.js app with mongodb atlas integration already set up for us we're using the standard npx create next app command along with the dash dash example with mongodb parameter which will give us our fully integrated mongodb application i'm going to put that in the current directory which is what the dot means and then the dash y will bypass the prompts and just accept all of the defaults now at this point we need to configure our manga to be atlas database connection instead of manually setting up our database and connection within the mongodb atlas dashboard we're going to do that all through versailles now before we move over to versel let's publish this project to github using the built-in version control within vs code if you're logged into your github account it's as easy as pressing one button in the source control tab so i'll just type a comment in here init and then publish branch i'm going to name mine versail dash integration and publish this as a public repository if you haven't already signed up for versailles now is a great time to pause the video and go ahead and do that again it's completely free so from your versailles dashboard create a new project and then choose to import a github repository by clicking continue with github i've already connected with github so mine already shows my projects here so i can see my versaille integration repo that i just published and so i'm going to import that it knows that this is a next.js application and everything else should be just fine so let's go ahead and deploy this and this deployment is actually going to fail because we haven't set up our mongodb integration yet we can see here it says please add your mongodb uri to the env.local file so let's go back to the main versailles dashboard and select the integrations tab and then from here we can browse the marketplace and select the mongodb atlas integration then we'll select add integration we'll select our account and click continue then we can choose to add this to all projects or specific projects i'm going to click specific projects and then select myvircell integration and then click continue we're going to give it all these permissions and add integration if you don't already have a mongodb atlas account you can sign up for one on this step but if you already have one you can click login now so that's what i'll do i'll use google this next step will allow you to select which atlas organization you want to connect to versailles you can either create a new one or select an existing one and then click continue and then i acknowledge this final step allows you to select an atlas project and cluster to connect to again you can either create a new one or select an existing one i'm going to create a new atlas project you can select your database location and this is going to be an m0 completely free cluster so let's create the new cluster and return to vircell so now the mongodb integration has been completed let's go back to overview and select our cell integration project then if we go over to settings and then environment variables and we scroll down we'll see this mongodb underscore uri environment variable so vercell just connected to mongodb created a new project for us created a new database created all of the network and user authentication required to connect and added our environment variable to our project all automatic and now this can be used in our next.js application all we have to do now is sync our environment variables to our local environment you can either manually copy and paste your mongodb underscore uri into your local.env file or you can use the versel cli to automate that let's use the versailles cli we're going to add that to our project by running the following command npm i verselle now in order to link our local project with our versailles project let's run versel setup and deploy yes we want to do that which scope that's which account do we want to deploy this to and then it found our project do we want to link it we're going to say yes and it's going to go through the build process and this time the deployment should work so we see we have a preview url here it's already been copied to our clipboard so let's go over to our browser and check that out so this is deployed to versailles and we can see that we are connected to mongodb and everything is working properly and it works this time because the environment variable with our mongodb connection string is already in production but back in vs code let's run the project locally and see what happens so we're going to run npm run dev that's going to start a local server running our application on localhost 3000. so let's open that we can see we're getting that same error as we were before in production please add your mongodb uri to the environment variable and back in vs code we're getting that same error message so the environment variable is in production but it's not in our local environment so we need to pull the environment variables into our project and to do that we can run versailles env pool notice over here we have a dot emv.local.example but we don't have any other environment variable files so let's run this and notice that it pulled our environment variables and we have this new.env file so let's run npm run dev again and let's check it out and now it's working locally as well so now every time we update this local repo and push our changes to github purcell is going to automatically redeploy our changes to production so how is all of this working well it's using a serverless function to connect to our database working with database connections and serverless functions is a slightly different experience than if you were to create your own fully hosted backend using something like no jsn express but why is it different well databases in general not just mongodb can have a finite amount of concurrent connections so when you are hosting your own web application that application is typically connecting to your database one time and it stays connected for as long as that application is running serverless functions though can't stay connected they restart they run on demand which could result in multiple new connections and those connections could exponentially build resulting in exceeding the database connection limits if your serverless function is not configured properly so let's look at some ways to connect to mongodb in a versailles serverless function first let's load some sample data into our database so that we have something to query for this we're going to use the atlas cli it makes it super easy to manage your mongodb atlas databases and projects so if you don't have the atlas cli installed you can run brew install mongodb dash atlas on mac or if you have windows download the msi file from the install page linked in the description after you get that installed run atlas auth login to get access to your atlas project you'll be given a one-time verification code that you can enter in your browser and then confirm authorization and we can see that we have successfully logged in now we can load some sample data by running atlas clusters load sample data cluster 0 assuming that your cluster is named cluster 0. this is going to load several sample data sets and it takes a few minutes to load but we can move on while it's doing that so now how do we properly connect to our database using a serverless function well nextgs is one of those technologies where there are a few ways to solve the problem we could interact with mongodb at build time creating a 100 statically generated website but many websites require dynamic data and that's where serverless functions come in first let's look at the wrong way of connecting to your database in a serverless function in xjs we can create serverless api routes in the pages directory so let's create a folder called api within that a file called wrong.js now before we write this file let's take a look at our package json so in here we'll see that we have our dependencies of react react-dom burcell next and we have this mongodb package so we're going to be using this so first we're going to import the client from our mongodb package after that we're going to get our mongodb uri environment variable and then we can optionally put some options here as well but we're going to leave this blank then we're going to check to make sure that we have our mongodb uri remember at first we were getting that message please add your mongodb uri to your environment variable file so that's where this check comes in if we don't have a uri we're just going to stop right there and throw an error next we're going to define our serverless function so invercell serverless functions always look like this we're going to export a default async function that is called handler and it has a request and a response since this is an async function we're going to add a try catch block and then within our try we're going to create a client which is going to await a new client and we're passing in our uri our options and then we're going to connect now let's add a console log here just to show every time we connected we're going to get a log that says just connected after that let's connect to our database and perform a query let me get rid of the sidebar to make this a little bit more readable so we have our client then we're going to set our database so remember we loaded some sample data so we're going to use the database that's called sample underscore restaurants then we're going to select our collection which is going to be restaurants and then we're going to get our results our results are going to await our dot find we're going to find everything and then we're just going to project certain fields that we want the grades the borough and the restaurant id since there are so many restaurants in this database we're going to limit that to four and then we're going to turn that into an array that we can then return to our client so to return that we use our response so we're going to say response status of 200 and then json passing in our results and then finally in our catch we'll console log our error and then send a response of status 500 and then also our error in json format so again this is the wrong way of doing it and we're going to see why let's save this open up our console let's do npm run dev and we'll go back to our localhost 3000 now remember we created an api route so to get to that api route we're going to go localhost 3000 slash api wrong and now we can see that we are returning data and also in our console we can see that we've just connected let's refresh this a few times and see what happens you see that every time we refresh we get that just connected console log so it's creating a connection every single time if we have thousands of users and they create a new connection every single time they request something from our database that could get out of hand very quickly we need each user to be able to reuse their individual connections so to fix this we can move the connection logic into a library file within the app this will allow each connection to be managed in the browser by each site user so you'll notice here that there is a lib folder and there's a mongodb.js file in there already and we're going to get to this file in a bit but for now let's create a new file we're going to call it connect to database.js and we're going to do a lot of the same things here we're going to import our client we're going to get our uri but now we're going to declare a variable that is client now this is going to become our cached connection we're going to run our check to make sure we have our uri throw an error if we don't and now we're exporting an async function that is called connect to database the first thing we're going to do here is we're going to check to see if we already have a cached client if we do we're going to return that client if we don't then we're going to create a new client and we're going to console log just connected just so that we can see how many times we connect then we're going to return that client and of course if we have an error we'll console error the error so again we only need to establish a new connection if one doesn't already exist remember connection quantities are finite and we should only connect if we aren't already connected so we have this utility file now that acts as a connection management system for mongodb and we can use this in our serverless function now so let's configure that next we're going to create another file under api called list.js so this is a serverless function but this time instead of importing the client we're going to import our connect to database utility file and then next we're going to do all of the same things that we did before we have our serverless function here we have our try catch block now this time we're creating a client that is coming from our connect to database utility function and then we're doing all the same things as we did before we're connecting to our database sample restaurants connecting to our collection restaurants and then we're doing our query here we're returning our response everything just like we did before but now we are using our cached connection utility file so let's save this and give that a try go back over to our browser now this time instead of going to slash api slash wrong we're going to go to slash api list and we can see we get our list now and it says just connected let's refresh it and now you can see on each refresh we're not getting a new connection but it's reusing the existing connection so when we execute the function we're getting a connection without worrying whether we need to create one or reuse one the underlying function code handles all of that for us now if we look at our cluster metrics in the mongodb atlas dashboard we can look at our connections and we can see when we ran the wrong api how many connections it created and then when we used our cache connections not as many connections were created another way to manage our connections is by using javascript modules and that's exactly what this mongodb.js file does this utility file was included in the next.js template that we used so let's take a look at this the top part should look very familiar we're importing our client we are getting our uri and then we're setting two variables client and client promise we're checking to see if we have a uri and throwing an error if we don't we're also checking to see what environment we're in if we're in development we're going to create a new client and then we're going to also set a global client promise and connect to that if we're in development we'll create this global variable that will persist through reloads if we're in production we're going to create a new client and also create a client promise then at the bottom we're exporting this module scoped client promise let's add a console login here so that we can see when this connects as well let's go back to our list api and now instead of using this connect to database utility file let's use our client promise from our mongodb utility file so we're going to import this client promise and then our client is going to await our client promise and then everything else is going to be the same so let's save that go back to our browser and give that a shot all right so let's refresh this we're still on our slash api slash list route so we see that we're connected let's refresh again and again it is reusing our connection it's not creating a new connection every single time so the module scoped approach runs only once and will not cause any connection pooling issues and we can use this client promise now in any of our serverless functions so now how do we consume this endpoint within our next js application let's open up the pages index file so this is our main application page now before we make any changes here let's see what's going on notice that we're importing the mongodb utility function in this file that's because all the way at the bottom we're going to use that in another serverless function now this is a next.js specific thing git server side props will run server side on every render and it's checking to see if we are connected so this is yet another way that we can use this utility function in a serverless way this function returns our connection status so if we scroll all the way back up to the beginning of our home component we'll see that it is getting our is connected state here and we can now use this connection status in our rendered app to determine what will display but now let's see how to display our data from the list endpoint that we created at the top first we'll need to import use effect and use state we're going to use those since we're dealing with restaurant data we'll create some state called restaurants and set restaurants and the initial state is going to be an empty array next we'll create a use effect and in this we'll have an async function which is going to use fetch to get our api list route and then we'll get our results json and then set our restaurants to our results json so we can now render this data in the application so let's delete some of this template content so we're going to add a grid here that maps through our restaurants displaying their name and the cuisine type so there isn't anything really out of the ordinary happening here in this process of consuming or rendering the data the heavy lifting that was important was that function as well as the connection management file so let's save this and check the app out in the browser so now we're at localhost 3000 and we can see a bunch of restaurants now in a grid it has the restaurant name and the cuisine type so now you should be able to set up a versaille project link it to a mongodb atlas project and cluster and use mongodb atlas with for cell serverless functions these same steps will work with any javascript framework it's not next.js specific now remember when dealing with serverless functions you have to manage your connections you don't want to spawn too many connections and you don't want to attempt to use connections that don't exist if you have any questions or feedback check out our mongodb community forums and let us know what you think if this video was helpful give it a like and subscribe for more content like this you
Info
Channel: MongoDB
Views: 16,912
Rating: undefined out of 5
Keywords: mongodb, javascript, vercel, da
Id: JIlYroSsInU
Channel Id: undefined
Length: 20min 20sec (1220 seconds)
Published: Tue Aug 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.