How to Integrate MongoDB Into Your Next.js App
Rate this tutorial
Are you building your next amazing application with
? Do you wish you could integrate MongoDB into your Next.js app effortlessly? Do you need this done before your coffee is done brewing? If you answered yes to these three questions, I have some good news for you. We have created an official
integration that will have you up and running in minutes, and you can consider this tutorial your official guide on how to use it.
In this tutorial, we'll take a look at how we can use the
to create a new Next.js application that follows MongoDB best practices for connectivity, connection pool monitoring, and querying. We'll also take a look at how to use MongoDB in our Next.js app with things like serverSideProps and APIs. Finally, we'll take a look at how we can easily deploy and host our application on
, the official hosting platform for Next.js applications. If you already have an existing Next.js app, not to worry, simply drop in the
into your existing project and you are good to go. We have a lot of exciting stuff to cover, so let's dive right in!
For this tutorial you'll need:
React and Next.js familiarity is expected to get the most out of this tutorial, but I will try to cover unique features with enough depth to still be valuable to a newcomer.
If you're not already familiar,
based framework for building modern web applications. The framework adds a lot of powerful features such as server side rendering, automatic code splitting, incremental static regeneration and much more that make it easy to build scalable and production ready apps.
To create a new Next.js app with MongoDB integration built-in, execute the following command in your terminal:
We are using the
npx create-next-appcommand and are passing the
--example with-mongodbparameter which will tell
create-next-appto bootstrap our app with the MongoDB integration example. Finally
mflixis the name of our application. You can name your application something else if you'd prefer. Executing this command will take a couple of seconds to download and install all the npm dependencies, but once they're downloaded and installed, navigate to your project directory by running:
In this directory, let's start up our application and see what happens. To start our Next.js app, in the mflix directory execute:
Once the app is built, let's see our app in action by navigating to
localhost:3000. Uh-oh. We got an error.
The good news is that the error is fairly descriptive. The reason for this error is that we haven't provided our MongoDB connection string to the Next.js app. Let's do that next.
If we look at our Next.js application directory, we'll find a
env.local.examplefile. Let's rename this file to
env.localand open it. This file will contain two properties that we'll need to fill out:
We'll get this information from our
. You can use a local MongoDB installation if you have one, but if you're just getting started, MongoDB Atlas is a great way to get up and running without having to install or manage your MongoDB instance. MongoDB Atlas has a forever free tier that you can
as well as get the sample data that we'll be using for the rest of this tutorial.
To get our MongoDB URI, in our MongoDB Atlas dashboard, hit the Connect button. Then the Connect to your application button, and here you'll see a string that contains your URI that will look like this:
If you are new to MongoDB Atlas, you'll need to go to Database Access section and create a username and password, as well as the Network Access tab to ensure your IP is allowed to connect to the database. However but if you already have a database user and network access enabled, you'll just need to replace the
<PASSWORD>fields with your information.
<DBNAME>, we'll load the MongoDB Atlas sample datasets and use one of those databases. To load the sample datasets, in your MongoDB Atlas dashboard under your chosen Cluster, click the
...button and hit Load Sample Dataset option. This will take a few minutes to load the data and create the various databases. The one we'll use for this tutorial is called
sample_mflix, so you'll set your
<DBNAME>value to that.
To close out this section, our
env.localfile should look like this:
To make sure our configuration is correct, let's restart our Next.js app by going to the terminal and building the application again. Execute the following command in your terminal:
When the application is built, navigate to
localhost:3000in your browser and you should see the following:
This is the
with-mongodbNext.js app welcome page. If you see the message "You are connected to MongoDB", you are good to go. If you see the message "You are NOT connected to MongoDB", then verify your connection string and make sure that the database user as well as network connection is properly set. If you run into any issues, head over to the
, and we'll help troubleshoot.
Now that we are connected to MongoDB, let's discuss how we can query our MongoDB data and bring it into our Next.js application. Next.js supports multiple different ways to get data. We can create
, get data by running
for a particular page, or even
by getting our data at build-time. We'll look at all three examples.
The first example we'll look at is building and exposing an API endpoint in our Next.js application. To create a new API endpoint route we will first need to create an
apidirectory in our
pagesdirectory, and then every file we create in this
apidirectory will be treated as an individual API endpoint.
Let's go ahead and create the
apidirectory and a new file in this
movies.js. This endpoint will return a list of 20 movies from our MongoDB database. The implementation for this route is as follows:
To explain what is going on here we'll start with the import statement. We are importing our
connectToDatabasemethod from the
util/mongodbfile. This file contains all the instructions on how to connect to our MongoDB Atlas cluster. Additionally, within this file we cache the instance of our connection so that subsequent requests do not have to reconnect to the cluster. They can use the existing connection. All of this is handled for you!
Next our API route handler has the signature of
export default async (req, res). If you're familiar with
, this should look very familiar. This is the function that gets executed when the
localhost:3000/api/moviesroute is called. We capture the request via
reqand return the response via the
Finally, we call the
res.jsonmethod and pass in our array of movies. This serves our movies in JSON format to our browser. If we navigate to
localhost:3000/api/movies, we'll see a result that looks like this:
We can add additional API routes by creating additional files in the
apidirectory. As a homework exercise, why don't you create an API route that returns a single movie based on a user provided id?
To give you some pointers, you'll use
to capture the
id. So if a user calls
http://localhost:3000/api/movies/573a1394f29313caabcdfa3ethe movie that should be returned is Seven Samurai. Another tip, the
_idproperty for the
sample_mflixdatabase in MongoDB is stored as an ObjectID, so you'll have to convert the string to an ObjectID. If you get stuck, create a thread on the
and we'll solve it together! Next, we'll take a look at how to access our MongoDB data within our Next.js pages.
getServerSideProps()method forces a Next.js page to load with server-side rendering. What this means is that every time this page is loaded, the
getServerSideProps()method runs on the backend, gets data, and sends it into the React component via props. The code within
getServerSideProps()is never sent to the client. This makes it a great place to implement our MongoDB queries.
Let's see how this works in practice. Let's create a new file in the
pagesdirectory, and we'll call it
movies.js. In this file, we'll add the following code:
As you can see from the example above, we are importing the same
connectToDatabaseutility class, and our MongoDB query is exactly the same within the
getServerSideProps()method. The only thing we really needed to change in our implementation is how we parse the response. The
getServerSideProps()return method has some trouble serializing our data. There is a
to address this, but the current workaround is to stringify and then parse the data manually.
Our page component called
Moviesgets the props from our
getServerSideProps()method, and we use that data to render the page showing the top movie title, metacritic rating, and plot. Your result should look something like this:
This is great. We can directly query our MongoDB database and get all the data we need for a particular page. The contents of the
getServerSideProps()method are never sent to the client, but the one downside to this is that this method runs every time we call the page. Our data is pretty static and unlikely to change all that often. What if we pre-rendered this page and didn't have to call MongoDB on every refresh? We'll take a look at that next!
For our final example, we'll take a look at how static page generation can work with MongoDB. Let's create a new file in the
pagesdirectory and call it
top.js. For this page, what we'll want to do is render the top 1000 movies from our MongoDB database.
Top 1000 movies? Are you out of your mind? That'll take a while, and the database round trip is not worth it. Well what if we only called this method once when we built the application, so that even if that call takes a few seconds, it'll only ever happen once and our users won't be affected. They'll get the top 1000 movies delivered as quickly or even faster than the 20 using
serverSideProps(). The magic lies in the
getStaticProps()method, and our implementation looks like this:
At a glance this looks very similar to the
movies.jsfile we created earlier. The only significant changes we made were changing our
limitfrom 20 to
getStaticProps(). If we navigate to
localhost:3000/topin our browser, we'll see a long list of movies.
Look at how tiny that scrollbar is. Loading this page took about 3.5 seconds on my machine as opposed to sub-1 second response time for the
/moviespage. The reason it takes this long is because in development mode the
getStaticProps()method is called every single time (just like the
getServerSideProps()method). But if we switch from development mode to production mode, we'll see the opposite. The
/toppage will be pre-rendered and will load almost immediately, while the
/api/moviesroutes will execute the server-side code each time.
Let's switch to production mode. In your terminal window stop the current app from running. To run our Next.js app in production mode we'll first need to build it, then we can run the
startcommand which will serve our built application. In your terminal window execute the following commands:
When you run the
npm run startcommand, your Next.js app is served in production mode. The
getStaticProps()method will not be executed every time you hit the
/toproute as this page will now be served statically. We can even see the pre-rendered static page by navigating to the
.next/server/pages/top.htmlfile and seeing the 1,000 movies listed in plain HTML.
The URL I'll use is the one provided above that has the application we built today. For reference that URL is
https://github.com/kukicado/nextjs-with-mongodb. Add your projects GitHub URL and hit Continue. On the next screen, you'll have the option to add Environment Variables and here we'll want to add the two variables from our
env.localfile. Those two variables will be
MongoDB_DB. Be sure to add both of these with their corresponding values before hitting Deploy.
NOTE: Vercel uses dynamic IP addresses so you'll need to add an exception to access from any IP address in your MongoDB Atlas dashboard. To do this simplify navigate to the Network Access tab, hit the Add IP Address button, and then hit the Allow Access From Anywhere button or for the Access List Entry enter 0.0.0/0.
We are live! Let's make sure everything works by navigating to the
In this tutorial we walked through the official Next.js with MongoDB example. I showed you how to connect your MongoDB database to your Next.js application and execute queries multiple ways. Then we deployed our application using Vercel.
Build a Simple Website with React, Axios, and a REST API Built with MongoDB Atlas App Services
May 31, 2022