FetchError: invalid json response body at... > reason: Unexpected token < in JSON at position 0

Viewed 2751

I'm trying to fetch data from the OpenSea API but keep getting the following error:

FetchError: invalid json response body at https://api.opensea.io/api/v1/assets?format=json&order_direction=desc&owner=0x0f91b5a27c51dcad415eafb190e8235e987dcdcb reason: Unexpected token < in JSON at position 0

Here is my current code:

export async function getServerSideProps() {
  const res = await fetch(`https://api.opensea.io/api/v1/assets?format=json&order_direction=desc&owner=0xc3b9d43afbb3dcc92e19703480f37070692494e1`)
  const data = await res.json()

  return { props: { data } }

}

const Page = ({data}) => {
  return (
    <>
      {data.assets.map(asset => (
        <p>{asset.id}</p>
      ))}
    </>
  )
}

export default Page
2 Answers

Unfortunately opensea does not allow such a request right now.

You get HTML response with 403 error (Forbidden) instead of json.

The similar question here: Request to opensea api failing

The error is triggered because you are getting a HTML response instead of JSON. If you make the request from the browser you get a successful response, but why you get an error making it through server-side? I think it's because there is a missing header in the server-side request. Try to get the HTML by using fetch.text() instead of fetch.json() then look for the error or the page you are getting and the difference between browser and server-side headers.

Related