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