Home > Software design >  Connect mongodb to Next.js built in API
Connect mongodb to Next.js built in API

Time:01-19

I am trying to connect a MongoDB database to the Next.js built-in API using the code provided below, which I obtained from the internet.

/api/blogs/[slug].ts

import type { NextApiRequest, NextApiResponse } from 'next'
import { connectToDatabase } from '../../../database/connectToDatabase'

const allowedReqMethod = "GET"

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method === allowedReqMethod) {
        const slug = req.query.slug
        try{
            const {db} = await connectToDatabase()
            const blog = await db.collection("blogs").findOne({slug})
            res.status(200).json({blog})
        } catch (error) {
            res.status(500).json({ message: "Internal server error" })
        }
    } else {
        res.status(400).json({ message: "Bad request" })
    }
}

connectToDatabase.ts

import { Db, MongoClient } from "mongodb";

const MONGODB_URI = process.env.MONGODB_URI;
const MONGODB_DB = process.env.MONGODB_DB;

let cachedClient: MongoClient;
let cachedDb: Db;

export async function connectToDatabase() {
    // check the cached.
    if (cachedClient && cachedDb) {
        // load from cache
        return {
            client: cachedClient,
            db: cachedDb,
        };
    }

    // set the connection options
    const opts = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    };

    // check the MongoDB URI
    if (!MONGODB_URI) {
        throw new Error("Define the MONGODB_URI environmental variable");
    }
    // check the MongoDB DB
    if (!MONGODB_DB) {
        throw new Error("Define the MONGODB_DB environmental variable");
    }

    // Connect to cluster
    let client = new MongoClient(MONGODB_URI);
    await client.connect();
    let db = client.db(MONGODB_DB);

    // set cache
    cachedClient = client;
    cachedDb = db;

    return {
        client: cachedClient,
        db: cachedDb,
    };
}

My question is, does the API initiate a connection to the database (via the function connectToDatabase()) every time the API is called? If so, would this not be considered bad practice as it would result in a long wait time?

CodePudding user response:

Based on the given example, the function does the connection once an then caches it in the let cachedClient: MongoClient; and let cachedDb: Db; variables, so the next time it calls the function it will reuse the cached connections.

  • Related