Home > OS >  Request authorization error in Spotify API
Request authorization error in Spotify API

Time:03-20

The weirdest thing is happening to my react app. I have moved the Client Id and Client Secret into the environment variables and am loading them into this file using dotenv to create an authorization request:

// Inject environment variables
import dotenv from 'dotenv';
dotenv.config();

const clientID = process.env.CLIENT_ID;
const clientSecret = process.env.CLIENT_SECRET;

// Request authorization
const authOptions = {
  url: "https://accounts.spotify.com/api/token",
  headers: {
    "Authorization":
      "Basic "  
      new Buffer.from(clientID   ":"   clientSecret).toString("base64"),
    "Content-Type": "application/x-www-form-urlencoded",
  },
  form: {
    grant_type: "client_credentials",
  },
  json: true,
};

export default authOptions;

But I'm getting a Failed to load resource: the server responded with a status of 400 () error:

{ error: "invalid_client", error_description: "Invalid client" }

The weird part is that if hard code the client id and secret, it works flawlessly.

I have even printed the environment variables in the console and am getting the correct values but the moment I use them in the authorization header it stops working.

Is there any way to fix this?

CodePudding user response:

From what I see you doing is using an env variable in react which isn't available in the browser.

Just a side note, maybe you shouldn't load secrets in the browser as that isn't a secure environment. Rather use the OAuth strategy for using your client id. Here's a link

To load environment variables to your app. You'd need to prefix it with REACT_APP_. Here's a link

Here's an example

.env

REACT_APP_CLIENT_ID=my-spotify-client-id

CodePudding user response:

I had this error once. I reset my client_secret, added the new value in the .env file, but forgot to terminate my app and run it again. After I rerun my app, it worked.

  • Related