Cross-Origin Request Blocked with spotify API

Hi,
I’m trying to create an application (front and back) where at some point the user click to connect to spotify which “hits” the route /spotify on the back-end and the oauth thing is supposed to start but I keep getting those CORS errors.
My front is localhost:3001, back localhost:3000

The error message from firefox :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://accounts.spotify.com/authorize?response_type=code&client_id=CLIENT_KEY&scope=user-read-private&redirect_uri=https%3A%2F%2Flocalhost%3A3000%2Fcallback&state=1btxz1elydu. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

and my code :

  • Front
fetch("http://localhost:3000/spotify", {
      method: "GET",
      origin: "https://localhost:3001",
      credentials: "include",
    }).catch((err) => console.error(err));
  • Back
app.use(
  cors({
    origin: process.env.CORS, // http://localhost:3001 
  })
);

const stateKey = "spotify_auth_state";

app.get("/spotify", (req, res) => {
  // generates states and set it in cookie
  const state = genState();
  res.set({
    "Access-Control-Allow-Credentials": "true",
    "Access-Control-Allow-Origin": "http://localhost:3001",
  });
  res.cookie(stateKey, state);

  // Authorization request
  const scope = "user-read-private";
  res.redirect(
    "https://accounts.spotify.com/authorize?" +
      querystring.stringify({
        response_type: "code",
        client_id: client_id,
        scope: scope,
        redirect_uri: redirect_uri,
        state: state,
      })
  );
});

I’ve been trying a lot and nothing works. Please help me!

As a workaround, you might try a proxy server and see what happens. I’ve only done it once, and it slowed things down significantly, but at least it worked!

Did you end up figuring this out? I’m hitting a similar CORS issue with Spotify/OAuth

Yeah but it was a while ago :sweat_smile:, so basically if you get cors error it’s coming from your browser.
There is different options:

  • you can get an extension on your favorite browser called “CORS Everywhere”
  • You have to authorize your app in your Spotify developer account (so if you develop locally you need to add like localhost)

I cannot really help more I can’t really remember and I’m always struggling with this cors error