Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

MongoDB Developer
JavaScript
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
JavaScriptchevron-right

Building Modern Applications with Next.js and MongoDB

Ado Kukic20 min read • Published Jan 27, 2022 • Updated Apr 11, 2023
Next.jsJavaScript
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
This article is out of date. Check out the official Next.js with MongoDB tutorial for the latest guide on integrating MongoDB with Next.js.
Developers have more choices than ever before when it comes to choosing the technology stack for their next application. Developer productivity is one of the most important factors in choosing a modern stack and I believe that Next.js coupled with MongoDB can get you up and running on the next great application in no time at all. Let's find out how and why!
If you would like to follow along with this tutorial, you can get the code from the GitHub repo. Also, be sure to sign up for a free MongoDB Atlas account to make it easier to connect your MongoDB database.

What is Next.js

Next.js is a React based framework for building modern web applications. The framework comes with a lot of powerful features such as server side rendering, automatic code splitting, static exporting and much more that make it easy to build scalable and production ready apps. Its opinionated nature means that the framework is focused on developer productivity, but still flexible enough to give developers plenty of choice when it comes to handling the big architectural decisions.
NextJS Homepage
For this tutorial, I'll assume that you are already familiar with React, and if so, you'll be up and running with Next.js in no time at all. If you are not familiar with React, I would suggest looking at resources such as the official React docs or taking a free React starter course to get familiar with the framework first.

What We're Building: Macro Compliance Tracker

The app we're building today is called the Macro Compliance Tracker. If you're like me, you probably had a New Years Resolution of "I'm going to get in better shape!" This year, I am taking that resolution seriously, and have gotten a person trainer and nutritionist. One interesting thing that I learned is that while the old adage of calories in needs to be less than calories out to lose weight is generally true, your macronutrients also play just as an important role in weight loss.
There are many great apps that help you track your calories and macros. Unfortunately, most apps do not allow you to track a range and another interesting thing that I learned in my fitness journey this year is that for many beginners trying to hit their daily macro goals is a challenge and many folks end up giving up when they fail to hit the exact targets consistently. For that reason, my coach suggests a target range for calories and macros rather than a hard set number.
MCT App
So that's what we're building today. We'll use Next.js to build our entire application and MongoDB as our database to store our progress. Let's get into it!

Setting up a Next.js Application

The easiest way to create a Next.js application is by using the official create-next-app npx command. To do that we'll simply open up our Terminal window and type: npx create-next-app mct. "mct" is going to be the name of our application as well as the directory where our code is going to live.
create-next-app
Execute this command and a default application will be created. Once the files are created navigate into the directory by running cd mct in the Terminal window and then execute npm run dev. This will start a development server for your Next.js application which you'll be able to access at localhost:3000.
Next.js Default
Navigate to localhost:3000 and you should see a page very similar to the one in the above screenshot. If you see the Welcome to Next.js page you are good to go. If not, I would suggest following the Next.js docs and troubleshooting tips to ensure proper setup.

Next.js Directory Structure

Before we dive into building our application any further, let's quickly look at how Next.js structures our application. The default directory structure looks like this:
Next.js Default Directory Structure
The areas we're going to be focused on are the pages, components, and public directories. The .next directory contains the build artifacts for our application, and we should generally avoid making direct changes to it.
The pages directory will contain our application pages, or another way to think of these is that each file here will represent a single route in our application. Our default app only has the index.js page created which corresponds with our home route. If we wanted to add a second page, for example, an about page, we can easily do that by just creating a new file called about.js. The name we give to the filename will correspond to the route. So let's go ahead and create an about.js file in the pages directory.
As I mentioned earlier, Next.js is a React based framework, so all your React knowledge is fully transferable here. You can create components using either as functions or as classes. I will be using the function based approach. Feel free to grab the complete GitHub repo if you would like to follow along. Our About.js component will look like this:
1import React from 'react'
2import Head from 'next/head'
3import Nav from '../components/nav'
4
5const About = () => (
6 <div>
7 <Head>
8 <title>About</title>
9 <link rel="icon" href="/favicon.ico" />
10 </Head>
11
12 <Nav />
13
14 <div>
15 <h1>Macro Compliance Tracker!</h1>
16 <p>
17 This app will help you ensure your macros are within a selected range to help you achieve your New Years Resolution!
18 </p>
19 </div>
20 </div>
21)
22
23export default About
Go ahead and save this file. Next.js will automatically rebuild the application and you should be able to navigate to http://localhost:3000/about now and see your new component in action.
About Us Page Unstyled
Next.js will automatically handle all the routing plumbing and ensure the right component gets loaded. Just remember, whatever you name your file in the pages directory is what the corresponding URL will be.

Adding Some Style with Tailwind.css

Our app is looking good, but from a design perspective, it's looking pretty bare. Let's add Tailwind.css to spruce up our design and make it a little easier on the eyes. Tailwind is a very powerful CSS framework, but for brevity we'll just import the base styles from a CDN and won't do any customizations. To do this, we'll simply add <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"/> in the Head components of our pages.
Let's do this for our About component and also add some Tailwind classes to improve our design. Our next component should look like this:
1import React from 'react'
2import Head from 'next/head'
3import Nav from '../components/nav'
4
5const About = () => (
6 <div>
7 <Head>
8 <title>About</title>
9 <link rel="icon" href="/favicon.ico" />
10 <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
11 </Head>
12
13 <Nav />
14
15 <div className="container mx-auto text-center">
16 <h1 className="text-6xl m-12">Macro Compliance Tracker!</h1>
17 <p className="text-xl">
18 This app will help you ensure your macros are within a selected range to help you achieve your New Years Resolution!
19 </p>
20 </div>
21 </div>
22)
23
24export default About
If we go and refresh our browser, the About page should look like this:
About Us Page Styled
Good enough for now. If you want to learn more about Tailwind, check out their official docs here.
Note: If when you make changes to your Next.js application such as adding the className's or other changes, and they are not reflected when you refresh the page, restart the dev server.

Creating Our Application

Now that we have our Next.js application setup, we've gone through and familiarized ourselves with how creating components and pages works, let's get into building our Macro Compliance Tracker app. For our first implementation of this app, we'll put all of our logic in the main index.js page. Open the page up and delete all the existing Next.js boilerplate.
Before we write the code, let's figure out what features we'll need. We'll want to show the user their daily calorie and macro goals, as well as if they're in compliance with their targeted range or not. Additionally, we'll want to allow the user to update their information every day. Finally, we'll want the user to be able to view previous days and see how they compare.
Let's create the UI for this first. We'll do it all in the Home component, and then start breaking it up into smaller individual components. Our code will look like this:
1import React from 'react'
2import Head from 'next/head'
3import Nav from '../components/nav'
4
5const Home = () => (
6 <div>
7 <Head>
8 <title>Home</title>
9 <link rel="icon" href="/favicon.ico" />
10 <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
11 </Head>
12
13 <div className="container mx-auto">
14
15 <div className="flex text-center">
16 <div className="w-full m-4">
17 <h1 className="text-4xl">Macro Compliance Tracker</h1>
18 </div>
19 </div>
20
21 <div class="flex text-center">
22 <div class="w-1/3 bg-gray-200 p-4">Previous Day</div>
23 <div class="w-1/3 p-4">1/23/2020</div>
24 <div class="w-1/3 bg-gray-200 p-4">Next Day</div>
25 </div>
26
27 <div class="flex mb-4 text-center">
28 <div class="w-1/4 p-4 bg-green-500 text-white">
29 <h2 className="text-3xl font-bold">1850
30 <div class="flex text-sm p-4">
31 <div class="w-1/3">1700</div>
32 <div class="w-1/3 font-bold">1850</div>
33 <div class="w-1/3">2000</div>
34 </div>
35 </h2>
36 <h3 className="text-xl">Calories</h3>
37 </div>
38 <div class="w-1/4 p-4 bg-red-500 text-white">
39 <h2 className="text-3xl font-bold">195
40 <div class="flex text-sm p-4">
41 <div class="w-1/3">150</div>
42 <div class="w-1/3 font-bold">160</div>
43 <div class="w-1/3">170</div>
44 </div>
45 </h2>
46 <h3 className="text-xl">Carbs</h3>
47 </div>
48 <div class="w-1/4 p-4 bg-green-500 text-white">
49 <h2 className="text-3xl font-bold">55
50 <div class="flex text-sm p-4">
51 <div class="w-1/3">50</div>
52 <div class="w-1/3 font-bold">60</div>
53 <div class="w-1/3">70</div>
54 </div>
55 </h2>
56 <h3 className="text-xl">Fat</h3>
57 </div>
58 <div class="w-1/4 p-4 bg-blue-500 text-white">
59 <h2 className="text-3xl font-bold">120
60 <div class="flex text-sm p-4">
61 <div class="w-1/3">145</div>
62 <div class="w-1/3 font-bold">160</div>
63 <div class="w-1/3">175</div>
64 </div>
65 </h2>
66 <h3 className="text-xl">Protein</h3>
67 </div>
68 </div>
69
70 <div className="flex">
71 <div className="w-1/3">
72 <h2 className="text-3xl p-4">Results</h2>
73 <div className="p-4">
74 <label className="block">Calories</label>
75 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
76 </div>
77 <div className="p-4">
78 <label className="block">Carbs</label>
79 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
80 </div>
81 <div className="p-4">
82 <label className="block">Fat</label>
83 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
84 </div>
85 <div className="p-4">
86 <label className="block">Protein</label>
87 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
88 </div>
89 <div className="p-4">
90 <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
91 Save
92 </button>
93 </div>
94 </div>
95 <div className="w-1/3">
96 <h2 className="text-3xl p-4">Target</h2>
97 <div className="p-4">
98 <label className="block">Calories</label>
99 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
100 </div>
101 <div className="p-4">
102 <label className="block">Carbs</label>
103 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
104 </div>
105 <div className="p-4">
106 <label className="block">Fat</label>
107 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
108 </div>
109 <div className="p-4">
110 <label className="block">Protein</label>
111 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
112 </div>
113 <div className="p-4">
114 <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
115 Save
116 </button>
117 </div>
118 </div>
119 <div className="w-1/3">
120 <h2 className="text-3xl p-4">Variance</h2>
121 <div className="p-4">
122 <label className="block">Calories</label>
123 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
124 </div>
125 <div className="p-4">
126 <label className="block">Carbs</label>
127 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
128 </div>
129 <div className="p-4">
130 <label className="block">Fat</label>
131 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
132 </div>
133 <div className="p-4">
134 <label className="block">Protein</label>
135 <input type="number" className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white"></ input>
136 </div>
137 <div className="p-4">
138 <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
139 Save
140 </button>
141 </div>
142 </div>
143 </div>
144 </div>
145 </div>
146)
147
148export default Home
And this will result in our UI looking like this:
MCT App
There is a bit to unwind here. So let's take a look at it piece by piece. At the very top we have a simple header that just displays the name of our application. Next, we have our day information and selection options. After that, we have our daily results showing whether we are in compliance or not for the selected day. If we are within the suggested range, the background is green. If we are over the range, meaning we've had too much of a particular macro, the background is red, and if we under-consumed a particular macro, the background is blue. Finally, we have our form which allows us to update our daily results, our target calories and macros, as well as variance for our range.
Our code right now is all in one giant component and fairly static. Next let's break up our giant component into smaller parts and add our front end functionality so we're at least working with non-static data. We'll create our components in the components directory and then import them into our index.js page component. Components we create in the components directory can be used across multiple pages with ease allowing us reusability if we add multiple pages to our application.
The first component that we'll create is the result component. The result component is the green, red, or blue block that displays our result as well as our target and variance ranges. Our component will look like this:
1import React, {useState, useEffect} from 'react'
2const Result = ({results}) => {
3 let [bg, setBg] = useState("");
4
5 useEffect(() => {
6 setBackground()
7 });
8
9 const setBackground = () => {
10 let min = results.target - results.variant;
11 let max = results.target + results.variant;
12
13 if(results.total >= min && results.total <= max) {
14 setBg("bg-green-500");
15 } else if ( results.total < min){
16 setBg("bg-blue-500");
17 } else {
18 setBg("bg-red-500")
19 }
20 }
21
22 return (
23 <div className={bg + " w-1/4 p-4 text-white"}>
24 <h2 className="text-3xl font-bold">{results.total}
25 <div className="flex text-sm p-4">
26 <div className="w-1/3">{results.target - results.variant}</div>
27 <div className="w-1/3 font-bold">{results.target}</div>
28 <div className="w-1/3">{results.target + results.variant}</div>
29 </div>
30 </h2>
31 <h3 className="text-xl">{results.label}</h3>
32 </div>
33 )
34 }
35
36export default Result
This will allow us to feed this component dynamic data and based on the data provided, we'll display the correct background, as well as target ranges for our macros. We can now simplify our index.js page component by removing all the boilerplate code and replacing it with:
1<div className="flex mb-4 text-center">
2 <Result results={results.calories} />
3 <Result results={results.carbs} />
4 <Result results={results.fat} />
5 <Result results={results.protein} />
6</div>
Let's also go ahead and create some dummy data for now. We'll get to retrieving live data from MongoDB soon, but for now let's just create some data in-memory like so:
1const Home = () => {
2 let data = {
3 calories: {
4 label: "Calories",
5 total: 1840,
6 target: 1840,
7 variant: 15
8 },
9 carbs: {
10 label: "Carbs",
11 total: 190,
12 target: 160,
13 variant: 15
14 },
15 fat: {
16 label: "Fat",
17 total: 55,
18 target: 60,
19 variant: 10
20 },
21 protein: {
22 label: "Protein",
23 total: 120,
24 target: 165,
25 variant: 10
26 }
27 }
28
29const [results, setResults] = useState(data);
30
31return ( ... )}
If we look at our app now, it won't look very different at all. And that's ok. All we've done so far is change how our UI is rendered, moving it from hard coded static values, to an in-memory object. Next let's go ahead and make our form work with this in-memory data. Since our forms are very similar, we can create a component here as well and re-use the same component.
We will create a new component called MCTForm and in this component we'll pass in our data, a name for the form, and an onChange handler that will update the data dynamically as we change the values in the input boxes. Also, for simplicity, we'll remove the Save button and move it outside of the form. This will allow the user to make changes to their data in the UI, and when the user wants to lock in the changes and save them to the database, then they'll hit the Save button. So our Home component will now look like this:
1const Home = () => {
2 let data = {
3 calories: {
4 label: "Calories",
5 total: 1840,
6 target: 1850,
7 variant: 150
8 },
9 carbs: {
10 label: "Carbs",
11 total: 190,
12 target: 160,
13 variant: 15
14 },
15 fat: {
16 label: "Fat",
17 total: 55,
18 target: 60,
19 variant: 10
20 },
21 protein: {
22 label: "Protein",
23 total: 120,
24 target: 165,
25 variant: 10
26 }
27 }
28
29 const [results, setResults] = useState(data);
30
31 const onChange = (e) => {
32 const data = { ...results };
33
34 let name = e.target.name;
35
36 let resultType = name.split(" ")[0].toLowerCase();
37 let resultMacro = name.split(" ")[1].toLowerCase();
38
39 data[resultMacro][resultType] = e.target.value;
40
41 setResults(data);
42 }
43
44 return (
45 <div>
46 <Head>
47 <title>Home</title>
48 <link rel="icon" href="/favicon.ico" />
49 <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" />
50 </Head>
51
52 <div className="container mx-auto">
53
54 <div className="flex text-center">
55 <div className="w-full m-4">
56 <h1 className="text-4xl">Macro Compliance Tracker</h1>
57 </div>
58 </div>
59
60 <div className="flex text-center">
61 <div className="w-1/3 bg-gray-200 p-4">Previous Day</div>
62 <div className="w-1/3 p-4">1/23/2020</div>
63 <div className="w-1/3 bg-gray-200 p-4">Next Day</div>
64 </div>
65
66 <div className="flex mb-4 text-center">
67 <Result results={results.calories} />
68 <Result results={results.carbs} />
69 <Result results={results.fat} />
70 <Result results={results.protein} />
71 </div>
72
73 <div className="flex">
74 <MCTForm data={results} item="Total" onChange={onChange} />
75 <MCTForm data={results} item="Target" onChange={onChange} />
76 <MCTForm data={results} item="Variant" onChange={onChange} />
77 </div>
78
79 <div className="flex text-center">
80 <div className="w-full m-4">
81 <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
82 Save
83 </button>
84 </div>
85 </div>
86 </div>
87 </div>
88)}
89
90export default Home
Aside from cleaning up the UI code, we also added an onChange function that will be called every time the value of one of the input boxes changes. The onChange function will determine which box was changed and update the data value accordingly as well as re-render the UI to show the new changes.
Next, let's take a look at our implementation of the MCTForm component.
1import React from 'react'
2
3const MCTForm = ({data, item, onChange}) => {
4 return(
5 <div className="w-1/3">
6 <h2 className="text-3xl p-4">{item}</h2>
7 <div className="p-4">
8 <label className="block">Calories</label>
9 <input type="number" name={item + " Calories"} className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white" onChange={(e) => onChange(e)}></input>
10 </div>
11 <div className="p-4">
12 <label className="block">Carbs</label>
13 <input type="number" name={item + " Carbs"} className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white" onChange={(e) => onChange(e)}></input>
14 </div>
15 <div className="p-4">
16 <label className="block">Fat</label>
17 <input type="number" name={item + " Fat"} className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white" onChange={(e) => onChange(e)}></input>
18 </div>
19 <div className="p-4">
20 <label className="block">Protein</label>
21 <input type="number" name={item + " Protein"} className="bg-gray-200 text-gray-700 border rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white" onChange={(e) => onChange(e)}></input>
22 </div>
23 </div>
24 )
25}
26
27export default MCTForm
As you can see this component is in charge of rendering our forms. Since the input boxes are the same for all three types of forms, we can reuse the component multiple times and just change the type of data we are working with.
Again if we look at our application in the browser now, it doesn't look much different. But now the form works. We can replace the values and the application will be dynamically updated showing our new total calories and macros and whether or not we are in compliance with our goals. Go ahead and play around with it for a little bit to make sure it all works.

Connecting Our Application to MongoDB

Our application is looking good. It also works. But, the data is all in memory. As soon as we refresh our page, all the data is reset to the default values. In this sense, our app is not very useful. So our next step will be to connect our application to a database so that we can start seeing our progress over time. We'll use MongoDB and MongoDB Atlas to accomplish this.

Setting Up Our MongoDB Database

Before we can save our data, we'll need a database. For this I'll use MongoDB and MongoDB Atlas to host my database. If you don't already have MongoDB Atlas, you can sign up and use it for free here, otherwise go into an existing cluster and create a new database. Inside MongoDB Atlas, I will use an existing cluster and set up a new database called MCT. With this new database created, I will create a new collection called daily that will store my daily results, target macros, as well as allowed variants.
MongoDB Atlas
With my database set up, I will also add a few days worth of data. Feel free to add your own data or if you'd like the dataset I'm using, you can get it here. I will use MongoDB Compass to import and view the data, but you can import the data however you want: use the CLI, add in manually, or use Compass.
Thanks to MongoDB's document model, I can represent the data exactly as I had it in-memory. The only additional fields I will have in my MongoDB model is an _id field that will be a unique identifier for the document and a date field that will represent the data for a specific date. The image below shows the data model for one document in MongoDB Compass.
MongoDB Compass
Now that we have some real data to work with, let's go ahead and connect our Next.js application to our MongoDB Database. Since Next.js is a React based framework that's running Node server-side we will use the excellent Mongo Node Driver to facilitate this connection.

Connecting Next.js to MongoDB Atlas

Our pages and components directory renders both server-side on the initial load as well as client-side on subsequent page changes. The MongoDB Node Driver works only on the server side and assumes we're working on the backend. Not to mention that our credentials to MongoDB need to be secure and not shared to the client ever.
Not to worry though, this is where Next.js shines. In the pages directory, we can create an additional special directory called api. In this API directory, as the name implies, we can create api endpoints that are executed exclusively on the backend. The best way to see how this works is to go and create one, so let's do that next. In the pages directory, create an api directory, and there create a new file called daily.js.
In the daily.js file, add the following code:
1export default (req, res) => {
2 res.statusCode = 200
3 res.setHeader('Content-Type', 'application/json')
4 res.end(JSON.stringify({ message: 'Hello from the Daily route' }))
5}
Save the file, go to your browser and navigate to localhost:3000/api/daily. What you'll see is the JSON response of {message:'Hello from the Daily route'}. This code is only ever run server side and the only thing the browser receives is the response we send. This seems like the perfect place to set up our connection to MongoDB.
API Endpoint Response
While we can set the connection in this daily.js file, in a real world application, we are likely to have multiple API endpoints and for that reason, it's probably a better idea to establish our connection to the database in a middleware function that we can pass to all of our api routes. So as a best practice, let's do that here.
Create a new middleware directory at the root of the project structure alongside pages and components and call it middleware. The middleware name is not reserved so you could technically call it whatever you want, but I'll stick to middleware for the name. In this new directory create a file called database.js. This is where we will set up our connection to MongoDB as well as instantiate the middleware so we can use it in our API routes.
Our database.js middleware code will look like this:
1import { MongoClient } from 'mongodb';
2import nextConnect from 'next-connect';
3
4const client = new MongoClient('{YOUR-MONGODB-CONNECTION-STRING}', {
5 useNewUrlParser: true,
6 useUnifiedTopology: true,
7});
8
9async function database(req, res, next) {
10 req.dbClient = client;
11 req.db = client.db('MCT');
12 return next();
13}
14
15const middleware = nextConnect();
16
17middleware.use(database);
18
19export default middleware;
If you are following along, be sure to replace the {YOUR-MONGODB-CONNECTION-STRING} variable with your connection string, as well as ensure that the client.db matches the name you gave your database. Also be sure to run npm install --save mongodb next-connect to ensure you have all the correct dependencies. Database names are case sensitive by the way. Save this file and now open up the daily.js file located in the pages/api directory.
We will have to update this file. Since now we want to add a piece of middleware to our function, we will no longer be using an anonymous function here. We'll utility next-connect to give us a handler chain as well as allow us to chain middleware to the function. Let's take a look at what this will look like.
1import nextConnect from 'next-connect';
2import middleware from '../../middleware/database';
3
4const handler = nextConnect();
5
6handler.use(middleware);
7
8handler.get(async (req, res) => {
9
10 let doc = await req.db.collection('daily').findOne()
11 console.log(doc);
12 res.json(doc);
13});
14
15export default handler;
As you can see we now have a handler object that gives us much more flexibility. We can use different HTTP verbs, add our middleware, and more. What the code above does, is that it connects to our MongoDB Atlas cluster and from the MCT database and daily collection, finds and returns one item and then renders it to the screen. If we hit localhost:3000/api/daily now in our browser we'll see this:
Daily API Response
Woohoo! We have our data and the data model matches our in-memory data model, so our next step will be to use this real data instead of our in-memory sample. To do that, we'll open up the index.js page.
Our main component is currently instantiated with an in-memory data model that the rest of our app acts upon. Let's change this. Next.js gives us a couple of different ways to do this. We can always get the data async from our React component, and if you've used React in the past this should be second nature, but since we're using Next.js I think there is a different and perhaps better way to do it.
Each Next.js page component allows us to fetch data server-side thanks to a function called getStaticProps. When this function is called, the initial page load is rendered server-side, which is great for SEO. The page doesn't render until this function completes. In index.js, we'll make the following changes:
1import fetch from 'isomorphic-unfetch'
2const Home = ({data}) => { ... }
3
4export async function getStaticProps(context) {
5 const res = await fetch("http://localhost:3000/api/daily");
6 const json = await res.json();
7 return {
8 props: {
9 data: json,
10 },
11 };
12}
13
14export default Home
Install the isomorphic-unfetch library by running npm install --save isomorphic-unfetch, then below your Home component add the getStaticProps method. In this method we're just making a fetch call to our daily API endpoint and storing that json data in a prop called data. Since we created a data prop, we then pass it into our Home component, and at this point, we can go and remove our in-memory data variable. Do that, save the file, and refresh your browser.
Congrats! Your data is now coming live from MongoDB. But at the moment, it's only giving us one result. Let's make a few final tweaks so that we can see daily results, as well as update the data and save it in the database.

View Macro Compliance Tracker Data By Day

The first thing we'll do is add the ability to hit the Previous Day and Next Day buttons and display the corresponding data. We won't be creating a new endpoint since I think our daily API endpoint can do the job, we'll just have to make a few enhancements. Let's do those first.
Our new daily.js API file will look as such:
1handler.get(async (req, res) => {
2 const { date } = req.query;
3
4 const dataModel = { "_id": new ObjectID(), "date": date, "calories": { "label": "Calories", "total": 0, "target": 0, "variant": 0 }, "carbs": { "label": "Carbs", "total": 0, "target": 0, "variant": 0 }, "fat": { "label" : "Fat", "total": 0, "target": 0, "variant": 0 }, "protein": { "label" : "Protein", "total": 0, "target": 0, "variant": 0 }}
5
6 let doc = {}
7
8 if(date){
9 doc = await req.db.collection('daily').findOne({date: new Date(date)})
10 } else {
11 doc = await req.db.collection('daily').findOne()
12 }
13 if(doc == null){
14 doc = dataModel
15 }
16 res.json(doc)
17});
We made a couple of changes here so let's go through them one by one. The first thing we did was we are looking for a date query parameter to see if one was passed to us. If a date parameter was not passed, then we'll just pick a random item using the findOne method. But, if we did receive a date, then we'll query our MongoDB database against that date and return the data for that specified date.
Next, as our data set is not exhaustive, if we go too far forwards or backwards, we'll eventually run out of data to display, so we'll create an empty in-memory object that serves as our data model. If we don't have data for a specified date in our database, we'll just set everything to 0 and serve that. This way we don't have to do a whole lot of error handling on the front and can always count on our backend to serve some type of data.
Now, open up the index.js page and let's add the functionality to see the previous and next days. We'll make use of dayjs to handle our dates, so install it by running npm install --save dayjs first. Then make the following changes to your index.js page:
1// Other Imports ...
2import dayjs from 'dayjs'
3
4const Home = ({data}) => {
5 const [results, setResults] = useState(data);
6
7 const onChange = (e) => {
8 }
9
10 const getDataForPreviousDay = async () => {
11 let currentDate = dayjs(results.date);
12 let newDate = currentDate.subtract(1, 'day').format('YYYY-MM-DDTHH:mm:ss')
13 const res = await fetch('http://localhost:3000/api/daily?date=' + newDate)
14 const json = await res.json()
15
16 setResults(json);
17 }
18
19 const getDataForNextDay = async () => {
20 let currentDate = dayjs(results.date);
21 let newDate = currentDate.add(1, 'day').format('YYYY-MM-DDTHH:mm:ss')
22 const res = await fetch('http://localhost:3000/api/daily?date=' + newDate)
23 const json = await res.json()
24
25 setResults(json);
26 }
27
28return (
29 <div className="flex text-center">
30 <div className="w-1/3 bg-gray-200 p-4"><button onClick={getDataForPreviousDay}>Previous Day</button></div>
31 <div className="w-1/3 p-4">{dayjs(results.date).format('MM/DD/YYYY')}</div>
32 <div className="w-1/3 bg-gray-200 p-4"><button onClick={getDataForNextDay}>Next Day</button></div>
33 </div>
34
35)}
We added two new methods, one to get the data from the previous day and one to get the data from the following day. In our UI we also made the date label dynamic so that it displays and tells us what day we are currently looking at. With these changes go ahead and refresh your browser and you should be able to see the new data for days you have entered in your database. If a particular date does not exist, it will show 0's for everything.
MCT No Data

Saving and Updating Data In MongoDB

Finally, let's close out this tutorial by adding the final piece of functionality to our app, which will be to make updates and save new data into our MongoDB database. Again, I don't think we need a new endpoint for this, so we'll use our existing daily.js API. Since we're using the handler convention and currently just handle the GET verb, let's add onto it by adding logic to handle a POST to the endpoint.
1handler.post(async (req, res) => {
2 let data = req.body;
3 data = JSON.parse(data);
4 data.date = new Date(data.date);
5 let doc = await req.db.collection('daily').updateOne({date: new Date(data.date)}, {$set:data}, {upsert: true})
6
7 res.json({message: 'ok'});
8})
The code is pretty straightforward. We'll get our data in the body of the request, parse it, and then save it to our MongoDB daily collection using the updateOne() method. Let's take a closer look at the values we're passing into the updateOne() method.
The first value we pass will be what we match against, so in our collection if we find that the specific date already has data, we'll update it. The second value will be the data we are setting and in our case, we're just going to set whatever the front-end client sends us. Finally, we are setting the upsert value to true. What this will do is, if we cannot match on an existing date, meaning we don't have data for that date already, we'll go ahead and create a new record.
With our backend implementation complete, let's add the functionality on our front end so that when the user hits the Save button, the data gets properly updated. Open up the index.js file and make the following changes:
1const Home = ({data}) => {
2 const updateMacros = async () => {
3 const res = await fetch('http://localhost:3000/api/daily', {
4 method: 'post',
5 body: JSON.stringify(results)
6 })
7 }
8
9 return (
10 <div className="flex text-center">
11 <div className="w-full m-4">
12 <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={updateMacros}>
13 Save
14 </button>
15 </div>
16 </div>
17)}
Our new updateMacros method will make a POST request to our daily API endpoint with the new data. Try it now! You should be able to update existing macros or create data for new days that you don't already have any data for. We did it!

Putting It All Together

We went through a lot in today's tutorial. Next.js is a powerful framework for building modern web applications and having a flexible database powered by MongoDB made it possible to build a fully fledged application in no time at all. There were a couple of items we omitted for brevity such as error handling and deployment, but feel free to clone the application from GitHub, sign up for MongoDB Atlas for free, and build on top of this foundation.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Quickstart

Aggregation Framework with Node.js 3.3.2 Tutorial


Oct 01, 2024 | 9 min read
Tutorial

Getting Started with MongoDB Atlas, NodeJS, and Azure App Service


Apr 02, 2024 | 5 min read
Quickstart

Getting Started With MongoDB & Mongoose


Aug 05, 2024 | 9 min read
Tutorial

How to Integrate MongoDB Into Your Next.js App


Apr 02, 2024 | 11 min read
Table of Contents