Skip to main content

Mongo and Next.JS

In this tutorial, we will learn how to connect to MongoDB and use Next.JS to create a simple app.

Steps

  1. Use create-next-app to bootstrap a next app

    npx create-next-app --example with-mongodb dabble-nextjs-mongo
  2. Change into the dabble-nextjs-mongo project directory

    cd dabble-nextjs-mongo
  3. Run the dev server

    npm run dev
  4. Try to view the app by visiting localhost:3000 - you should see an error because we still need to set the mongo connection string

  5. Rename env.local.example to env.local

  6. Open env.local and set the following environment variables

    MONGODB_URI=your-mongodb-uri
    MONGODB_DB=your-mongodb
  7. Setting up a mongodb on Atlas

    1. Go to MongoDB Atlas
    2. mongodb+srv://USERNAME:PASSWORD@cluster0.tdm0q.mongodb.net/DBNAME?retryWrites=true&w=majority
    3. Setup a username and password
    4. Set the network access for your IP address
  8. Restart the dev server, this time there should not be an error and you will see a screen like the following.

  9. Create a file named pages/api/movies.js and paste in the following code.

    import { connectToDatabase } from "../../util/mongodb";

    export default async (req, res) => {
    const { db } = await connectToDatabase();

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

    res.json(movies);
    };

Resources