'In Next.js when fetching data from ghost CMS it ends up in 502 error only on first load
I'm using Heroku free plan to host the blog section of a website in Ghost CMS and use Next.js for the front(netlify) to fetch the data from it. On first loading I'm getting an 502 error - Runtime.UnhandledPromiseRejection - FetchError: invalid json response body / Unexpected token < in JSON at position 0. By refreshing the page everything works as expected. Then when the dyno sleeps and someone click the blog url again and wakes the dyno, the same behaviour occurs.
async function getPosts() {
const res = await fetch(
`${BLOG_URL}/ghost/api/v4/content/posts/?key=${CONTENT_API_KEY}&fields=title,slug,custom_excerpt,published_at`,
);
const data = await res.json();
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
const posts = data.posts;
return posts;
}
export const getStaticProps = async ({ params }) => {
const posts = await getPosts();
return {
props: { posts },
revalidate: 3,
};
};
This is the code for the blog page and similar for the slug page. It seems that JSON is invalid during the call and "if (!data)" does not handling the error. Any ideas why this error appears and if there is a solution?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
