How to use the Spotify API In Your React JS App

In this tutorial you will learn how to use the Spotify Api in your application.

I also made a step by step video

List of contents

Create Spotify App

First, we need to create a Spotify App at Spotifys developer dashboard. For that you need to login at https://developer.spotify.com/dashboard/login.

Click on the green button "Create an App". In the Modal you need to set an app name as well as a description. Confirm the terms and hit the Create button.

You will be redirected to the spotify app overview. Here you get the Client ID which we will be needing later in our react app.

To complete this step we need to set the redirect URI. For that click on "edit settings". Under "Redirect URIs" type in http://localhost:3000 and confirm by clicking on add, then save the settings.

Now we are ready to start coding.

Setup React Application

Open your terminal and create a new react application with following command:

npx create-react-app spotify-react

This creates a complete react application. With cd spotify-react && yarn start you jump into the projects directy and start the development server which then runs at http://localhost:3000 by default.

(If for whatever reason the port is not 3000 make sure to change the redirect url in your spotify app settings.)

Authentication

To be able to use the API, the user needs to be authenticated with his Spotify Account. For that case we need to create a link which leads us to the Spotify Authentication/Login page.

This links consists of the following params:

  • Endpoint
  • Client ID
  • Redirect URI
  • Response Type

Let's start coding, open up App.js and remove all that stuff you don't need, so you app will look similiar to this:

import './App.css';

function App() {

    return (
        <div className="App">
            <header className="App-header">

            </header>
        </div>
    );
}

export default App;

Now let's add the variables which we then use for our authentication link.

(You get the CLIENT_ID from the Spotify App Overview, mentioned at the beginning.)

const CLIENT_ID = "+++++++++++++++++++++++++++++"
const REDIRECT_URI = "http://localhost:3000"
const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
const RESPONSE_TYPE = "token"

Now we can create the link in the return of our App.js which looks like this:

<a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}>Login to Spotify</a>

Let's open http//:localhost:3000 in your browser. When you click on the Login to Spotify link, you will be redirected to the Spotify Authentication page.

Either you are already logged in, than you just need to accept the terms, or you need to login with your Spotify Account credentials.

After accepting the terms you will be redirected back to the app at localhost:3000.
A hash is passed to the URL which contains the access token which we need to authorize the API calls.

Access Token

As we want to check for the token as soon as we come back, we use the useEffect from react.
Then we check the URL for the hash and extract the token by performing some tasks. After that we store the token in a state variable with help of the useState hook as well as we save the token in our localeStorage.

Import the useEffect as well as the useState hook to your application.

import {useEffect, useState} from 'react';

Now create the state variable for the token and set it to an empty string by default.

const [token, setToken] = useState("")

The useEffect function will look like this:

useEffect(() => {
    const hash = window.location.hash
    let token = window.localStorage.getItem("token")

    if (!token && hash) {
        token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]

        window.location.hash = ""
        window.localStorage.setItem("token", token)
    }

    setToken(token)

}, [])

Let me explain what happens in here:
When we open the app, we check if we have a hash or we already have a token saved in our localStorage.
If we do have a token stored, we simply continue by setting our token state variable.
If we don't have a token, we check if we have a hash. If so we perform tasks on that string to extract the token.

We substring the hash at the beginning. We split the String by the ampersands. Then we search vor that element which contains access_token. This element than again will be split at the equal sign. The array we get contains the token at index 1.

Once we got the token we save it in our localStorage and reset the hash.

Logout

To logout we simply create a function which removes the token from our localStorage as well as we set the state token back to an empty string.

const logout = () => {
    setToken("")
    window.localStorage.removeItem("token")
}

Let's add the Logout Button to our app, rendering conditionally depending on token state.

The intermediate stand of App.js should now look like this

function App() {
    const CLIENT_ID = "+++++++++++++++++++++++++++++"
    const REDIRECT_URI = "http://localhost:3000"
    const AUTH_ENDPOINT = "https://accounts.spotify.com/authorize"
    const RESPONSE_TYPE = "token"

    const [token, setToken] = useState("")

    useEffect(() => {
        const hash = window.location.hash
        let token = window.localStorage.getItem("token")

        if (!token && hash) {
            token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]

            window.location.hash = ""
            window.localStorage.setItem("token", token)
        }

        setToken(token)

    }, [])

    const logout = () => {
        setToken("")
        window.localStorage.removeItem("token")
    }

    return (
        <div className="App">
            <header className="App-header">
                <h1>Spotify React</h1>
                {!token ?
                    <a href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}`}>Login
                        to Spotify</a>
                    : <button onClick={logout}>Logout</button>}
            </header>
        </div>
    );
}

export default App;

Fetching Data

Now we are ready to start with the fun part. In this tutorial we are searching for artists and display some informations like name and their profile image. Check out the documentation for way more possibilities.

First, create two new states, one which will keep our search term, and one which will keep the fetched data.

const [searchKey, setSearchKey] = useState("")
const [artists, setArtists] = useState([])

Install axios which will handle our HTTP request with following command

yarn add axios

and import it to the app

import axios from 'axios";

Now create the searchArtists function. We use axios to perform the GET request to the spotify API endpoint. As request configuration we pass an object which contains the header with the Bearer Authorization and the token. As well as a params object containing the search term and the type of search which is here set to artist.
Once the request is done, and the fetch successful the response is set to our artists state.

const searchArtists = async (e) => {
    e.preventDefault()
    const {data} = await axios.get("https://api.spotify.com/v1/search", {
        headers: {
            Authorization: `Bearer ${token}`
        },
        params: {
            q: searchKey,
            type: "artist"
        }
    })

    setArtists(data.artists.items)
}

To perfom the search lets add the form to our app.

<form onSubmit={searchArtists}>
    <input type="text" onChange={e => setSearchKey(e.target.value)}/>
    <button type={"submit"}>Search</button>
</form>

We are almost there.

Displaying Data

The last step is to display the data in our application. For that we let's create the renderArtists function and call it inside the return of our App.js.

const renderArtists = () => {
    return artists.map(artist => (
        <div key={artist.id}>
            {artist.images.length ? <img width={"100%"} src={artist.images[0].url} alt=""/> : <div>No Image</div>}
            {artist.name}
        </div>
    ))
}
{renderArtists()}

Visit your browser at http://localhost:3000. Login with your Spotify account, enter an artists in the search field and see the data rendered in your app.

Thank's for reading! I hope you liked this article. Please leave me some feedback! :)

Step by Step Video

33