How to use the Spotify API In Your React JS App
Tags: spotify, react, tutorial
Published: 2021-12-17 11:14:02

---
title: How to use the Spotify API In Your React JS App
published: true
description: 
tags: spotify, react, tutorial,
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zr2726xa6vw4fomjrczl.png
---

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

If you have any questions [hit me up von Twitter](https://twitter.com/Dom_TheDev)

GitHub Files: https://github.com/dom-the-dev/spotify-with-react

> [Subscribe to my YouTube Channel](https://www.youtube.com/channel/UCAa2t4QIxlaUuPO2FKq5TDw?sub_confirmation=1)


I also made a step by step [video](#video)

#### List of contents
- [Create Spotify App](#create-spotify)
- [Setup React Application](#setup-react)
- [Authentication](#authentication)
- [Access Token](#token)
- [Logout](#logout)
- [Fetching Data](#fetch-data)
- [Displaying Data](#display-data)


### Create Spotify App <a name="create-spotify"></a>

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 <a name="setup-react"></a>

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

```CLI 
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 <a name="authentication"></a>

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:

```react
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.)

```react
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: 

```react
 <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 <a name="token"></a>

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.

```react
import {useEffect, useState} from 'react';
``` 

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

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

The useEffect function will look like this: 

```react
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 <a name="#logout"></a>

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.

```react
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

```react

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 <a name="fetch-data"></a>

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](https://developer.spotify.com/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.

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

Install `axios` which will handle our HTTP request with following command

```cli
yarn add axios
```

and import it to the app

```react
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.

```react
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.

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

We are almost there.

### Displaying Data <a name="display-data"></a>

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`.

```react
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>
    ))
}
```

```react
{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 <a name="video"></a>

{% youtube wBq3HCvYfUg %}