Overview
In this tutorial, you learn how to create a Next.js application that connects to MongoDB. You also learn how to deploy the application on Vercel, a platform that hosts Next.js applications.
Note
This tutorial uses the Next.js Pages Router instead of the App Router that Next.js introduced in version 13.
Prerequisites
Before you begin, complete the following steps:
Complete the MongoDB Get Started guide to set up a new Atlas account and load sample data into a new free tier MongoDB deployment.
Get the connection string for your cluster and save it to use later in this tutorial.
Create a Vercel account by visiting the Vercel website.
Download Node.js version 18 or later.
Ensure you have npm and npx installed.
Tutorial
This tutorial guides you through the following steps:
Create a Next.js application.
Connect MongoDB to Next.js.
Query MongoDB from Next.js.
Deploy your application on Vercel.
Create a Next.js Application
You can create a Next.js application with MongoDB integration by using the with-mongodb example template.
To create a new Next.js application with MongoDB integration, run the following command in your terminal:
npx create-next-app --example with-mongodb sample_mflix
The command uses npx create-next-app and the
--example with-mongodb parameter to create an
application from the MongoDB integration example.
sample_mflix is the name of the application. Use a
different name if you prefer.
After the command completes, navigate to your project directory by running the following command:
cd sample_mflix
Install the npm dependencies by running the following command:
npm install
To start your Next.js application, run the following command:
npm run dev
After the application builds, navigate to
localhost:3000 in your browser. The page displays an
error message because you have not yet provided your MongoDB
connection string.
Connect MongoDB to Next.js
The Next.js application directory contains an
env.local.example file. Rename this file to
env.local and open it. The file contains one property:
MONGODB_URI.
Set your MongoDB connection string as the value for the
MONGODB_URI property. Your env.local file looks
similar to the following example:
MONGODB_URI=<Your connection string>
To verify your configuration, restart your Next.js application by running the following command in your terminal:
npm run dev
When the application builds, navigate to localhost:3000
in your browser. You see the with-mongodb Next.js
application welcome page.
Tip
Your connection is successful if you see the message "You are connected to MongoDB". If you see the message "You are NOT connected to MongoDB", verify your connection string and ensure that your database user and network connection are configured correctly.
Query MongoDB from Next.js
Next.js supports multiple ways to retrieve data. You can create API endpoints, run server-side rendered functions for a page, or generate static pages by getting data at build time. This tutorial shows examples of all three methods.
Example 1: Create a Next.js API Endpoint for MongoDB
To create a new API endpoint route, create an api
directory in your pages directory. Each file you create
in the api directory becomes an individual API endpoint.
Create a new file in the api directory called
movies.tsx. This endpoint returns a list of movies from
your MongoDB database. Add the following code to the
movies.tsx file:
1 import clientPromise from "../../lib/mongodb"; 2 import { NextApiRequest, NextApiResponse } from 'next'; 3 4 export default async (req: NextApiRequest, res: NextApiResponse) => { 5 try { 6 const client = await clientPromise; 7 const db = client.db("sample_mflix"); 8 const movies = await db 9 .collection("movies") 10 .find({}) 11 .sort({ metacritic: -1 }) 12 .limit(10) 13 .toArray(); 14 res.json(movies); 15 } catch (e) { 16 console.error(e); 17 } 18 }
The preceding code creates an API endpoint that returns the
top 10 movies from the sample_mflix database sorted by
their metacritic rating in descending order. The
res.json method serves the array of movies in JSON format
to the browser. When you navigate to
localhost:3000/api/movies, the browser displays a list of movies
returned from your database.
Add more API routes by creating additional files in the
api directory.
Example 2: Next.js Pages with MongoDB
You can get data directly into your Next.js pages by using the
getServerSideProps() method. This method is available
when you use Next.js pages.
The getServerSideProps() method forces a Next.js page to
use server-side rendering to load. Every time the page loads,
the getServerSideProps() method runs on the backend, gets
data, and sends it into the React component through props.
The code inside getServerSideProps() is never sent to the
client.
Create a new file in the pages directory called
movies.tsx. The following code shows how to use
getServerSideProps() to query MongoDB:
1 import clientPromise from "../lib/mongodb"; 2 import { GetServerSideProps } from 'next'; 3 4 interface Movie { 5 _id: string; 6 title: string; 7 metacritic: number; 8 plot: string; 9 } 10 11 interface MoviesProps { 12 movies: Movie[]; 13 } 14 15 const Movies: React.FC<MoviesProps> = ({ movies }) => { 16 return ( 17 <div> 18 <h1>Top 20 Movies of All Time</h1> 19 <p> 20 <small>(According to Metacritic)</small> 21 </p> 22 <ul> 23 {movies.map((movie) => ( 24 <li key={movie._id}> 25 <h2>{movie.title}</h2> 26 <h3>{movie.metacritic}</h3> 27 <p>{movie.plot}</p> 28 </li> 29 ))} 30 </ul> 31 </div> 32 ); 33 }; 34 35 export default Movies; 36 37 export const getServerSideProps: GetServerSideProps = async () => { 38 try { 39 const client = await clientPromise; 40 const db = client.db("sample_mflix"); 41 const movies = await db 42 .collection("movies") 43 .find({}) 44 .sort({ metacritic: -1 }) 45 .limit(20) 46 .toArray(); 47 return { 48 props: { movies: JSON.parse(JSON.stringify(movies)) }, 49 }; 50 } catch (e) { 51 console.error(e); 52 return { props: { movies: [] } }; 53 } 54 };
The Movies page component receives the props from the
getServerSideProps() method and uses that data to render
the page. The page shows the top movie title, metacritic
rating, and plot.
Note
The getServerSideProps() method runs every time the
page is called. If your data does not change often, use
static page generation instead.
Example 3: Next.js Static Generation with MongoDB
You can use static page generation to pre-render pages at build time. This method is useful when your data does not change frequently.
Create a new file in the pages directory called
top.tsx. The following code shows how to use
getStaticProps() to render the top one-thousand highest
rated movies from your MongoDB database:
1 import { ObjectId } from "mongodb"; 2 import clientPromise from "../lib/mongodb"; 3 import { GetStaticProps } from "next"; 4 5 interface Movie { 6 _id: ObjectId; 7 title: string; 8 metacritic: number; 9 plot: string; 10 } 11 12 interface TopProps { 13 movies: Movie[]; 14 } 15 16 export default function Top({ movies }: TopProps) { 17 return ( 18 <div> 19 <h1>Top 1000 Movies of All Time</h1> 20 <p> 21 <small>(According to Metacritic)</small> 22 </p> 23 <ul> 24 {movies.map((movie) => ( 25 <li key={movie._id.toString()}> 26 <h2>{movie.title}</h2> 27 <h3>{movie.metacritic}</h3> 28 <p>{movie.plot}</p> 29 </li> 30 ))} 31 </ul> 32 </div> 33 ); 34 } 35 36 export const getStaticProps: GetStaticProps<TopProps> = async () => { 37 try { 38 const client = await clientPromise; 39 40 const db = client.db("sample_mflix"); 41 42 const movies = await db 43 .collection("movies") 44 .find({}) 45 .sort({ metacritic: -1 }) 46 .limit(1000) 47 .toArray(); 48 49 return { 50 props: { movies: JSON.parse(JSON.stringify(movies)) }, 51 }; 52 } catch (e) { 53 console.error(e); 54 return { 55 props: { movies: [] }, 56 }; 57 } 58 };
When you navigate to localhost:3000/top, the browser displays
a list of movies.
In development mode, your application calls the getStaticProps() method
every time similar to the getServerSideProps() method. In
production mode, the /top page pre-renders and loads
almost immediately.
To run your Next.js application in production mode, build it
first. Then, run the start command to serve the built
application. Run the following commands in your terminal:
npm run build npm run start
When you run the npm run start command, Next.js
serves your application in production mode. The
getStaticProps() method does not run every time you
access the /top route because Next.js serves the page statically.
To see the pre-rendered static page, view the
.next/server/pages/top.html file.
Deploy your application on Vercel
Deploy your Next.js application with MongoDB on Vercel. Before you deploy, you must commit the application code from the preceding steps to a GitHub repository. To learn how to create a Github account and commit to a repository, see the GitHub documentation.
After you commit your code to a repository, navigate to Vercel and log in. On your Vercel dashboard, click the Import Project button, and then click Import Git Repository.
Enter your GitHub repository URL and click Continue. On
the next screen, add the variables from your env.local
file.
Click the Deploy button. Vercel automatically builds and deploys your Next.js application. When it completes, you will receive a URL where you can access your application.
Note
Vercel uses dynamic IP addresses, so you must add an exception to
access your data from any IP address in your MongoDB Atlas
dashboard. To do this, navigate to the Network Access tab,
click the Add IP Address button, and then click the
Allow Access From Anywhere button.
Additional Resources
For more information about the concepts in this tutorial, see the following resources: