/token endpoint - CORS Error

Solved!

/token endpoint - CORS Error

My Question or Issue

When sending an request to: https://accounts.spotify.com/token

 

 

 

 

 

Access to fetch at 'https://accounts.spotify.com/token' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

 

 

 

 

 

 

It would be nice to know if it is intentional to block request coming from the client.
I'm creating an svelte package that would handle authentication + wraps the player for the end-user for easy access. It currently handles authentication with PKCE, but sending request from the client will cause these CORS issues. For sake of simplicity for end-users, aimed to have this package client-sided as the Web Playback SDK is fully client-sided.

Code used for fetching:

Spoiler
  const body: AccessTokenBody = {
    client_id: client,
    grant_type: 'authorization_code',
    code: code,
    redirect_uri: redirect,
    code_verifier: verifier
  }; 
  const response = await fetch(endpoints.token, {
    body: new URLSearchParams(body),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
  });

  if (response.status === 200) {
    const json: AccessTokenResponse = await response.json();
    return json;
  } else {
    console.log('Invalid response while fetcing token!', response.statusText);
  }

Sidenote:
I have created an personal react app 1y ago that used PKCE and Web Playback SDK and it worked fully in the client. It seems nothing has changed in the documentation, so has there been an decision to block request from the client?

Reply

Accepted Solutions
Marked as solution

Welcome to the forum, @Anent!

 

The endpoint for fetching access tokens is https://accounts.spotify.com/api/token. The error message that you posted shows a slightly different endpoint. Could you double check that you are sending the request to the right URI?

View solution in original post

3 Replies
Marked as solution

Welcome to the forum, @Anent!

 

The endpoint for fetching access tokens is https://accounts.spotify.com/api/token. The error message that you posted shows a slightly different endpoint. Could you double check that you are sending the request to the right URI?

Thanks, yeah this is totally on me. I don't know how I missed that I'm calling an incorrect endpoint 😞
Thought that an incorrect endpoint would give some error codes etc, and didn't focus on it so much 😕

Changed it to the correct endpoint and got it working.

Great, glad to hear that you were able to solve it 🙂

Suggested posts