DEV Community

Cover image for Connect MongoDB database with Next JS App(the simplest way)
Saad Naeem
Saad Naeem

Posted on

Connect MongoDB database with Next JS App(the simplest way)

In Next.js, especially when deploying on serverless environments or edge networks, database connections are established on every request.

This is due to the nature of serverless functions, which do not maintain state between requests and can be spun up or down as needed. Here are some key points to consider:

Serverless Functions:

Next.js uses serverless functions for API routes and server-side rendering (SSR).
Each invocation of a serverless function is stateless and isolated, meaning it doesn't maintain a persistent connection to a database.

Therefore, a new database connection must be established for each request.

import mongoose from "mongoose";

// Object to track connection state
type ConnectionObject = {
    isConnected?: number;
};

// Single connection object to be used across requests
const connection: ConnectionObject = {};

// Function to connect to the database
async function dbConnect(): Promise<void> {
    // Check if already connected to avoid redundant connections
    if (connection.isConnected) {
        console.log("Already Connected");
        return;
    }

    try {
        // Establish a new connection
        const db = await mongoose.connect(process.env.MONGO_URI || "", {
            // Use appropriate options here based on your setup
        });

        // Track the connection state
        connection.isConnected = db.connections[0].readyState;

        console.log("DB is connected");
    } catch (error) {
        console.log("DB connection error:", error);
        process.exit(1); // Exit the process if unable to connect
    }
}

export default dbConnect;

Enter fullscreen mode Exit fullscreen mode

Thank You Me Latter

Top comments (0)