Skip to content

Instantly share code, notes, and snippets.

@donstefani
Created March 8, 2020 22:44
Show Gist options
  • Save donstefani/70ef1069d4eab7f2339359526563aab2 to your computer and use it in GitHub Desktop.
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
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);
}
};
@EstebanVargas10
Copy link

Thanks! :)

@matthewgani
Copy link

matthewgani commented Aug 3, 2022

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;
};

@rajasuman09
Copy link

That worked. Thanks

@mungaben
Copy link

thank you ! saved me big time

@Harischand2
Copy link

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