DEV Community

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

Posted on

1

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay