Bad gateway error

From what I see, the problem is caused by your nextjs app, since It takes too long to build the content and return it to the browser. If you access your APIs directly, do they respond fast or not? You should investigate your code to understand who exactly responds so long, your nextjs framework, or the strapi’s API.