Ritvik Biswas
Ritvik Biswas

Reputation: 130

How to use Express to structure the "Client Credentials Flow" for authorization to use the Spotify API?

I'm trying to write a utility with Node.js and Express that would use the Spotify API. However, I'm stuck trying to figure out the best way to use the "Client Credentials Flow" with Express to get an access token to use the API...

https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow

I did some research and Spotify gives this example (in the link below) but it seems rather outdated with the "request" library being used?

https://github.com/spotify/web-api-auth-examples/blob/master/client_credentials/app.js

I've been seeing things like Axios and stuff, but I'm kind of new to all of this and don't know how or where to even look...

Upvotes: 2

Views: 1594

Answers (1)

Ritvik Biswas
Ritvik Biswas

Reputation: 130

I figured this out and here's some help for my friends in the future who may be stuck (based on Google, I saw many were stuck):

  1. Axios is the tool to use to make requests to an API server such as Spotify's. Express is the tool to use if you want to listen and serve requests. This is the link that clarified it for me:

https://stackoverflow.com/questions/62244076/difference-between-express-js-and-axios-js-in-node#:~:text=Axios%20is%20used%20to%20send,an%20alternative%20to%20fetch().

  1. My goal here was to use Spotify's client credentials flow to send a POST request to Spotify's API servers and to get a access token that would allow me to use their API. Axios has this utility. I also want to make this function I write with async-await so that my function waits for the response before it returns it.

Here's the code I wrote that worked for me:

const axios = require('axios');
const qs = require('qs');
require('dotenv').config();

const client_id = process.env.SPOTIFY_API_ID; // Your client id
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');

const getAuth = async () => {
  try{
    //make post request to SPOTIFY API for access token, sending relavent info
    const token_url = 'https://accounts.spotify.com/api/token';
    const data = qs.stringify({'grant_type':'client_credentials'});

    const response = await axios.post(token_url, data, {
      headers: { 
        'Authorization': `Basic ${auth_token}`,
        'Content-Type': 'application/x-www-form-urlencoded' 
      }
    })
    //return access token
    return response.data.access_token;
    //console.log(response.data.access_token);   
  }catch(error){
    //on fail, log the error in console
    console.log(error);
  }
}

Note:

  • Make sure to stringify the grant-credentials before sending it. Don't use the 'querystring' dependency. Use the newer 'qs' dependency. Works the same.
  • Use 'dotenv' to make Node.js environment variables to protect your sensitive data like I did! May help further when you push to GitHub and just add the .env to the files to be ignored in your .gitignore file!
  • Axios has some confusing documentation especially for beginners like me trying to use API's with such authentication flows. Here's are some links that helped me understand and structure my code (along with a lot of testing and failing):

https://flaviocopes.com/axios-send-authorization-header/

https://flaviocopes.com/node-axios/

Upvotes: 3

Related Questions