Spotify API: Vanilla JavaScript Authorization Code Flow Login Example with PKCE
This is bare-bones code for logging into the Spotify Web API with the PKCE OAuth2 flow. It's bascially straight from the docs but rolled into a single example that also pulls the user id to verify things are working.
Note: The reason this example gets so may scopes is because they are used for the rest of the examples on the site.
Example
JavaScript: Config
const clientId = 'cd3e61bde252419da1e9b1051947a9a4'
const redirectUri = 'http://localhost:3300/pages/2zzlhz3m/'
const verify_token_key = "spotify_example_verify_token"
const access_token_key = "spotify_example_access_token"
const user_id_key = "spotify_example_user_id"
const scopes =
'user-read-private',
'user-read-email',
'user-top-read',
'user-follow-read',
'user-library-read',
'user-library-modify',
'playlist-modify-public',
'playlist-modify-private',
'playlist-read-private',
'ugc-image-upload',
'playlist-read-collaborative',
'user-read-playback-state',
'user-modify-playback-state',
'user-read-currently-playing',
'user-read-recently-played',
]
const scope = scopes.
JavaScript: Main Script
const
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const values = crypto.
return values.
}
const codeVerifier =
const
const encoder =
const data = encoder.
return window...
}
const
return
.
.
.
}
const
const hashed = await
const codeChallenge =
const authUrl =
window..
const params =
: 'code',
: clientId,
scope,
: 'S256',
: codeChallenge,
: redirectUri,
}
authUrl. = .
window.. = authUrl.
}
const
let codeVerifier = localStorage.
const payload =
: 'POST',
:
: 'application/x-www-form-urlencoded',
},
: ,
}
const url =
const body = await
const response = await body.
localStorage.
localStorage.
window.. = redirectUri
}
const
/****************************************i**
NOTE: This is a sample an only set up to
work with simple GET requests
********************************************/
const payload =
: method,
:
: `Bearer `
}
}
const body = await
const response = await body.
return response
}
const
const logoutButton = document.
logoutButton. = "log out"
logoutButton.
spotifySpace.
const user_data = await
localStorage.
spotifyId. = user_data.
}
const
localStorage.
localStorage.
}
document.
const
const loginButton = document.
loginButton. = "log in"
loginButton.
spotifySpace.
spotifyId. = "Not logged in"
}