Establish a connection between MongoDB and the built-in API in Next.js

I've been working on integrating a MongoDB database with the Next.js built-in API by using the code snippet below, which I found online.

/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,
    };
}

I'm wondering if the API establishes a new database connection (using the connectToDatabase() function) every time it's called. If so, wouldn't this be considered poor practice due to potential delays?

Answer №1

After reviewing the provided example, it is evident that the function establishes a connection and then stores it in variables let cachedClient: MongoClient; and let cachedDb: Db;. Therefore, subsequent calls to the function will utilize these cached connections.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

transferring data between components in a software system

I received a response from the server and now I want to pass this response to another component for display. I attempted one method but ended up with undefined results. You can check out how I tried here: how to pass one component service response to other ...

Adjusting the state prevents the input fields from being updated

Encountering a problem where setting the const buyFormData results in updating the array but causing the rest of the code (which updates the Input Fields) to stop functioning. No javascript error is showing, the code just hangs there. In my child component ...

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

The TypeScript error code TS2345 indicates that the argument type 'JQueryXHR' cannot be assigned to the parameter type 'Promise<any>'

In a coding tutorial, an example code snippet demonstrates how to execute a JQuery getJSON() call and then transform the result into a Promise, which is later converted into an Observable. /// <reference path="../typings/tsd.d.ts" /> import { Compo ...

What is the best way to optimize reactive values using the Vue composition API?

Imagine I have a block of code like this... const computedStyle = computed(() => normalizeStyle([undefined, styleProp, undefined]) ); const computedClass = computed(() => normalizeClass([ "button", classProp, { "b ...

Creating a Lambda function in CDK: A guide to configuring the Dockerfile and setting environment variables

I am currently working on a SAM project using template.yml. Here is a snippet of the configuration: Globals: Function: Timeout: 30 Environment: Variables: DBNAME: !Ref DBNAME Resources: MessageFunction: Type: AWS::Serverless: ...

Creating a Next.js dynamic route that takes in a user-submitted URL for customization

Currently, I have implemented the Next.js Router to facilitate the display of different dashboards based on the URL slug. While this functionality works seamlessly when a button with the corresponding link is clicked (as the information is passed to the Ne ...

Explore RxJs DistinctUntilChanged for Deep Object Comparison

I have a scenario where I need to avoid redundant computations if the subscription emits the same object. this.stateObject$ .pipe(distinctUntilChanged((obj1, obj2) => JSON.stringify({ obj: obj1 }) === JSON.stringify({ obj: obj2 }))) .subscribe(obj =& ...

Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid. export const theme = { headers: { h1: { }, h6: { color: '#828286' }, }, } console.in ...

Generating a new object from a TypeScript class using JavaScript

Currently, I am facing an issue while attempting to call a JavaScript class from TypeScript as the compiler (VS) seems to be having some trouble. The particular class in question is InfoBox, but unfortunately, I have not been able to locate a TypeScript d ...

Utilizing Next.js Image Component to Apply CSS for Width and Height Settings

Currently, I am utilizing the Image component provided by Next.js, which requires setting specific width and height values. To address this, I am incorporating Tailwind CSS utility classes to establish the desired dimensions. <Image src={imageSr ...

Facing an issue with the React-Three-Fiber Canvas component triggering a 'Module parse failed: setter should have exactly one param' error in my Next.js application. Any suggestions for resolving this issue

Having issues with the Canvas component in react-three-fiber not functioning correctly in my next app. I am new to react-three-fiber and Next.js, and when I try to use the Canvas component, I encounter the following error: ./node_modules/three/build/three ...

Incorporating HTTP status codes into error handling

I have developed an API where I've organized the services separately from the controllers. In my service functions, I've included basic checks to trigger errors when certain conditions are met. Currently, my controller function just returns a 500 ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

In Typescript, it is possible to provide values other than undefined for a parameter that is

I experimented with the code below in TypeScript Playground with all settings enabled. My expectation was that the TS compiler would only allow the first call() to be valid. However, to my surprise, all four calls were accepted. Upon inspecting the calls, ...

"Querying with Mongoose's findOne Method Yields Empty Object Result

I have successfully saved some documents in mongodb compass and now I am attempting to retrieve the values by querying certain parameters. As I understand it, when using mongodb findOne, there are arguments such as query, fields(by default value: all), o ...

Error encountered: "The requested resource does not have the 'Access-Control-Allow-Origin' header in Angular 6 and Nodejs."

I have encountered an issue with my Angular 6 app and Node.js. When I submit the form, I am receiving the following error: Failed to load http://localhost:3000/contact/send: Response to preflight request doesn't pass access control check: No 'Ac ...

The error message "Unconfigured error" continues to appear when using Next.js Image

www.gravatar.com is not being properly configured under images in your `next.config.js` file. This is my current configuration: const config = { reactStrictMode: true, images: { domains: ["gravatar.com"], disableStaticImages: true, }, } mod ...

NextJs application displaying empty homepage and preventing redirection

After successfully deploying my nextjs app on netlify, I encountered a strange issue. When I visit the base url of my website, instead of seeing the homepage, all I get is a blank screen. Oddly enough, if I navigate to specific pages on my site, they load ...

"Ensuring Contact Information is Unique: A Guide to Checking for Existing Email or Phone Numbers in

I'm encountering an issue with validating email and phone numbers in my MongoDB database. Currently, my code only checks for the presence of the email but does not respond to the phone number. const express = require("express"); const router ...