I tried searching a lot on the internet but I didn't find an effective solution. It turns out that, when loading two pages at the same time, one of them generates the error "MongoDB: Connection is closed", on the client side I am using getServerSideProps so that the api is called on the server side (I believed that this would solve the problem), but now I believe the problem is in the api.
I'm going to use this example API, it looks like this:
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Get query/params
try {
const db = await getDatabase(process.env.APP_DB);
const users = db.collection('users');
const user = await users.findOne({
refresh_token: refreshToken
});
if (!user) return res.status(403).json({ error: "Not authorized." });
res.status(200).json({ name: user.name, lastname: user.lastname, email: user.email, phone: user.phone, refreshToken: user.refresh_token });
} catch (error) {
console.error(error);
} finally {
await closeDatabase()
}
}
Yes, I am opening and closing my connection on each API call because I haven't seen effective ways to use the connection pool without leaking connections.
To help, I tried leaving my connection to the database as follows:
const client = new MongoClient(MONGODB_URI, {
});
let cachedDb = null;
async function connectToDatabase(dbName) {
if (cachedDb) {
return cachedDb;
}
try {
await client.connect();
const db = client.db(dbName);
cachedDb = db;
return db;
} catch (error) {
console.error('Error connecting to MongoDB:', error);
throw error;
}
}
export async function getDatabase(dbName) {
if (!cachedDb) {
await connectToDatabase(dbName);
}
return cachedDb;
}
export async function closeDatabase() {
if (cachedDb) {
await client.close();
cachedDb = null;
}
}
Note: I am ignoring imports and other irrelevant information in this example.
I'm using next14 and mongoose 8.2.0.
Unfortunately I was not successful and one connection continues to close the other halfway. Can you help me with a solution? I'm a curious, novice developer. Thanks!