Nextjs and MongoDB Internal Server Error

I have a Next.js app project that allows storing names and emails using a MongoDB database with MongoDB Atlas.

When I enter a name and an email on my local machine, I don’t encounter any errors, and these data (name and email) are stored perfectly in the database. I can see them in a collection that I created on MongoDB Atlas.

However, when I try to perform the same operations while being online, I receive an error message saying “Internal Server Error.”

My question is: Why is the database able to store the entered data on my local machine but unable to do so when I’m online?

So this my configFile Database :

import { MongoClient, Db } from "mongodb";

let db: Db;
let uri = process.env.NEXT_PUBLIC_MONGODB_URI;

export const connectToDatabase = async (): Promise<void> => {
  const url = uri;
  const dbName = "taftafemails";

  const client = new MongoClient(url, {
    useUnifiedTopology: true,
  } as any);

  try {
    await client.connect();
    console.log("Connected to the MongoDB server");

    db = client.db(dbName);
  } catch (error) {
    console.error("Error connecting to the MongoDB server:", error);
  }
};

export const getDatabase = (): Db => {
  if (!db) {
    throw new Error("Database connection not established");
  }
  return db;
};

This is my file for api routes : pages/api/contact.ts:

import { NextApiRequest, NextApiResponse } from "next";
import { connectToDatabase, getDatabase } from "database/mongo";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "POST") {
    try {
      const { name, email } = req.body;

      await connectToDatabase();

      const db = getDatabase();

      const collection = db.collection("contacts");

      const existingContact = await collection.findOne({ email });
      if (existingContact) {
        res.status(409).json({
          error: "Cette adresse existe déjà, veuillez choisir un autre",
        });
        return;
      }

      await collection.insertOne({ name, email });

      res.status(200).json({
        message: "Vous êtes maintenant abonnés, on vous tient informés !",
      });
    } catch (error) {
      console.error("Error submitting contact form:", error);
      console.dir(error);
      res.status(500).json({ error: "Internal Server Error" });
    }
  } else if (req.method === "GET") {
    res.status(200).json({ message: "Ceci est le formulaire d'inscription" });
  } else {
    res.status(405).json({ error: "Méthode non autorisée" });
  }
}

This is my Form file to communucate with api/route :

try {
        const response = await fetch("/api/contact", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ name, email }),
        });
        ...

Please help me :pray: :pray:

What do you mean by “when I’m online?”

It sounds like you can’t connect when the Nextjs app is hosted somewhere else besides your local. I would verify that 1. the IP address of the other location is whitelisted on Atlas 2. There are no FW’s blocking the connectivity (if it’s a VM or other hosted server)

So in the “Add IP Whitelist Entry”, I select the “Allow Access From Anywhere” which is 0.0.0.0/0, please I’m not familiar with MongoDB, please help :pray:

Okay so the IP is whitelisted which is good. So MongoDB isn’t blocking the IP.

If you have the mongosh installed or can install it whichever machine is having issues connecting you can try to connect to your atlas cluster via mongosh. This will rule out any connectivity issues if it can connect.