when i run the site locally, there are no problems connecting to mongodb - issue only when deployed to netlify
site: https://main--ayurmantraa.netlify.app/mongo
enter any text in the text box and press save data - see the console log/network call - it always returns timesout / returns 502 after approx. 10-15 seconds …i also have other calls to database within the app - post login and see they also return 502 after 10-15 seconds…the mongo page is a good example of what i am trying to do in the rest of the app.
i tried making all services background - following the netlify docs using
// This enables the function to run in the background for up to 15 minutes
export const config = {
type: "experimental-background",
};
----------------within /src/app/functions, the saveData.ts file:
export default async function handler(req: Request) {
try {
if (req.method == "POST") {
const a = await req.text();
const data = JSON.parse(a);
const client = new MongoClient(
"mongodb+srv://<usr>:<pwd>@<myDb>.mongodb.net/etc",
{
authSource: "admin",
}
);
await client.connect();
return await client
.db("myFirstDatabase")
.collection("bookings")
.insertOne(data)
.then(async (r) => {
await client.close();
return NextResponse.json(
{ message: "Data saved successfully!", m2: r, data: data, req: JSON.stringify(req) },
{
status: 201,
}
);
})
.catch(async (e) => {
await client.close();
return NextResponse.json(
{ message: e },
{
status: 500,
}
);
});
}
} catch (error: any) {
return { statusCode: 500, body: error.toString() };
}
}
// This enables the function to run in the background for up to 15 minutes
export const config = {
type: "experimental-background",
};
----------------and using nextjs/react framework, within /src/app/api/saveData/route.ts:
export async function POST(req: Request) {
if (req.method == "POST") {
const a = await req.text();
const data = JSON.parse(a);
const client = new MongoClient(
"mongodb+srv://<usr>:<pwd>@<myDb>.mongodb.net/etc",
{
authSource: "admin",
}
);
await client.connect();
return await client
.db("myFirstDatabase")
.collection("customer")
.insertOne(data)
.then(async (r) => {
await client.close();
return NextResponse.json(
{ message: "Data saved successfully!", m2: r, data: data, req: JSON.stringify(req) },
{
status: 201,
}
);
})
.catch(async (e) => {
await client.close();
return NextResponse.json(
{ message: e },
{
status: 500,
}
);
});
}
}
any advice on this? thank you for your time !
update 1: also tried the solution to a similar problem here (502 error on production even though the response times are well below 10 seconds) with no luck