Search code examples
javascriptreactjsspotify

How do I store my Spotify access_token local so I can access it in different Javascript files


Hi Im relatively new to coding with Javascript, and Im trying to work out how I can access Spotify API's access_token within different javascript files. Im running two local server, one React and the other in node. The React server has a button that allows the user to login with Spotify's Oauth in the node server and then the access token and refresh token are redirect successfully back to the react server. The OAuth works quite well as I got it from the Spotify API guide they provide. The way I set up these files is that in my main project I have a auther-server older which includes the Spotify OAuth files and a client folder which is where i create my React app in. Here is where i got the OAuth files( https://github.com/spotify/web-api-auth-examples ). The only things changed in these files was in the app.js found in authorization_code folder where I entered my client and secret id with the correct redirect url, and I also did:

res.redirect('http://localhost:3000/#' +
      querystring.stringify({
        access_token: access_token,
        refresh_token: refresh_token
      }));
  } else {
    res.redirect('/#' +
      querystring.stringify({
        error: 'invalid_token'
      }));

where I made the redirect link go to http://localhost:3000/# with the tokens which is my React app is. From there I go to my React directory and in the App.js file I follow a guide i found on youtube which helps me get what the user is now playing ( https://www.youtube.com/watch?v=prayNyuN3w0&t=1496s). Here is the code:

import React, { Component, useEffect } from "react";
import "./App.css";
import Spotify from 'spotify-web-api-js';


const spotifyWebApi = new Spotify();
class App extends Component {
  constructor() {
    super();
    const params = this.getHashParams();
    this.state ={
      loggedIn: params.access_token ? true : false,
      nowPlaying: {
        name: 'Not Checked',
        image: '',
      } 
    }
    if (params.access_token){
      spotifyWebApi.setAccessToken(params.access_token)
    }
  }
  getHashParams() {
    var hashParams = {};
    var e,
      r = /([^&;=]+)=?([^&;]*)/g,
      q = window.location.hash.substring(1);
    while ((e = r.exec(q))) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
    }
    return hashParams;
  }
  getNowPlaying(){
    spotifyWebApi.getMyCurrentPlaybackState()
      .then((response) => {
      this.setState({
          nowPlaying:{
            name: response.item.name,
            image: response.item.album.images[0].url
          }
        })
      })   
  } 
  render() {
    return (
      <div className="App">
        <a href="http://localhost:8888">
          <button>Login With Spotify</button>
        </a>
        <div>Now Playing: {this.state.nowPlaying.name}</div>
        <div>
          <img src={ this.state.nowPlaying.image } style={{width: 100}}/>
        </div>
        <button onClick={() => this.getNowPlaying()}>Check Now Playing</button>
        <br></br>
      </div>
    );
  }
}
export default App;

This all works nicely, but Im trying to now access the user's data( playlists) so I can later make new recommendations using Naive Bayes and KNN classifiers, but Ill tackled that after I get over this bit first. Ive looked up ways of storing the tokens and found localStorage.set(token....) to store it in the browser but I havent had success with it as I am confused on where to set this in my code. I think its also worth to note im using the spotify web api js libary, https://github.com/jmperez/spotify-web-api-js . Im guessing that i would make a similar function in the class App like the getNowPlaying() to get the playlists, but I keep getting lost. This is my first question on here, and I probably didnt do a good job of explaining my issue here, but i hope i can find some help on here. Thanks and let me know if I need to provide any more information. :)


Solution

  • You are probably on a good lead to do what you want with localStorage.set.

    It is globally accessible. You can to the localStorage.set from wherever you retrieve the token to store it. Then you will be able to do the localStorage.get from wherever you are in your app.

    Using the localStorage is a good idea because it will help you keep this token between page refresh. You might want to remove it from localStorage at some point though for security purpose if someone might have access to the machine you use.

    Another way if you do not want to use the localStorage is setting it on a separate JavaScript file that you would import wherever you might want to use it.

    You can even look for store principles if you want to make that data centralization a step further.