Are you building your next amazing application with Next.js? 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 Next.js<>MongoDB 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 with-mongodb example 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 Vercel, the official hosting platform for Next.js applications. If you already have an existing Next.js app, not to worry, simply drop in the MongoDB utility file 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!
Prerequisites
For this tutorial, you'll need:
NodeJS 12+.
npm and npx.
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.
What is Next.js?
If you're not already familiar, Next.js is a React-based framework for building modern web applications. The framework adds a lot of powerful features — such as server side rendering, automatic code splitting, and incremental static regeneration — that make it easy to build scalable and production-ready apps.
Getting started with-mongodb
Next.js has an extensive examples library that shows how you can integrate the framework with various features like GraphQL servers, authentication libraries, or CSS frameworks. The example we'll use for this post is called with-mongodb and as you might expect, it'll come with everything needed to connect to a MongoDB database.
To create a new Next.js app with MongoDB integration built in, execute the following command in your terminal: