~/snippets/Spotify-API-Setup
Published on

Spotify API Setup

675 words4 min read–––
Views
const url = 'https://accounts.spotify.com/authorize'
function getAuthorizationCodeURL() {
  const u = new URL(url)
  u.searchParams.append('client_id', '')
  u.searchParams.append('response_type', 'code')
  u.searchParams.append('redirect_uri', 'http://127.0.0.1:8080/callback')
  u.searchParams.append('scope', 'user-read-currently-playing')
  u.searchParams.append('state', '')
  u.searchParams.append('show_dialog', true)

  return u.href
}

// the above url will redirect to https://localhost:8000/callback?code=bigassnumber
// const code = bigassnumber (manually)

/* this function will provide us refresh token which is valid indefinitely
  save that refresh token in a environment variable and use it to fetch fresh token
  in the function below this one
*/

async function getSpotifyAuthToken() {
  const authTokenBasePath = 'https://accounts.spotify.com/api/token'
  const authTokenURL = new URL(authTokenBasePath)
  authTokenURL.searchParams.append('grant_type', 'authorization_code')
  authTokenURL.searchParams.append('code', code)
  authTokenURL.searchParams.append('redirect_uri', 'http://127.0.0.1:8080/callback')

  const authorizationHeader =
    'Basic ' + new Buffer(clientId + ':' + clientSecret).toString('base64')

  return fetch(authTokenURL.href, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: authorizationHeader,
    },
  }).then((response) => response.json())
}

/* fetch fresh token */

const client_id = process.env.clientId
const client_secret = process.env.clientSecret
const refresh_token = process.env.refreshToken

const basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64')
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`

module.exports = async function getAccessToken() {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: querystring.stringify({
      grant_type: 'refresh_token',
      refresh_token,
    }),
  })

  return response.json()
}