View your live Spotify history with React and Node
You will need Node 6+ installed on your machine. Some knowledge of Node and React will be helpful.
In this tutorial, we’ll be creating an application that displays your Spotify music history in realtime. Once you connect a Spotify account, it’ll display a list of your 10 most recently played tracks. Then it’ll keep updating that list as you play more songs. The final result will look like this:
Prerequisites
Experience with building Node.js and React applications is required to grasp the concepts explored in this tutorial. You also need Node.js (v6 and later) along with npm on your machine to run the commands and code included in this article. You can find installation instructions here.
Getting started
Create a new folder for this project in your filesystem. You can call it spotify-history
or just spotify
. Open up your terminal and cd
into the newly created directory. Next, run the command below to initialize a new Node.js project:
npm init -y
The above command creates a new package.json
file in the current directory. Now let’s install the dependencies we’ll be needing to build the server component of our application.
Run the following command in the terminal to install the required packages. I’ll explain what each one does as we progress through the tutorial.
npm install express cors nedb dotenv node-cron node-fetch pusher --save
Once the server dependencies have been installed, run the command below to install create-react-app globally on your machine. This tool helps us bootstrap React apps quickly with no build configuration.
npm install -g create-react-app
Once the installation completes, you’ll have access to the create-react-app
command that will be used to set up the React project. Next, run the following command from within the root of your project directory to create the frontend component of the app.
create-react-app client
This command creates a new client
directory and installs all the packages that are needed to build and run a React application within it.
Next, change into the newly created client
directory and run the command below install some additional dependencies that we’ll be needing in our application frontend:
npm install pusher-js date-fns --save
Finally, run npm start
within the client
directory to start the development server. It should be available at http://localhost:3000 or some other port if 3000 is not available on your machine.
Create the application frontend
Let’s begin by changing up the code in client/src/App.js
to look like this:
// client/src/App.js
import React, { Component } from 'react';
import Pusher from 'pusher-js';
import format from 'date-fns/format';
import './App.css';
class App extends Component {
constructor() {
super();
const urlParams = new URLSearchParams(window.location.search);
const isUserAuthorized = urlParams.has('authorized') ? true : false;
this.state = {
isUserAuthorized,
musicHistory: [],
};
}
render() {
const { isUserAuthorized, musicHistory } = this.state;
const connectSpotify = isUserAuthorized ? (
''
) : (
<a href="http://localhost:5000/login">Connect your Spotify account</a>
);
const TableItem = (item, index) => (
<tr key={item.played_at}>
<td>{index + 1}</td>
<td>{item.track_name}</td>
<td>{format(item.played_at, 'D MMM YYYY, hh:mma')}</td>
</tr>
);
const RecentlyPlayed = () => (
<div className="recently-played">
<h2>Recent Tracks</h2>
<table className="table">
<thead>
<tr>
<th>#</th>
<th>Song title</th>
<th>Time</th>
</tr>
</thead>
<tbody>{musicHistory.map((e, index) => TableItem(e, index))}</tbody>
</table>
</div>
);
return (
<div className="App">
<header className="header">
<h1>Spotify Listening History</h1>
<p>View your music history in realtime with Spotify and Pusher</p>
{connectSpotify}
{musicHistory.length !== 0 ? <RecentlyPlayed /> : null}
</header>
</div>
);
}
}
export default App;
We’ve initialized the state of the application with two values: isUserAuthorized
which keeps track of whether the user has authenticated with Spotify or not via a URL parameter, and musicHistory
which is where all the recently played tracks will be stored. If isUserAuthorized
is set to false (which it is by default), a link that prompts the user to connect a Spotify account to the app will be displayed on the screen.
Let’s change up the styles for the app in client/src/App.css
:
// client/src/App.css
.App {
width: 100%;
max-width: 750px;
margin: 0 auto;
padding: 30px;
text-align: center;
}
table {
width: 100%;
text-align: center;
}
th,
td {
padding: 12px 15px;
border-bottom: 1px solid #E1E1E1; }
th:first-child,
td:first-child {
padding-left: 0; }
th:last-child,
td:last-child {
padding-right: 0; }
Set up the server
In the root of your project directory, create a new server.js
file and change its contents to look like this:
// server.js
require('dotenv').config({ path: 'variables.env' });
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const Datastore = require('nedb');
const cron = require('node-cron');
const Pusher = require('pusher');
const clientUrl = process.env.CLIENT_URL;
const app = express();
const db = new Datastore();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 5000);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
Next, create a file called variables.env
also in the root of your project folder. This is where all the environmental variables will be stored so that they can be made available on process.env
. The dotenv
package is what allows us to achieve this.
// variables.env
PORT=5000
CLIENT_URL=https://localhost:3000
The CLIENT_URL
variable is the URL where the React development server is available on. You can change the value if your app is running on another port.
Sign up for Spotify
Before you can access and use Spotify’s API, you need to create a free account. You don’t need to be on the premium plan to follow through with this tutorial. Once you have done so, go to the developer dashboard and log in to with your Spotify account. Accept the terms of service and create your first app by selecting any one of the three options presented.
Fill the popup form as shown above and hit Next to move along. Hit No on the Are you developing a commercial integration? screen and tick all the checkboxes on the final screen before hitting the green SUBMIT button to create the app.
Once your app has been created, you will be redirected to the app page where you can access your Client ID and Client Secret tokens. You will find this at the top left of your screen. Also hit the EDIT SETTINGS button at the top right and add the redirect URI (http://localhost:5000/callback) in the popup form that appears, then hit the ADD button. Finally hit SAVE at the bottom of the form to save your settings.
Add the following variables to your variable.env
file:
// variables.env
SPOTIFY_CLIENT_ID=<your spotify client id>
SPOTIFY_CLIENT_SECRET=<your spotify client secret>
SPOTIFY_REDIRECT_URI=http://localhost:5000/callback
Next, create new credentials.js
file in your project directory and change its contents to look like this:
// credentials.js
const spotify = {
client_id: process.env.SPOTIFY_CLIENT_ID,
client_secret: process.env.SPOTIFY_CLIENT_SECRET,
redirect_uri: process.env.SPOTIFY_REDIRECT_URI,
};
module.exports = spotify;
Create the authentication flow
We need to create a flow for authorizing users’ Spotify accounts to work with our app. We can do this by creating the login route in the server, which is where the user hits the Connect your Spotify account link is clicked on the app frontend.
Create a new file called authorizeSpotify.js
and paste in the following code within it:
// authorizeSpotify.js
const spotify = require('./credentials');
const authorizeSpotify = (req, res) => {
const scopes = 'user-read-recently-played';
const url = `https://accounts.spotify.com/authorize?&client_id=${
spotify.client_id
}&redirect_uri=${encodeURI(
spotify.redirect_uri
)}&response_type=code&scope=${scopes}`;
res.redirect(url);
};
module.exports = authorizeSpotify;
Next import this module into server.js
and use it in the a new /login
route as shown below:
// server.js
...
const Pusher = require('pusher');
const authorizeSpotify = require('./authorizeSpotify');
...
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/login', authorizeSpotify);
...
Whenever, the user hits the /login
route (by trying to connect a Spotify account), the app generates a request where the user is prompted to grant the user-read-recently-played
permission.
When the user grants the permission, it will redirect back to the redirect URL you specified while creating the app (http://localhost:5000/callback). We need to grab the code that is included in the URL parameters and exchange it for an access token which will be used when interacting with the Spotify API. Let’s write the code that’ll do just that in the next step.
Create a new file called getAccessToken.js
and paste the following code inside it:
// getAccessToken.js
const fetch = require('node-fetch');
const spotify = require('./credentials');
const getAccessToken = (req, res, next) => {
const { code } = req.query;
if (code) {
const url = 'https://accounts.spotify.com/api/token';
const data = {
grant_type: 'authorization_code',
code,
redirect_uri: spotify.redirect_uri,
client_id: spotify.client_id,
client_secret: spotify.client_secret,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
};
const searchParams = new URLSearchParams();
Object.keys(data).forEach(prop => {
searchParams.set(prop, data[prop]);
});
fetch(url, {
method: 'POST',
headers,
body: searchParams,
})
.then(res => res.json())
.then(credentials => {
req.credentials = credentials;
next();
})
.catch(next);
}
};
module.exports = getAccessToken;
Next, require getAccessToken
in server.js
and use it in the /callback
route as shown below:
// server.js
...
const authorizeSpotify = require('./authorizeSpotify');
const getAccessToken = require('./getAccessToken');
...
app.get('/login', authorizeSpotify);
app.get('/callback', getAccessToken);
...
In getAccessToken
, we grab the code off the URL parameters and exchange it for an access token by making a POST request to the Spotify Accounts service. When the requested credentials are received, they’re saved on the req
object and next()
is invoked which executes the next middleware.
Let’s go ahead and create the succeeding middleware in the next step. This middleware is tasked with saving the credentials received from Spotify to a temporary database. Here’s the code that helps us achieve that:
// server.js
...
app.get('/login', authorizeSpotify);
app.get('/callback', getAccessToken, (req, res, next) => {
db.insert(req.credentials, err => {
if (err) {
next(err);
} else {
res.redirect(`${clientUrl}/?authorized=true`);
}
});
});
This code allows us to redirect the user back to the app frontend once the credentials have been saved to the database. Notice the ?authorized=true
parameter? That presence of that in the URL lets us detect that authorization was successful and isUserAuthorized
will now be set to true
in the app frontend.
Fetch the user’s recently played tracks
Now that we know that authorization with the Spotify API was successful, we need to fetch the 10 most recently played tracks of the user and display it on the page. At this point, you should start listening to some music on Spotify if your account is new so that some songs will show up when this request is performed.
Under the constructor()
function, add the componentDidMount()
lifecycle hook to your React app and paste the following code within it:
// client/src/App.js
componentDidMount() {
const { isUserAuthorized } = this.state;
if (isUserAuthorized) {
fetch('http://localhost:5000/history')
.then(res => res.json())
.then(data => {
this.setState({
musicHistory: data,
});
})
.catch(error => console.log(error));
}
}
We’re making a request to the /history
route and we expect the 10 most recently played songs on the users’ account to be sent back. Let’s create this route on the server in the next step.
Create a file called getRecentlyPlayed
and paste the code below within it. This is where the actual request to Spotify is performed.
// getRecentlyPlayed.js
const fetch = require('node-fetch');
const getRecentlyPlayed = accessToken => {
const url = 'https://api.spotify.com/v1/me/player/recently-played?limit=10';
return fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
})
.then(res => res.json())
.then(data => data.items)
.catch(error => console.log(error));
};
module.exports = getRecentlyPlayed;
Next, import it in server.js
and add the /history
route below the other two:
// server.js
...
const getAccessToken = require('./getAccessToken');
const getRecentlyPlayed = require('./getRecentlyPlayed');
...
app.get('/history', (req, res) => {
db.find({}, (err, docs) => {
if (err) {
throw Error('Failed to retrieve documents');
}
const accessToken = docs[0].access_token;
getRecentlyPlayed(accessToken)
.then(data => {
const arr = data.map(e => ({
played_at: e.played_at,
track_name: e.track.name,
}));
res.json(arr);
})
.catch(err => console.log(err));
});
});
At this point, if the user is authenticated and this route is hit, the most recently played songs will be sent to the frontend and displayed on the page.
Set up realtime updates with Pusher
The next task is to make the list of songs update on the page as you continue to listen. Head over to the Pusher website and sign up for a free account. Select Channels apps on the sidebar, and hit Create Channels app to create a new app. Once your app is created, retrieve your credentials from the API Keys tab, then add the following to your variables.env
file.
// variables.env
PUSHER_APP_ID=<your app id>
PUSHER_APP_KEY=<your app key>
PUSHER_APP_SECRET=<your app secret>
PUSHER_APP_CLUSTER=<your app cluster>
We’re going to set up a cron job to run every five minutes, retrieve the most recently played songs and merge it with the existing list of recent tracks so that new songs are displayed on top. Change up server.js
to look like this:
// server.js
....
const db = new Datastore();
const pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER,
encrypted: true,
});
...
app.get('/history', (req, res) => {
db.find({}, (err, docs) => {
if (err) {
throw Error('Failed to retrieve documents');
}
const accessToken = docs[0].access_token;
getRecentlyPlayed(accessToken)
.then(data => {
const arr = data.map(e => ({
played_at: e.played_at,
track_name: e.track.name,
}));
res.json(arr);
})
.then(() => {
cron.schedule('*/5 * * * *', () => {
getRecentlyPlayed(accessToken).then(data => {
const arr = data.map(e => ({
played_at: e.played_at,
track_name: e.track.name,
}));
pusher.trigger('spotify', 'update-history', {
musicHistory: arr,
});
});
});
})
.catch(err => console.log(err));
});
});
Once the initial listing is made, a cron job is triggered that runs every five minutes. That’s what the */5 * * * *
string signifies. The user’s most recently played tracks are fetched and pushed to the spotify
channel via the update-history
event. Any client that is subscribed to this channel can receive the latest data and update the list of tracks on the page.
Let’s go ahead and do just that in the frontend of our app. Update the componentDidMount()
lifecycle hook in client/src/App.js
to look like this:
// client/src/App.js
componentDidMount() {
const { isUserAuthorized } = this.state;
if (isUserAuthorized) {
fetch('http://localhost:5000/history')
.then(res => res.json())
.then(data => {
this.setState({
musicHistory: data,
});
})
.catch(error => console.log(error));
const pusher = new Pusher('<your app key>', {
cluster: '<your app cluster>',
encrypted: true,
});
const channel = pusher.subscribe('spotify');
channel.bind('update-history', data => {
this.setState(prevState => {
const arr = data.musicHistory
.map(item => {
const isPresent = prevState.musicHistory.find(
e => e.played_at === item.played_at
);
if (isPresent === undefined) {
return item;
} else {
return null;
}
})
.filter(Boolean);
return {
musicHistory: arr.concat(prevState.musicHistory),
};
});
});
}
}
Here, we opened a connection to Channels and used the subscribe()
method to subscribe to the spotify
channel. Updates to the user’s music history are listened for via the bind
method. Once an update is received, the data is merged with the existing one so that the list is updated with the latest tracks.
Don’t forget to replace the <your app key>
and <your app cluster>
placeholders with the appropriate details from your Pusher account dashboard.
Start your server by running node server.js
and link your Spotify account on the frontend. As long as you continue to play music, you should see the page update with your most recent tracks updates.
Conclusion
That’s it! In this tutorial, you learned how to view your Spotify music history in realtime with React and Pusher. Along the way, you learned how to use Spotify’s API, and Pusher Channels to send and receive data in realtime.
You can find the app’s source code in this GitHub repo.
14 November 2018
by Ayooluwa Isaiah