Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Catevika/eab8c6c2e6ad98003b3b49ea05bfce61 to your computer and use it in GitHub Desktop.
Save Catevika/eab8c6c2e6ad98003b3b49ea05bfce61 to your computer and use it in GitHub Desktop.
NEXTJS14 - Connect MongoDB with Mongoose avoiding multiple connections because of Hot Module Replacement
import mongoose from 'mongoose';

if (!process.env.MONGODB_URI) {
  throw new Error('Invalid environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI;

export const connectDB = () => {
  const existingConnection = mongoose.connections[0].readyState;

  if (existingConnection) {
    console.log('Use existing MongoDB connection');
    return null;
  }

  try {
    mongoose.connect(uri);
    console.log('MongoDB connected');
  } catch (error) {
    return { error: 'MongoDB failed to connect' };
  }
};

export default connectDB;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment