How to get spotify user access token using spotify-api.js and express.js?

How to get spotify user access token using spotify-api.js and express.js?

Get your spotify access token using spotify-api.js and express.js with less mess...

Introduction

If you don't know what is Spotify-api.js , then let me tell you it is an api wrapper to work with spotify api in a typesafe environment. You can view its documentation here.

Many developers asked me how to get the user authorized token and create a UserClient so i decided to create a guide how to do it with express and spotify-api.js.

User authorized token or User access token is a token which helps you to make api requests and access the user's account on user's behalf like getting the user's tracks, following an artist, etc.

Setting up

Obviously, you have to install the modules first.

npm init -y
npm i express spotify-api.js

Now, you have to get your spotify application's client id and client secret. Since they are credentials, its better to store them in .env file.

CLIENT_ID = "your id"
CLIENT_SECRET = "your secret"

If you don't know how to get your spotify application's client id and client secret, you can visit the Spotify Developer's Dashboard and create a new application.

For the sake of this guide, let the file structure be

node_modules/
index.js
.env
package-lock.json
package.json

Concept

First, lets understand how we are going to get the user authorized token.

  • Step 1: Hosting the server.
  • Step 2: The user visits the login page (/login).
  • Step 3: The login page would redirect the user to the spotify authorization page.
  • Step 4: The user will grant access to your application.
  • Step 5: After the user grants the access, the spotify authorization page would redirect the user to the callback page (/callback) with the code search query.
  • Step 6: In the backend, we will be using spotify-api.js to create the UserClient and getting the user authorized token.

Setting up the server

Now, lets go to index.js and setup the server using express.

const express = require('express');
const app = express(); 

app.get('/', (req, res) => res.send('Hello World'));
app.listen(3000, () => console.log('Listening on http://localhost:3000/'));

After running the script, you can see the 'Hello World' in http://localhost:3000.

Now, lets create the /login path.

const SCOPES = 'user-read-private user-read-email user-follow-modify';
const REDIRECT_URL = 'http://localhost:3000/callback';
const LOGIN_URL = `https://accounts.spotify.com/authorize?response_type=code&client_id=${process.env.CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URL)}&scope=${SCOPES}`;

app.get('/login', (req, res) => res.redirect(LOGIN_URL));
  • In the following code, http://localhost:3000/callback is used as the redirect uri so make sure you have added this redirect uri in your application dashboard. If you don't know how to add the redirect uri in you application, you can check the Official Spotify Web API Guide.
  • const SCOPES = 'user-read-private user-read-email user-follow-modify';
    
    If you are wondering what does SCOPES mean, it is a collection of authorization scopes you wanted to be allowed on user's behalf from the authorization separated by a space. You can view the different types of scopes offered by the spotify api here.

After creating the /login path, its time to create the /callback path where the spotify api will redirect after the user grants access to the api. Here, we will be using spotify-api.js to reduce our work.

const { Client } = require('spotify-api.js');

app.get('/callback', async (req, res) => {
  // Creating an user client with the authorized details.
  const client = await Client.create({
    token: {
      clientID: process.env.CLIENT_ID, // Your spotify application client id.
      clientSecret: process.env.CLIENT_SECRET, // Your spotify application client secret.
      code: req.query.code, // The code search query from the web redirect. Do not use this field if your aim is to refresh the token.
      redirectURL: REDIRECT_URL // The redirect url which you have used when redirected to the login page.
    }
  });


  // After the getting the user client, you can get the token...
  console.log(`Spotify token: ${client.token}`);
  res.send(`Hi ${client.user.displayName}!`);
});

Now, after running it, you can try to visit http://localhost:3000/login and you will see it working!

After creating the client, now you can perform use api like following artists.

await client.artists.follow('artist-id');

To follow artists, you have to use the user-follow-modify scope. To know more about scopes, visit here.

The Code

Here is the full code of the server.

const { Client } = require('spotify-api.js');
const express = require('express');
const app = express(); 

const SCOPES = 'user-read-private user-read-email user-follow-modify';
const REDIRECT_URL = 'http://localhost:3000/callback';
const LOGIN_URL = `https://accounts.spotify.com/authorize?response_type=code&client_id=${process.env.CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URL)}&scope=${SCOPES}`;

app.get('/', (req, res) => res.send('Hello World'));
app.get('/login', (req, res) => res.redirect(LOGIN_URL));

app.get('/callback', async (req, res) => {
  // Creating an user client with the authorized details.
  const client = await Client.create({
    token: {
      clientID: process.env.CLIENT_ID, // Your spotify application client id.
      clientSecret: process.env.CLIENT_SECRET, // Your spotify application client secret.
      code: req.query.code, // The code search query from the web redirect. Do not use this field if your aim is to refresh the token.
      redirectURL: REDIRECT_URL // The redirect url which you have used when redirected to the login page.
    }
  });


  // After the getting the user client, you can get the token...
  console.log(`Spotify token: ${client.token}`);
  res.send(`Hi ${client.user.displayName}!`);
});

app.listen(3000, () => console.log('Listening on http://localhost:3000/'));

Happy Coding!


Spotify-api.js: github.com/spotify-api/spotify-api.js
Spotify-api.js Documentation: spotify-api.js.org