Jamming Project - Get API token

I’m super stuck on the retrieving the API token from the spotify API.

let token

const getAccessToken = async() => {
    const clientId = ""
    const clientSecret = ""

    const response = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        body: 'grant_type=client_credentials&client_id=' + clientId + '&client_secret=' + clientSecret,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
    try {
        if (response.ok) {
            const fulfilledValue = await response.json();
    catch (error) {
        throw (error)


I’m only able to console.log the token, but I can’t figure out how to assign the token to a variable outside of my async function.

I’m in desperate need for help, it’s driving me crazy for hours…

Hey - are you trying to implement the Implicit Grant method?

You shouldn’t need to fetch anything here. The token is included in the URL when the user grants access and returns to your app.

The getAccessToken() function can check for the token with a regex like so (I did this project using the old video tutorial, so it may look different than what you have. The Spotify component has helper functions for authorization, serach and saving playlists.)

let accessToken;

const Spotify = {
  getAccessToken() {
    if (accessToken) {
      return accessToken;

    // check for an access token
    const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
    const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);

    if (accessTokenMatch && expiresInMatch) {
      accessToken = accessTokenMatch[1];
      const expiresIn = Number(expiresInMatch[1]);
      // This clears the token & expiry so we can get a new token when it expires
      window.setTimeout(() => (accessToken = ""), expiresIn * 1000);
      window.history.pushState("Access Token", null, "/");
      return accessToken;



Thank you for the hint on using the implicit grant. I’m going to implement it :slight_smile:

1 Like