Unhandled Promise Rejection Vercel NextJS
Answered
Barbary Lion posted this in #help-forum
Barbary LionOP
I have hosted my mongodb nextjs site on vercel, integrated mongodb, added try catch literally everywhere but I am still getting 500 1 out of every 2-3 requests made to the home page with this error:
LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
Error: Runtime exited with error: exit status 128
Runtime.ExitError
ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoServerSelectionError: Server selection timed out after 30000 ms","reason"
My website: https://mysticleads.com
I can't seem to get any specific logs or find anything concrete on google or vercel.
Please help
LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
Error: Runtime exited with error: exit status 128
Runtime.ExitError
ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoServerSelectionError: Server selection timed out after 30000 ms","reason"
My website: https://mysticleads.com
I can't seem to get any specific logs or find anything concrete on google or vercel.
Please help
Answered by Anay-208
const { data } = await axios.post(`${process.env.MONGODB_API_ENDPOINT}/findOne`, {
dataSource:"source",
database: "admins",
collection: "users",
filter: {
email: email,
name: name
},
projection: {}
}, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"apiKey": process.env.MONGODB_API_KEY
},
})
this code works for me
168 Replies
Barbary LionOP
anyone?
@Barbary Lion anyone?
can you send your code?
short part
Barbary LionOP
what part of the code?
where you're using db
Barbary LionOP
yeah man a sec
// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient } from "mongodb"
if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
}
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
import { MongoClient } from "mongodb"
if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
}
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
and then I am using like this:
import clientPromise from "@/lib/mongodb";
//check if user already exists
const client = await clientPromise;
const db = client.db("test");
const users = db.collection("users");
let user = await users.findOne({ email });
import clientPromise from "@/lib/mongodb";
//check if user already exists
const client = await clientPromise;
const db = client.db("test");
const users = db.collection("users");
let user = await users.findOne({ email });
@Anay-208 see any issue?
@Barbary Lion <@755810867878297610> see any issue?
It’s an issue with mongodb server only. It could be because each connection is connecting to same shared cluster, which is causing increasing in latency.
I recommend you to use mongodb data api
Barbary LionOP
What's that?
@Barbary Lion What's that?
Mongodb data api, just allows you to access database with a api
You can enable it on panel
And see documentation on how to use it
@Anay-208 Mongodb data api, just allows you to access database with a api
Barbary LionOP
Can you share some useful links?
It’s a mongodb cluster issue only. You’ll have to contact support for
Barbary LionOP
Migrating to data api might be a Big change
@Anay-208 It’s a mongodb cluster issue only. You’ll have to contact support for
Barbary LionOP
mongodb support right?
otherwise its a latency for it. you'll have to contact mongodb for it
I'm suggesting you alternatives
Barbary LionOP
So my solution is to either contact mongodb support or use mongodb data api?
mongodb data api is best for serverless apps
Barbary LionOP
alright then I'll first try to contact support otherwise use data api
Wait, is it working on development?
Barbary LionOP
But I still didn't get the cause of the issue(though you described it)
yes it is
no issues
Its not a mongodb issue then. It could be the issue of your hosting provider rate limiting outbound connections
Barbary LionOP
i am using vercel
and just connecting to the database once?
Also I am using next auth
and try to use the same code in production once which you used in development
and fyi, its best to embed code in codeblocks like this
this can be achieved by
```
console.log("Hello World")this can be achieved by
```js
Code goes here```
Barbary LionOP
home
I dont need that
@Anay-208 and try to use the same code in production once which you used in development
Barbary LionOP
so I just need to remove if condition
lemme try that
@Barbary Lion so I just need to remove if condition
just try removing that
Barbary LionOP
yeah
and use the same statement for production as in development
Barbary LionOP
I pushed it let me test
I don't think it'll work.
Barbary LionOP
any other suggestions?
edge function crashed
even worse lol
@Anay-208 getting this
TypeError: Expected an instance of Response to be returned
at (node_modules/next/dist/esm/server/web/adapter.js:180:14)
TypeError: Expected an instance of Response to be returned
at (node_modules/next/dist/esm/server/web/adapter.js:180:14)
change it back
Barbary LionOP
on it
done
so now my solution is back to data api/support?
and you've allowed access by all ips in mongodb cluster, right?>
Barbary LionOP
yes
covered
you wanna jump on a call to further look over my code?
Barbary LionOP
@Anay-208 The site is actually working fine I mean 1 out of every 2 requests is 200 and also database works fine
@Anay-208 Can you try on some other provider first
Barbary LionOP
any other solution before trying this?
Nope. I believe it could be due to cold start
Barbary LionOP
what's that
@Barbary Lion what's that
you can google it
using data-api is a best option for serverless apps
Barbary LionOP
alr so support is also out of the picture?
You can try contacting vercel support I think
data api is the best option
Barbary LionOP
okay thanks I will
Barbary LionOP
@Anay-208 I changed my .mongodb file inside lib to this https://github.com/vercel/mongodb-starter/blob/main/lib/mongodb.ts
That fixed it
@Barbary Lion That fixed it
This is right. This repo is of Vercel so that’s why it works. They’ve added the best compatible way.
Barbary LionOP
@Anay-208
The error hasn't gone fully
umm
Barbary LionOP
its like 1 out of every 20-30 requests still failing
I also deployed on serverless netlify
I added this at the end of mongodb uri ?serverSelectionTimeoutMS=60000&readPreference=secondaryPreferred
@Anay-208 That fixed it to 1 failed request every 20-30 requests
but wasn't a permanent fix
@Barbary Lion I added this at the end of mongodb uri ?serverSelectionTimeoutMS=60000&readPreference=secondaryPreferred
try adding
?retryWrites=true&w=majorityBarbary LionOP
that's already there
Barbary LionOP
2024-01-30T14:51:25.319Z ba64318f-9366-4bd2-a5e7-d81e884c3b88 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"MongoServerSelectionError: connection timed out","reason":{"errorType":"MongoServerSelectionError","errorMessage":"connection timed out","reason":{"type":"ReplicaSetNoPrimary","servers":{},"stale":false,"compatible":true,"heartbeatFrequencyMS":10000,"localThresholdMS":15,"setName":"atlas-wwfy0e-shard-0","maxElectionId":null,"maxSetVersion":null,"commonWireVersion":0,"logicalSessionTimeoutMinutes":null},"stack":["MongoServerSelectionError: connection timed out"," at EventTarget.<anonymous> (/var/task/node_modules/mongodb/lib/sdam/topology.js:276:34)"," at [nodejs.internal.kHybridDispatch] (node:internal/event_target:757:20)"," at EventTarget.dispatchEvent (node:internal/event_target:692:26)"," at abortSignal (node:internal/abort_controller:369:10)"," at TimeoutController.abort (node:internal/abort_controller:403:5)"," at Timeout.<anonymous> (/var/task/node_modules/mongodb/lib/utils.js:1011:92)"," at listOnTimeout (node:internal/timers:569:17)"," at process.processTimers (node:internal/timers:512:7)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: MongoServerSelectionError: connection timed out"," at process.<anonymous> (file:///var/runtime/index.mjs:1276:17)"," at process.emit (node:events:529:35)"," at emit (node:internal/process/promises:149:20)"," at processPromiseRejections (node:internal/process/promises:283:27)"," at process.processTicksAndRejections (node:internal/process/task_queues:96:32)"]}
[ERROR] [1706626285320] LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
Error: Runtime exited with error: exit status 128
Runtime.ExitError
[ERROR] [1706626285320] LAMBDA_RUNTIME Failed to post handler success response. Http response code: 400.
Error: Runtime exited with error: exit status 128
Runtime.ExitError
@Anay-208 see anything?
Barbary LionOP
its from vercel
how do I check mongodb logs?
btw this is the website https://mysticleads.com
Asiatic Lion
Hi there!
Same as here?
Same as here?
Barbary LionOP
yh
I've checked all of em
@Asiatic Lion https://github.com/vercel/vercel/issues/10671
@Barbary Lion it hasn’t been fixed since 4 months. I highly recommend you to use mongodb api as an alternative
Before that, contact Vercel support directly
Barbary LionOP
alright
I am literally tired of this stupid err
the guy at mongodb support also said he isn't sure if data api would solve the issue(he was very unconfident)
@Barbary Lion the guy at mongodb support also said he isn't sure if data api would solve the issue(he was very unconfident)
… it would. I’ve used data api for 1 application
I haven’t got any error
Barbary LionOP
ah thanks for telling that
atleast now i'm sure
It could be different depending upon the functions. I’m not sure
But I recommend contacting Vercel support first with a link to that discussion
That the guy sent
Barbary LionOP
yeah right
@Anay-208 would you recommend any wrapper for the data api?
I am thinking about this https://github.com/surmon-china/mongodb-data-api
Barbary LionOP
what did you do?
@Barbary Lion what did you do?
I used fetch api. I’ll also make a wrapper for data api soon
Asiatic Lion
@Anay-208, can you tell the version of Next.js of your project, please?
It is App Router already? Thank you.
It is App Router already? Thank you.
Barbary LionOP
@Asiatic Lion It's not app router
Pages router
Barbary LionOP
@Anay-208 I am having trouble with data api as well
It says conn refused
can you help?
hi, since this thread is already answered, could you make new posts for other questions?
Barbary LionOP
its not answered. The problem I am facing has no other solution than "upgrading" mongodb from shared cluster to payed one
or the data api which I can't seem to get
oh ok
@Barbary Lion <@755810867878297610> I am having trouble with data api as well
Can you send your code?
Barbary LionOP
@Anay-208 sending it
mongoconfig.js
export default function config(payload,method) {
return {
method: "post",
url: `https://ap-south-1.aws.data.mongodb-api.com/app/data-wjryq/endpoint/data/v1/action/${method}`,
headers: {
"Content-Type": "application/json",
"Access-Control-Request-Headers": "*",
"api-key":
process.env.DATAAPI_KEY,
},
data: payload,
};
}handler
var axios = require("axios");
import config from "@/lib/mongoconfig";
//check if user already exists
var data = {
collection: "users",
database: "test",
dataSource: "Cluster0",
projection: {
email: email,
},
};
axios.post(config(data, "findOne"))
.then((res) => console.log(res))
.catch((res) => console.log(res))and the error i get is econnreset
@Anay-208 interestingly it works on postman with the same api key etc but fails on localhost
Barbary LionOP
okay hold on
@Barbary Lion Click to see attachment
I also got this error once
Barbary LionOP
and ?
I didn't do anything and it worked after few mins
Barbary LionOP
interesting
lemme try again
and now its even working in production
Barbary LionOP
nah its still not working
@Anay-208 any idea on what I should do?
I took down all other mongodb connections and its working in postman
but can't in localhost
apart from the host there isn't a diff between those two
@Barbary Lion <@755810867878297610> any idea on what I should do?
Try sending request using Curl
Barbary LionOP
I don't have curl
how is that gonna help btw?
If it doesn’t work with curl, then it’s a mongodb issue.
I’ll send you soon my code and how I got it working
In 2 hours maybe
Barbary LionOP
okay I also think its a mongodb issue
maybe I can try creating a new db
const { data } = await axios.post(`${process.env.MONGODB_API_ENDPOINT}/findOne`, {
dataSource:"source",
database: "admins",
collection: "users",
filter: {
email: email,
name: name
},
projection: {}
}, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"apiKey": process.env.MONGODB_API_KEY
},
})
this code works for me
Answer
Barbary LionOP
lemme put it
also a big thank you for helping me navigate this
@Anay-208 I think its working
@Anay-208 yeah its working
@Barbary Lion <@755810867878297610> yeah its working
Can you mark my answer as a solution?
Barbary LionOP
yeah sure
If you've any other issues, create another help-forum and ping me
Barbary LionOP
@Anay-208 Really glad you helped me with this. I hope the timeout error goes away with this
@Anay-208 If you've any other issues, create another help-forum and ping me
Barbary LionOP
thank you I will
I need to now change the entire application's db calls
Most painful would be to create a custom adapter in next auth
I am using that