Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Nextjs example. Why use next-connect

Here is an example for how to use MongoDB with nextjs: https://developer.mongodb.com/how-to/nextjs-building-modern-applications

Why is next-connect used here? Why share a connection with middleware? Couldn’t a module be used instead?

Hi Roeland, you could. I’m actually making some updates to this article (will be out early next week). There’s been some pretty nice changes to Next.js since this article came out and there are a few improvements I can think of that would make it much better. :slight_smile:

1 Like

Hi Roeland - after looking into this some more, I think I have a more elegant solution (I talked to one of the folks over at Vercel, and they recommended this approach). It’s essentially what you suggested, no need to use middleware. You can simply update your database.js to look like this:

import { MongoClient } from "mongodb";

let uri = "YOUR-CONNECTION-STRING";
let cachedDb = null;

export async function connectToDatabase() {
  if (cachedDb) {
    return cachedDb;
  }
  const client = await MongoClient.connect(uri, { useNewUrlParser: true });
  const db = await client.db("DB-NAME");

  cachedDb = db;
  return db;
}

and then in your API routes, you’d simply import the connectToDatabase method and go from there…

handler.post(async (req, res) => {
  let data = req.body;
  data = JSON.parse(data);
  data.date = new Date(data.date);
  let db = await connectToDatabase();
  let doc = db
    .collection("daily")
    .updateOne({ date: new Date(data.date) }, { $set: data }, { upsert: true });

  res.json({ message: "ok" });
});

Let me know if this helps!

2 Likes

Yes, I did something similar.
But how does MongoDB handle connections?
The connection is not closed here and since an api route will be deployed to aws lambda, there could be many open connections.
Could that cause problems?

I found more about aws lambda and mongodb here:
https://docs.atlas.mongodb.com/best-practices-connecting-to-aws-lambda/

Thanks for the help!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.