title: nodejs express + create-react-app oauth2.0 error 401 'Invalid access token' Spotify API
body: <p>I'm trying to build an app that allows me to call Spotify's API from a <code>create-react-app</code> client through a <code>nodejs express</code> server. I'm trying to use the <a href="https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow" rel="nofollow noreferrer">Authorization Code Flow</a>.</p>
  <p>It works getting the authorization code using the following code to generate the URL, completely on client side (if and how using server-side is another question):</p>
  <pre><code>getSpotifyCodeUrl() {
    const authEndPoint = 'https://accounts.spotify.com/authorize'
    const clientId = CLIENT_ID;
    const responseType = 'code';
    const redirectUrl = 'http://localhost:3000/';
    // TODO: state for cross-site request forgery protection
    // cont state = '...';
    const scope = 'user-read-private user-read-email';
    return(
      authEndPoint +
      '?response_type=' + responseType +
      '&amp;client_id=' + clientId +
      (scope ? '&amp;scope=' + encodeURIComponent(scope) : '') +
      '&amp;redirect_uri=' + encodeURIComponent(redirectUrl)
    )
  }
  </code></pre>
  <p>The user simply clicks a link with the href as generated above.</p>
  <pre><code>{!this.state.token ? &lt;a className=&quot;btn btn--loginApp-link&quot; href={this.getSpotifyCodeUrl()}&gt;
    Login to Spotify
  &lt;/a&gt; : &quot;&quot;}
  </code></pre>
  <p>After the user gets redirected back, I use the following function to extract the authorization code from</p>
  <pre><code>componentDidMount() {
    this.setState({code: new URLSearchParams(window.location.search).get('code')});
  }
  </code></pre>
  <p>With the code I retrieve the access token. Call from client:</p>
  <pre><code>getSpotifyAccessToken() {
    fetch('/auth?code=' + this.state.code)
      .then((res) =&gt; res.json())
      .then(data =&gt; {
        this.setState({token: data.token});
        localStorage.setItem('token', this.state.token);
      });
  }
  </code></pre>
  <p>API call on server:</p>
  <pre><code>app.get(&quot;/auth&quot;, (req, res) =&gt; {
    let code = req.query.code;
    let authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        code: code,
        redirect_uri: 'http://localhost:3000/',
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (new Buffer.from(clientId + ':' + clientSecret).toString('base64'))
      },
      json: true
    };
  
    request.post(authOptions, function(error, response, body){
      if (!error &amp;&amp; response.statusCode === 200) {
        token = body.access_token;
        res.json({ token: &quot;Token: &quot; + body.access_token});
      } else { 
        console.log(&quot;/auth response body&quot;)
        console.log(body) 
      } 
    });
  });
  </code></pre>
  <p>Strange thing is I get a token, but can also see the following error in my server terminal:</p>
  <blockquote>
  <p>{
  error: 'invalid_grant',
  error_description: 'Invalid authorization code'
  }</p>
  </blockquote>
  <p>If I then try to use the token to do a (simple) request from client:\</p>
  <pre><code>getSpotifyMe() {
    fetch('/me?token=' + this.state.token)
      .then((res) =&gt; res.json())
      .then(data =&gt; {
        console.log(data);
      });
  }
  </code></pre>
  <p>And corresponding server call:</p>
  <pre><code>app.get(&quot;/me&quot;, (req, res) =&gt; {
    let token = req.query.token;
    console.log(&quot;Token: &quot; + token);
    let options = {
      url: 'https://api.spotify.com/v1/me',
      headers: { 'Authorization': 'Bearer ' + token },
      json: true
    }
  
    request.get(options, function(error, response, body) {
      console.log(&quot;/me request body&quot;);
      console.log(body);
      if (!error &amp;&amp; response.statusCode === 200) {
        res.json(body);
      } else {
      } 
    })
  })
  </code></pre>
  <p>Which gives me a 401 error:</p>
  <blockquote>
  <p>{ error: { status: 401, message: 'Invalid access token' } }</p>
  </blockquote>
  <p>I've tried some things. Doing the call from client, no success. Refreshing tokens, deleting cookies, authorizations from account, but no success. The strange thing is I can use the token said to be invalid in the <a href="https://developer.spotify.com/console/get-current-user/" rel="nofollow noreferrer">Spotify Web Console</a>, doing the exact same call I'm trying to do in the application.</p>
  <p>Do you know where I'm causing these errors (invalid_grant and 401) in my application? And how I could solve them?</p>