Created
March 8, 2020 22:44
-
-
Save donstefani/70ef1069d4eab7f2339359526563aab2 to your computer and use it in GitHub Desktop.
Getting an access token for a React app from the Spotify API using Node.js and Axios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import qs from 'qs'; | |
export const getAuth = async () => { | |
const clientId = process.env.REACT_APP_BASIC_CLIENT_ID; | |
const clientSecret = process.env.REACT_APP_BASIC_CLIENT_SECRET; | |
const headers = { | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/x-www-form-urlencoded', | |
}, | |
auth: { | |
username: clientId, | |
password: clientSecret, | |
}, | |
}; | |
const data = { | |
grant_type: 'client_credentials', | |
}; | |
try { | |
const response = await axios.post( | |
'https://accounts.spotify.com/api/token', | |
qs.stringify(data), | |
headers | |
); | |
console.log(response.data.access_token); | |
return response.data.access_token; | |
} catch (error) { | |
console.log(error); | |
} | |
}; |
Thanks! :)
I ran into the problem where querystring has been deprecated so learned to use URLSearchParams. This code snippet also uses the grant type refresh_token. This was what worked for me, remember to return response.data.access_token if needed. Hope this helps someone
const getAccessToken = async () => {
const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
// header paremeter
const config = {
headers: {
Authorization: `Basic ${basic}`,
"Content-Type": "application/x-www-form-urlencoded",
}
}
// request body parameter
const data = new URLSearchParams([
['grant_type', 'refresh_token'],
['refresh_token',refresh_token]
]).toString()
const response = await axios.post(TOKEN_ENDPOINT, data, config)
return response.data;
};
That worked. Thanks
thank you ! saved me big time
Thanks, the code all the way to the top still works for 2024! Happy Debugging!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As of September, 2021, this code didn't work for me.
Remove
auth
and addBASE64_ENCODED_AUTH_CODE
to put it intoAuthorization
inheaders
.It worked well for me.