Gabriel Gutierrez
Gabriel Gutierrez

Reputation: 147

"ReferenceError: XMLHttpRequest is not defined" when using getServerSideProps() with NextJS

I'm trying out NextJS with SSR and I'm getting the following error when using the spotify-web-api-js library (witch works fine on the client side) to get a playlist's data:

error - ReferenceError: XMLHttpRequest is not defined
    at _performRequest (D:\GitHub\spotify-stats.js\node_modules\spotify-web-api-js\src\spotify-web-api.js:75:15)
    at _checkParamsAndPerformRequest (D:\GitHub\spotify-stats.js\node_modules\spotify-web-api-js\src\spotify-web-api.js:169:12)
    at Constr.getPlaylistTracks (D:\GitHub\spotify-stats.js\node_modules\spotify-web-api-js\src\spotify-web-api.js:759:12)
    at getServerSideProps (webpack-internal:///./pages/index.js:416:85)
    at Object.renderToHTML (D:\GitHub\spotify-stats.js\node_modules\next\dist\server\render.js:508:26)
    at async doRender (D:\GitHub\spotify-stats.js\node_modules\next\dist\server\base-server.js:669:38)
    at async cacheEntry.responseCache.get.isManualRevalidate.isManualRevalidate (D:\GitHub\spotify-stats.js\node_modules\next\dist\server\base-server.js:778:28)
    at async D:\GitHub\spotify-stats.js\node_modules\next\dist\server\response-cache\index.js:80:36 {
  page: '/'
}

The code inside the getServerSideProps is the following:

export async function getServerSideProps() {
  const res = await SpotifyApi.getPlaylistTracks("37i9dQZEVXbMDoHDwVN2tF", {
    limit: 4,
  });
  const list = res.items;
  console.log("items", list);
  const data = {};
  return { props: { data } };
}

Is there any way to fix this issue or should I use the "server" version for SSR (and have one more library with the same functionality of the client one just for this page)?

Upvotes: 1

Views: 1932

Answers (1)

klvs
klvs

Reputation: 1177

The XMLHttpRequest API isn't provided in node.js. I suppose it's possible to use a module that does but it would probably be better to use a library that is intended to be used for both client and server side (isomorphic).

Taking a look at spotify's web api documentation I notice that they list a bunch of wrappers of their API for different languages and environments. This isomorphic one sticks out to me as the best option for your usecase.

Upvotes: 2

Related Questions