Reputation: 130
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...
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
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):
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:
https://flaviocopes.com/axios-send-authorization-header/
https://flaviocopes.com/node-axios/
Upvotes: 3