Skip to content

Instantly share code, notes, and snippets.

@mkriegeskorte
Created September 28, 2020 16:35
Show Gist options
  • Save mkriegeskorte/94ca9882e01bdbd69bea9b8c43cd6e88 to your computer and use it in GitHub Desktop.
Save mkriegeskorte/94ca9882e01bdbd69bea9b8c43cd6e88 to your computer and use it in GitHub Desktop.
Get recently played Spotify Track in serverless function running on vercel
const axios = require('axios')
const spotifyAPIBaseUri = 'https://api.spotify.com'
const spotifyAccountsBaseUri = 'https://accounts.spotify.com'
const {
SPOTIFY_CLIENT_ID, // Your Spotify OAuth Client ID
SPOTIFY_CLIENT_SECRET, // Spotify OAuth Client Secret
SPOTIFY_REFRESH_TOKEN, // Your personal refresh token (you have to authenticate yourself against your app once to receive this)
} = process.env
let accessToken = ''
axios.defaults.withCredentials = true
axios.defaults.headers.common['Content-Type'] = 'application/json'
const refreshAccessToken = () => {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${new Buffer.from(
`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`
).toString('base64')}`,
}
return axios
.post(
`${spotifyAccountsBaseUri}/api/token`,
`grant_type=refresh_token&refresh_token=${SPOTIFY_REFRESH_TOKEN}`,
{
headers: headers,
}
)
.then(response => {
accessToken = response.data.access_token
})
}
const getRecentlyPlayedTrack = () => {
const headers = accessToken
? {
Authorization: `Bearer ${accessToken}`,
}
: {}
return axios.get(
`${spotifyAPIBaseUri}/v1/me/player/recently-played?limit=1`,
{
headers: headers,
}
)
}
export default (req, res) => {
getRecentlyPlayedTrack()
.then(({ data }) => {
res.send(data)
})
.catch(e => {
refreshAccessToken()
.then(() => {
getRecentlyPlayed()
.then(({ data }) => {
res.send(data)
})
.catch(e => {
res.status(500).send('Failed to get recently played track')
})
})
.catch(e => {
res.status(500).send('Failed to refresh token')
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment