How To Use MongoDB In a Next.js Application
4 min read

How To Use MongoDB In a Next.js Application

How To Use MongoDB In a Next.js Application
Photo by Boitumelo Phetla / Unsplash

This is a step by step guide to help you to show how easily you can use MongoDB with your Next.js Application

Heads Up

This article is created for the advanced developers and thinking typescript in mind. If you don't use typescript just removing types you can use the same code in js. Or just use this to convert it to JS.

Set up your free mongoDB Atlas account.

MongoDB Atlas Database | Multi-Cloud Database Service
The multi-cloud database service at the heart of our application data platform that accelerates and simplifies how you build with data. Try MongoDB Atlas today!

You can signup for MongoDB by visiting the above link and pressing the signup button.

Setting up the database.

Assuming that you've created an account successfully let's go ahead with the next step. Click on the Databases located on the left menu. Then click on create.

Depending on your budget that you can create a paid or free shared database. Important thing is to choose the closest region to your users.

Once your database is ready click on the connect button. From the popup please choose "Connect your application".

Select your driver and version to Node.js and 4.0 or later. One this is setup copy the connection string.

To the Next.js

Open up your Next.js project and create a file called .env if you don't already have one. This file should be in the root of your project.

Create a variable called MONGODB_URI and paste the connection string. Something Like this:

MONGODB_URI=mongodb+srv://<username>:<password>@cluster120.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Before we move on with the codebase we need to create a new user in mongo db and replace<username> and <password> with it.

Go back to MongoDB account and click on the Database Access and create your first user. Make sure to give permission to access the database.

Now replace <username> and <password> in the connection string with your database user just created.

Back to coding

Go to your terminal and cd to your next.js project then install the 'mongodb' package just running

yarn add mongodb

Then go to your src folder if you have one otherwise just create a utils folder in the root. Then create a file called mongodb.ts

Copy this snippet into the file:

import { MongoClient } from 'mongodb';

const MONGODB_URI: any = process.env.MONGODB_URI;
const MONGODB_DB: any = process.env.DB_NAME;

// check the MongoDB URI
if (!MONGODB_URI) {
    throw new Error('Define the MONGODB_URI environmental variable');
}

// check the MongoDB DB
if (!MONGODB_DB) {
    throw new Error('Define the MONGODB_DB environmental variable');
}

let cachedClient: any = null;
let cachedDb: any = null;

export async function connectToDatabase() {
    // check the cached.
    if (cachedClient && cachedDb) {
        // load from cache
        return {
            client: cachedClient,
            db: cachedDb,
        };
    }

    // set the connection options
    const opts :any = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    };

    // Connect to cluster
    let client = new MongoClient(MONGODB_URI, opts);
    await client.connect();
    let db = client.db(MONGODB_DB);

    // set cache
    cachedClient = client;
    cachedDb = db;

    return {
        client: cachedClient,
        db: cachedDb,
    };
}

Let's create a simple API in your Next.js that insert jokes to your databases.

in the pages/api folder create a file called 'jokes.ts'

import {connectToDatabase} from '@utils/mongodb'

export default async function jokes(req, res) {
  
  const { joke }  = req.body;


  try {
  
      let { db } = await connectToDatabase();
   
      let createTheJoke =  await db.collection('jokes').insert({
          joke: joke 
        });

        res.status(200).send({ done: 'Joke Created', joke: joke  })
      
  
  } catch (error: any) {
    res.status(error.status || 500).end(error.message)
  }
}

It's simple as that. The important part is:

await db.collection('jokes').insert({
joke: joke
});

This will insert a joke in your database.

To create the joke you need to send a POST request to http://localhost:3000/api/jokes

That's it for today people. Thank you so much for reading and supporting my writing.

Feel free to request any tutorial or article just by sending an email.

More resources:

Setup New Relic (Browser) In Your Next.js App
Have you ever wondered why you have a high bounce rate? or why is your application not performing? New Relic helps you to understand what happens with your application after the user lands in your app. For anyone who likes to learn with videos here is the video of this
Useful KPIs For Any Frontend Teams And How to Measure Them
Train your team to focus on what matters and give an effective performance review Before you jump into finding a KPI for your team, it’s important to know your responsibility and the ‘why’. Are you responsible for helping your company to generate more sales, marketing growth, SEO ranking? or