Skip to content

Instantly share code, notes, and snippets.

@donstefani
Created March 8, 2020 22:44
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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);
}
};
@fiote
Copy link

fiote commented Jun 12, 2020

This saved my life. Thanks!

@Shubhank92
Copy link

Thanks for the solution, Really helpful!

@stavelmashally
Copy link

Thanks, helped me a lot!

@astriskit
Copy link

Thanks, this helped!

@rohit-sagar256
Copy link

Thanks for saving my time and also i don't think we need stringify for the small part we can also use {data: 'grant_type=client_credentials'}

@ghitafilali
Copy link

Thank you so much for posting this! I spent so much time getting it to work and couldn't, your code helped me get it to work in literally one try!

@zhaluza
Copy link

zhaluza commented Nov 2, 2020

Thanks! This is the format I was using for my Axios request - despite it working for others in the past, I kept getting 400 errors!

axios({
          url: 'https://accounts.spotify.com/api/token',
          method: 'post',
          params: {
            grant_type: 'client_credentials'
          },
          headers: {
            'Accept':'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          auth: {
            username: clientId,
            password: clientSecret
          }
      })

@TanmayBhosale
Copy link

Thank you soo much !!

@SjorsHijgenaar
Copy link

Amazing, thanks!

@eunos-1128
Copy link

eunos-1128 commented Sep 11, 2021

As of September, 2021, this code didn't work for me.

Remove auth and add BASE64_ENCODED_AUTH_CODE to put it into Authorization in headers.
It worked well for me.

import axios from 'axios';
import qs from 'qs';

export const getAuth = async () => {
  const BASE64_ENCODED_AUTH_CODE = "<your BASE64-Encoded Client ID/Client Secret >";
  const headers = {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: `Basic ${BASE64_ENCODED_AUTH_CODE}`
    }
  };
  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