Spotify Now Playing on your website ?

This is inspired by Lee Robinson, go check him out, he does a lot of super cool things!

You can see this working here on the bottom of the page

Like the summary says: This is a blog post about how to set up to make a component on your website which s…


This content originally appeared on DEV Community and was authored by Einar Guðni Guðjónsson

This is inspired by Lee Robinson, go check him out, he does a lot of super cool things!

You can see this working here on the bottom of the page

Like the summary says: This is a blog post about how to set up to make a component on your website which showcases what you are listening to on Spotify, at any given moment.

So before we can start to write some code, we have to do some preparation so that the Spotify API will work with us.

Please do take into account that you could do the first steps in the same way I showcase here, but after that, it will depend on how your website is built on how you can showcase this on your website. My page is built with Next.js and TailwindCSS and hosted on Vercel.

Spotify

There are three steps that we need to do for this to work. Here you will see these three steps. Below we will go and do these three steps.

  1. Create Spotify Application
  2. Authentication
  3. Environmental Variables

Create Spotify Application

The first step is to create a Spotify application so we can get credentials to authenticate and then use the API.

  • Log in to you Spotify Developer Dashboard
  • Create an App
  • Add name and description to their fields and click create.
  • Show Client Secret
    • We have to get this secret and use it later!
  • Copy your Client ID and Secret and paste for use later on in the process.
  • Edit your settings
  • Add http://localhost:3000 as a redirect URL
    • What is a redirect URL?

This step is done!
Now Spotify is configured and you are authorized to make requests.

Authenitcation

There are many ways to authenticate with the Spotify API, it will depend on your use case what is the most feasible solution.
For us, we will use the Authorization Code Flow, since we only need the permission granted once.

We will have our application request the authorization by logging into the scope we need. Here is an example of what the URL might look like. Swap out the client_id and scope for your own.

https://accounts.spotify.com/authorize?client_id=f42ae57ec93142b0b4017936f75fa65e&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:3000&scope=user-read-currently-playing%20user-top-read

Since we only need to authenticate once, we will be redirected to our redirect_uri we added in the step above.
In the URL, there will be a code query parameter, save that value.

http://localhost:3000/?code=AQA7...FyBs

Next, we will need to retrieve the refresh token. To do that we will have to generate a Base 64 encoded string containing the client_id and secret from the first step. You can use this tool for example, to encode it online. The format should be client_id:client_secret.

curl -H "Authorization: Basic <base64 encoded client_id:client_secret>"
-d grant_type=authorization_code -d code=<code> -d redirect_uri=http%3A
%2F%2Flocalhost:3000 https://accounts.spotify.com/api/token

This will return a JSON response that contains the refresh_token we needed. This token is valid indefinitetly unless you revoke access, so we'll want to save this in an environment variable. This refresh_token being valid indefinitely is one part of why we only need to authenticate once.

Add Environmental Variables

To securely access the API we need to include the secret with each request. But we don't want to showcase our secrets in public, and not on GitHub either. Thus, we should use environment variable.
You can do this in a few ways, but since I use Next.js and vercel I used this to help me to store my environment variables in a correct way.

Code

Here we will go over the two files needed to access the data from the Spotify API. Like I mentioned above, I will not go more into detail on how to make it visible on your site, which will differentiate from the framework your site is built with. However, I'm sure you can figure out how to display the data yourself. ?

spotify.js

import fetch from 'isomorphic-fetch'
import querystring from 'querystring'


// We access our values with enviroment variables,
// we don't want to share these values in our code
const client_id = process.env.SPOTIFY_CLIENT_ID
const client_secret = process.env.SPOTIFY_CLIENT_SECRET
const refresh_token = process.env.SPOTIFY_REFRESH_TOKEN

// We encode our client_id and client_secret again to send with the POST request.
// This is a part of the authorization header
const basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64')
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`

// This function gets the access token so that we can access the API

const getAccessToken = async () => {
  const response = await fetch(TOKEN_ENDPOINT, {
  method: 'POST',
   headers: {
    Authorization: `Basic ${basic}`,
    'Content-Type': 'application/x-www-form-urlencoded',
   },
   body: querystring.stringify({
    grant_type: 'refresh_token',
    refresh_token,
   }),
  })
  return response.json()
}

// We use the afformentioned access token and send it with the request to the API
// this requests gets the currently playing song.
export const getNowPlaying = async () => {
 const { access_token } = await getAccessToken()
 return fetch(NOW_PLAYING_ENDPOINT, {
  headers: {
   Authorization: `Bearer ${access_token}`,
  },
 })
}

now-playing.js

import { getNowPlaying } from '@/lib/spotify'

export default async function handler(_, res) {
  const response = await getNowPlaying()

 // Here we handle the request from the API
 if (response.status === 204 || response.status > 400) {
   return res.status(200).json({ isPlaying: false })
 }

 const song = await response.json()

 if (song.item === null) {
   return res.status(200).json({ isPlaying: false })
 }

 const isPlaying = song.is_playing
 const title = song.item.name
 const artist = song.item.artists.map((_artist) => _artist.name).join(', ')
 const album = song.item.album.name
 const albumImageUrl = song.item.album.images[0].url
 const songUrl = song.item.external_urls.spotify

 res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=30')

 // We return an obejct containing the information about the currently playing song
 return res.status(200).json({
   album,
   albumImageUrl,
   artist,
   isPlaying,
   songUrl,
   title,
 })
}

Conclusion

So to summarize!

These three main steps are required so you can get access to the Spotify API.
You can then use the API to display what you are listening to on your website.

  • First Create the application on the Spotify Developer website
  • Get the Authentication set up and working
    • This is important so the requests will work
  • Set up Environment Variables

You can use the Spotify API to do many other things, for example, show your most played songs!

But these steps are important so you can get access to the API and use it in your projects.

You can see this component on the bottom of my webpage, above the footer
Either there is a song playing or Not playing.


This content originally appeared on DEV Community and was authored by Einar Guðni Guðjónsson


Print Share Comment Cite Upload Translate Updates
APA

Einar Guðni Guðjónsson | Sciencx (2021-07-28T15:51:07+00:00) Spotify Now Playing on your website ?. Retrieved from https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/

MLA
" » Spotify Now Playing on your website ?." Einar Guðni Guðjónsson | Sciencx - Wednesday July 28, 2021, https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/
HARVARD
Einar Guðni Guðjónsson | Sciencx Wednesday July 28, 2021 » Spotify Now Playing on your website ?., viewed ,<https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/>
VANCOUVER
Einar Guðni Guðjónsson | Sciencx - » Spotify Now Playing on your website ?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/
CHICAGO
" » Spotify Now Playing on your website ?." Einar Guðni Guðjónsson | Sciencx - Accessed . https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/
IEEE
" » Spotify Now Playing on your website ?." Einar Guðni Guðjónsson | Sciencx [Online]. Available: https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/. [Accessed: ]
rf:citation
» Spotify Now Playing on your website ? | Einar Guðni Guðjónsson | Sciencx | https://www.scien.cx/2021/07/28/spotify-now-playing-on-your-website-%f0%9f%8e%bc/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.