Skip to content

Instantly share code, notes, and snippets.

@donstefani
Created March 8, 2020 22:44
Show Gist options
  • Select an option

  • Save donstefani/70ef1069d4eab7f2339359526563aab2 to your computer and use it in GitHub Desktop.

Select an option

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

fiote commented Jun 12, 2020

Copy link
Copy Markdown

This saved my life. Thanks!

@Shubhank92

Copy link
Copy Markdown

Thanks for the solution, Really helpful!

@stavelmashally

Copy link
Copy Markdown

Thanks, helped me a lot!

@astriskit

Copy link
Copy Markdown

Thanks, this helped!

@rohit-sagar256

Copy link
Copy Markdown

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
Copy Markdown

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

zhaluza commented Nov 2, 2020 •

Copy link
Copy Markdown

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
Copy Markdown

Thank you soo much !!

@SjorsHijgenaar

Copy link
Copy Markdown

Amazing, thanks!

@eunos-1128

eunos-1128 commented Sep 11, 2021 •

Copy link
Copy Markdown

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
Copy Markdown

Thanks! :)

@matthewgani

matthewgani commented Aug 3, 2022 •

Copy link
Copy Markdown

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
Copy Markdown

That worked. Thanks

@mungaben

Copy link
Copy Markdown

thank you ! saved me big time

@Harischand2

Copy link
Copy Markdown

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