I currently have a configuration (NextJs with GraphQL) where on my blog page, I fetch for posts from a WordPress website through GraphQL. Below, the code runs the function getPosts() which is inside an api/graphql-api.js file.
My issue is that this works perfectly in local environment as well as netlify-cli when I run it in dev. The problem I face is that it doesn’t fetch the blogs in Production and I cannot see any error logs to debug. I tried putting the graphql-api.js inside netlify->functions folder as well so that it can run through there but it still isn’t working (maybe because I’m importing the file from netlify/functions instead of .netlify/functions? What could be the problem? Below is the code:
export async function getServerSideProps(ctx){
try {
let blogPosts = await getPosts();
return {
props: {
blogPosts
}
}
} catch (error) {
console.log(error);
return {
props: {
blogPosts: []
}
}
}
}
The graphql-api.js file is:
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' }
const res = await fetch('http://blog.example.com/graphql', {
method: 'POST',
headers,
body: JSON.stringify({
query,
variables,
}),
})
const json = await res.json()
if (json.errors) {
console.error(json.errors)
throw new Error('Failed to fetch API')
}
return json.data
}
export async function getPosts(){
const data = await fetchAPI(
`query AllPosts {
posts(first: 9) {
edges {
cursor
node {
title
id
author {
node {
firstName
lastName
name
}
}
categories {
nodes {
name
slug
taxonomyName
}
}
databaseId
excerpt(format: RENDERED)
slug
content(format: RENDERED)
uri
featuredImage {
node {
mediaItemUrl
sourceUrl
}
}
date
}
}
pageInfo {
hasNextPage
hasPreviousPage
endCursor
startCursor
}
}
}
`,
{
variables: {},
}
);
return data?.posts?.edges;
}