Published on
🍵 3 min read

How to Get a Client Credential Token from Spotify Using Node.js?

Authors

Photo

Overview

How to Get a Client Credential Token from Spotify Using Node.js

Spotify has a web API that we can use in our applications. In this article, I will show you how to use the Spotify REST API and make requests to some endpoints. You can check the API reference here.

In this article, I will provide a demo using Node.js, but you could use any other framework because the logic is simple. We will first get the token from the Spotify API and then store that token to access other endpoints that Spotify provides. The reason I chose Node.js is that it is simple to install and set up. I will use this article as a reference for the next project that I will create using Next.js.

In addition to Node.js, Express will be used for routing, and dotenv will be used for environment variable management.

Basic Setup for Node.js

Take the Following Steps to Create the Basic Structure for a Node.js API:

  1. Create the Node.js project by typing the following command:

    npm init
    
  2. Install Express.js:

    npm install express
    
  3. Create an index.js file and copy and paste the following "Hello World" example into it:

    const express = require('express')
    const app = express()
    const port = 3000
    
    app.get('/list', (req, res) => {
      res.send('Hello World!')
    })
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`)
    })
    

We created an Express.js application that has one endpoint called list. If we run this application by typing the following command:

node index.js

We should see the following output:

![Output Screenshot](Screen Shot 2022-06-21 at 22.03.22.png)

If we go to the /list endpoint, we should see the "Hello World!" output on the screen like this:

![List Endpoint Screenshot](Screen Shot 2022-06-21 at 22.10.07.png)

Now we have created the basic setup for our Node.js application. Let's install the dotenv package and create a .env file. The .env file will be where we store the client ID and client secret values.

  • Install the dotenv package:

    yarn add dotenv
    
  • Create a .env file and type your client ID and client secret values that you get from the Spotify dashboard:

    SPOTIFY_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxx
    SPOTIFY_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxx
    

To get an access token from Spotify, we will send a request to the /api/token endpoint with the client_id and client_secret values.

app.post('/token', async (req, res) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With')

  var client_id = process.env.SPOTIFY_CLIENT_ID
  var client_secret = process.env.SPOTIFY_CLIENT_SECRET

  var authOptions = {
    url: 'https://accounts.spotify.com/api/token',
    headers: {
      Authorization: 'Basic ' + new Buffer(client_id + ':' + client_secret).toString('base64'),
    },
    form: {
      grant_type: 'client_credentials',
    },
    json: true,
  }

  request.post(authOptions, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      res.json({ token: body.access_token })
    }
  })
})

If we test this endpoint, we should see a token in the response.

Example response:

{
  "token": "BQDcG6MJ8DddSLyH5f-XvWjM9BB6pmnUEehZI3a7q3-jyGqfMXgwUQMG85-KcZAS2jm0ebfyDBs6BiJ78Hui_qUPhEd_NVQfnUsVeDXebzIbtnFslRQ"
}

We can use that token to access other endpoints.

References: