Performance improvement for Nextjs + Mongodb app

I am using mongodb with nextjs application. I am fetching data from mongodb inside getServerSideProps but I have observed it takes 4-5 secs to fetch data and display it on frontend. Any suggestions how can I improve it?
code:
mongodb.js:

import { MongoClient } from 'mongodb'

const uri = process.env.NEXT_PUBLIC_MONGODB_URI;

const options = {
    useUnifiedTopology: true,
    useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.NEXT_PUBLIC_MONGODB_URI) {
    throw new Error('Please add your Mongo URI to .env.local')
}

if (process.env.NEXT_PUBLIC_NODE_ENV === 'development') {
    // In development mode, use a global variable so that the value
    // is preserved across module reloads caused by HMR (Hot Module Replacement).
    if (!global._mongoClientPromise) {
        client = new MongoClient(uri, options)
        global._mongoClientPromise = client.connect()
    }
    clientPromise = global._mongoClientPromise
} else {
    // In production mode, it's best to not use a global variable.
    client = new MongoClient(uri, options)
    clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;

dashboard.js:

export async function getServerSideProps(context) {
    const session = await getServerSession(context.req, context.res, authOptions);

    if (!session) {
        return {
            redirect: {
                destination: '/login',
                permanent: false
            }
        }
    }

    const client = await clientPromise;
    const db = client.db("mongodb-db");

    const testCollection = db.collection("jobs");
    const testData = await jobsCollection.find({ userId: '100' }).toArray();

    const jobs = JSON.parse(JSON.stringify(testData));

    // Sort the jobs based on timestamp

    // Run a loop over all the sorted jobs i.e extract specific key/value pairs and return the data

    return {
        props: propsData
    }
}

In my case I think that the slowness issue is related to mongodb connection or cold start of vercel serverless functions. Because in monogdb atlas it is showing me query command takes 300-500ms so I don’t think that fetching 500-1k array of objects from mongodb is an issue here. If it is related to connections how can I improve performance? Do I need to close the cursor after fetching data from mongodb? Something like this: proper use of mongo db in Next.js · Discussion #12229 · vercel/next.js · GitHub

Any suggestions? Thanks

Hi :wave: @Aditya_Todkar1,

Welcome to the MongoDB Community forums :sparkles:

I suspect it’s not related to connection, instead, the getServerSideProps() method forces a Next.js page to load with server-side rendering. What this means is that every time this page is loaded, the getServerSideProps() method runs on the backend, gets data, and sends it into the React component via props.

To make it efficient you can wrap your function inside getServerSideProps . I found the following article - How to speed up your getServerSideProps that may be able to help you.

Note that this is an article written by the Next.js community so the content may or may not be helpful to your specific case.

Also, refer to this article to read more about different ways to fetch data to your Next.js application from MongoDB.

I hope it helps!

Best,
Kushagra

2 Likes