Skip to content

Instantly share code, notes, and snippets.

@xxiz
Last active December 25, 2022 01:33
Show Gist options
  • Save xxiz/1f694348fc15ca0b063a4826ef4a897f to your computer and use it in GitHub Desktop.
Save xxiz/1f694348fc15ca0b063a4826ef4a897f to your computer and use it in GitHub Desktop.
using oauth with spotify.com
const client_id = process.env.SPOTIFY_CLIENT_ID
const client_secret = process.env.SPOTIFY_CLIENT_SECRET
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN
const basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64')
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`
const TOP_TRACKS_ENDPOINT = `https://api.spotify.com/v1/me/top/tracks`
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`
async function getAccessToken() {
const response = await fetch(TOKEN_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Basic ${basic}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=refresh_token&refresh_token=${refresh_token}`,
})
return response.json()
}
async function getNowPlaying() {
const { access_token } = await getAccessToken()
return fetch(NOW_PLAYING_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`,
},
})
}
async function getTopTracks() {
const { access_token } = await getAccessToken()
return fetch(TOP_TRACKS_ENDPOINT, {
headers: {
Authorization: `Bearer ${access_token}`,
},
})
}
export { getNowPlaying, getTopTracks }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment