Getting a 504/502 error on api requests in Nextjs deployed on Vercel
What I did as a result of constant research was that I posted the API on Heroku and the frontend on Vercel. I read this suggestion in one stackoverflow post from a guy who said that he worked in Vercel and this was the most suitable solution for this.
I think this is a problem with the serverless architecture itself. I tried deploying Nextjs on netlify and faced a similar situation.
Try and isolate the source of the issue first, so you know what steps to take next.
For example, try returning some dummy data without using or connecting to the DB.
export default async function handler(req, res) {
console.log('Entered the serverless function')
return { "dummy": "data"}
}
If you still have timeout issues, you now know it's probably because of your Vercel NextJS setup.
If your NextJS setup is not the problem, then you know the issue is caused by your DB. Either the problem is in the query itself, or in the connection.
I'm not sure what DB you're using (I assume it's MongoDB from the syntax).
Most likely possible solutions:
- It's not very clear what
db()
does or what it is. I assume it handles connection to the MongoDB instance. Either way, make sure to check if thedb()
function is asynchronous or not. It's a common mistake; If the function is async and you don't call it properly, then it's possible that the timeout is caused by this asynchronous issue. - Do you create new connections for each request or do you reuse existing open connections? Creating a new connection every time can be expensive; It's possible that that's what causes your timeout issue.
If these don't work, try the below:
- How is your DB hosted? Is it managed by Vercel? Try using another manager to see if that is where the issue resides.
- Is everything setup correctly in your Vercel dashboard? Make sure you have the correct MongoDB connection string, and that your MongoDB instance is set up to accept connections from your app.