Working on API using MongoDB with NextJS

Author
April 06, 2022

In this tutorial i will teach how you can build API using MongoDB with Next.js step by step

Step 1 Create required folder for the api

Create a folder name /pages/api and inside the api folder create file index.js or any other name of your choice page name will be your api routes

For example: If you have created a file with the name index.js then your api routes will be http://localhost:3000/api

If you have create a file with the name feedback.js then your api routes will be http://localhost:3000/api/feedback

Step 2 Writing API function in the API routes file

Inside the index.js or feedback.js file which we have created above in first step we need to write handler function in order to handle api request

We need to write following function code inside our api files

function handler(req, res) {
  //You can write your api logics here
  res.status(200).json({ message: "This api works" });
}

export default handler;

Step 3 Creating API Routes with params

You need to create folder structure like pages/api/feedback/[feedbackid].js and here feedbackid will be your dynamic parameter which you will get in your handler function

You will hit the api like

http://localhost:3000/api/feedback/1234

Here 1234 is dynamic feedback id which you can recieve in req inside your handler function using req.query.feedbackid

function handler(req, res) {
  console.log(req.query.feedbackid);
  //You can write your api logics here
  res.status(200).json({ message: "This api works" });
}

export default handler;

Step 4 Integrating MongoDB

  • In order to add mongodb in to your NextJS we need to install mongodb package in your NextJS application
npm i mongodb --save
  • Connect to mongodb and insert data to your collection

In order to connect to mongodb inside your api routes file you need to add following piece of code

import { MongoClient } from "mongodb";
const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
const dbName = "myProject";

async function mongoconnection() {
  await client.connect();
  return "done";
}

function handler(req, res) {
  mongoconnection()
    .then(async () => {
      const db = client.db(dbName);
      const collection = db.collection("documents");
      await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
      res.status(200).json({ message: "This api works" });
    })
    .catch((error) => {
      console.log("Error", error);
    })
    .finally(() => client.close());
}

export default handler;