'Error when using Spotify access token with API through Firebase callable cloud function

I've been working on this for a while now and feel like I've read everything I can find but still can't get it to work. I'm trying to build a Firebase callable cloud function that uses axios to get a Spotify access token through client credentials auth flow and then uses that token to get data from my own account from the Spotify API. I'm using a chained function starting with axios.post and then axios.get.

The code works when it's getting the access token through axios.post but as soon as I chain an axios.get to use the token with the API something goes wrong. I'm new to Firebase and node.js so am not sure exactly how to catch the errors properly. The most common error is either a null result or a 'Unhandled error RangeError: Maximum call stack size exceeded' in the Firebase log... can't work out what either actually means for my code... With this particular version of my code I get a null result and a mass of around 50 different error logs in Firebase.

I've tried splitting the functions, using async and await and different arrangements of the headers but not a lot really changes. I've found similar questions but nothing that seemed to solve the issue. Any help would be amazing!

const functions = require("firebase-functions");
const axios = require('axios');
const qs = require('qs');    

exports.spot = functions.https.onCall( async (data, context) => {
  const client_id = //REMOVED;
  const client_secret = //REMOVED;
  const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');
  const token_url = 'https://accounts.spotify.com/api/token';
  const stringify_data = qs.stringify({'grant_type':'client_credentials'});
  const api_url = 'https://api.spotify.com/v1/recommendations'

  return axios
  .post(token_url, stringify_data, {
    headers: {
      'Authorization': `Basic ${auth_token}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    form: {
      grant_type: 'client_credentials'
    },
    json: true
  })
  .then(result => {
    return axios.get(api_url, {
      headers: {
        'Authorization': `Bearer ${result.data.access_token}`,
      }
    })
  })
  .then(result => {
    return result
  })
  .catch(error => {
    console.log(error);
  })
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source