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
Use
create-next-app
to bootstrap a next appnpx create-next-app --example with-mongodb dabble-nextjs-mongo
Change into the
dabble-nextjs-mongo
project directorycd dabble-nextjs-mongo
Run the dev server
npm run dev
Try to view the app by visiting
localhost:3000
- you should see an error because we still need to set the mongo connection stringRename
env.local.example
toenv.local
Open
env.local
and set the following environment variablesMONGODB_URI=your-mongodb-uri
MONGODB_DB=your-mongodbSetting up a mongodb on Atlas
- Go to MongoDB Atlas
- mongodb+srv://USERNAME:PASSWORD@cluster0.tdm0q.mongodb.net/DBNAME?retryWrites=true&w=majority
- Setup a username and password
- Set the network access for your IP address
Restart the dev server, this time there should not be an error and you will see a screen like the following.
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);
};