DEV Community

Dev.Faanid
Dev.Faanid

Posted on

Next.js API endpoint with MongoDB

Next.js supports multiple ways to get data. We can create
API endpoints, get data by running server-side rendered functions for a particular page, or even generate static pages 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);
   }
};

Enter fullscreen mode Exit fullscreen mode

To explain what is going on here, we'll start with the import statement. We are importing our clientPromisemethod 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 reqand return the response via the resobject.
Our handler function implementation calls the clientPromisefunction to get the instance of our MongoDB database. Next, we execute a MongoDB query using the
MongoDB Node.js Driver
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

Add additional API routes by creating additional files in the apidirectory:

To give you some pointers, you'll use Next.js 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.

Top comments (0)