Nextjs example. Why use next-connect

Here is an example for how to use MongoDB with nextjs: Building Modern Applications with Next.js and MongoDB | MongoDB

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:


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 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… (req, res) => {
  let data = req.body;
  data = JSON.parse(data); = new Date(;
  let db = await connectToDatabase();
  let doc = db
    .updateOne({ date: new Date( }, { $set: data }, { upsert: true });

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

Let me know if this helps!


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?

1 Like

I found more about aws lambda and mongodb here:

Thanks for the help!

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