Next.js API endpoint with MongoDB
Tags: nextjs, mongodb, api
Published: 2023-07-16 15:37:41

Next.js supports multiple ways to get data. We can create 
**[API endpoints](https://nextjs.org/docs/api-routes/introduction)**, get data by running **[server-side rendered functions](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering)** for a particular page, or even **[generate static pages](https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation)** by getting our data at build-time. 

## Example 1
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 **api **directory in our **pages **directory, and then every file we create in this **api **directory will be treated as an individual API endpoint.

Let's go ahead and create the **api **directory and a new file in this **directory **called **movies.js** . This endpoint will return a list of 20 movies from our MongoDB database. The implementation for this route is as follows:

```
import clientPromise from "../../lib/mongodb";

export default async (req, res) => {
   try {
       const client = await clientPromise;
       const db = client.db("sample_mflix");

       const movies = await db
           .collection("movies")
           .find({})
           .sort({ metacritic: -1 })
           .limit(10)
           .toArray();

       res.json(movies);
   } catch (e) {
       console.error(e);
   }
};

```
To explain what is going on here, we'll start with the import statement. We are importing our `clientPromise `method from the `lib/mongodb` file. 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 
Express.js
, this should look very familiar. This is the function that gets executed when the `localhost:3000/api/movies` route is called. We capture the request via `req `and return the response via the `res `object.
Our handler function implementation calls the `clientPromise `function to get the instance of our MongoDB database. Next, we execute a MongoDB query using the 
**[MongoDB Node.js Driver](https://docs.mongodb.com/drivers/node/?_ga=2.62434732.1249872732.1689513829-1061523893.1689513828)**
 to get the top 20 movies out of our movies collection based on their **metacritic **rating sorted in descending order.
Finally, we call the `res.json` method 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:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j47v3ccd1gtrrf2ei3v3.jpg)



## Add additional API routes by creating additional files in the `api `directory:

To give you some pointers, you'll use **[Next.js Dynamic API Routes](https://nextjs.org/docs/api-routes/dynamic-api-routes)**
 to capture the `id`. So, if a user calls `http://localhost:3000/api/movies/573a1394f29313caabcdfa3e`, the movie that should be returned is **Seven Samurai**. Another tip, the `_id` property for the `sample_my-app` database in MongoDB is stored as an ObjectID, so you'll have to convert the string to an ObjectID.