FetchError: invalid json response body reason: Unexpected token < in JSON at position 0 - nextjs

Viewed 2421

I am using getStaticProps and getStaticPaths, I used fetch API to call an API endpoint (which is Wordpress headless CMS in my case) and set the paths for dynamic routing. When I run npm dev it works fine, the data is fetched correctly. But at build time it gives error that:

FetchError: invalid json response body at https://abr.af/wp/wp-json/wp/v2/advisors reason: Unexpected token < in JSON at position 0

My code in pages/advisor/[advisor].js

export const getStaticPaths = async () => {
  const advisors = await getAdvisors()
  const paths = advisors.map((each) => {
    return {
      params: { advisor: each.slug },
    }
  })

  return {
    paths,
    fallback: false,
  }
}

export const getStaticProps = async ({ params }) => {
  const query = params.advisor
  const advisors = await getAdvisors()
  const advisor = advisors.find((advisor) => advisor.slug === query)
  return {
    props: {
      advisor,
    },
  }
}

my fetch function in component/FetchData.js

export async function getAdvisors() {
  const res = await fetch('https://abr.af/wp/wp-json/wp/v2/advisors', {
    method: 'GET',
    headers: {
      // update with your user-agent
      'User-Agent': '*',
      Accept: 'application/json; charset=UTF-8',
    },
  })
  const advisors = await res.json()

  return advisors
}

export async function getExpertise() {
  const res = await fetch('https://abr.af/wp/wp-json/wp/v2/expertise', {
    method: 'GET',
    headers: {
      // update with your user-agent
      'User-Agent': '*',
      Accept: 'application/json; charset=UTF-8',
    },
  })
  const expertise = await res.json()

  return expertise
}

I googled this issue and find that I should add User-Agent header to my request but this not solve my problem.

I am new to Next.js, I don't know what is the reason any help would be appreciated.

1 Answers

I had the same error, and had to switch to getServerSideProps. For my case, the api I was using was a next api that was not readily available during build time (db connection + fetching).

I had to go back to NextJS documentation, to understand when you should use getStaticProps.

And this is what is stated:

  • The data required to render the page is available at build time ahead of a user’s request.
  • The data comes from a headless CMS.
  • The data can be publicly cached (not user-specific).
  • The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance.
Related