Production grade Next.js

Conntecting to a DB

Connecting

Most DB's were not made for serverless environments. TO get around this with mongo, we're going to cache the DB connection for future use. This is possible because serverless functions reuse the same container across executions which allow us to keep some state around. Lets connect to our DB.

./db/connect.ts
global.mongo = global.mongo || {}

export const connectToDB = async () => {
  if (!global.mongo.client) {
    global.mongo.client = new MongoClient(process.env.DATABASE_URL, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      bufferMaxEntries: 0,
      connectTimeoutMS: 10000,
    })

    console.log('connecting to DB')
    await global.mongo.client.connect()
    console.log('connected to DB')
  }

  const db: Db = global.mongo.client.db('known')

  return { db, dbClient: global.mongo.client }
}

Here we store the db in a global in Node.js. We then check to see if that global is already present before trying to connect. Last, we return the db instance using the mongodb drive. Our db is called known. You can change this if you'd like to anything you want. Take a look through the middleware folder, you can see some db middleware in there that uses the connection to pass the db to any request that uses that middleware.

That's it for the DB, lets move onto using the DB in our pages!