When Serverless Functions are throwing a 502 error, this means that no response is being received from the function. This is either due to the function taking too long to respond, or it has thrown an error.
You can get instant feedback on why your Serverless Function is throwing a 502 error by looking at the realtime request logs for your deployment from the Vercel dashboard.
To do this, navigate and select your project on the Vercel dashboard then click "View Function Logs", from now on, until the page is closed, all requests made to Serverless Functions will generate a log. If any errors are present, these will be highlighted in Red.
The easiest way to understand why your Serverless Function is throwing a 502 error is by running it locally either with
next dev, if using Next.js, or
vercel dev if not. Here you can replicate the steps taken before receiving the error and receive instant feedback in your terminal.
If your deployment is not being statically generated at build time, you can change the structure of your application to do this.
Deploying a static site will provide you with a more reliable, available, and performant deployment as your user will be served content immediately, without waiting for page data to arrive and being served errors when content either takes too long or is sent in an incorrect format.