/**/

How To Get Spotify Refresh Token

mhrsntrk

mhrsntrk / December 23, 2020

Lee Robinson made a fantastic job for creating this fantastic frontend code made with Next.js and Tailwind CSS. He also made some great integrations with Github, Youtube, Spotify using their APIs. When I try to edit his frontend I really like the Spotify Now Playing add-on on the footer. So, I decided to keep it.

You can access my source code of my website on Github how to use it. I will try to explain how to get a Refresh Token for using this API.

Create an Application

First, we need to create a Spotify application to give us credentials to authenticate with the API.

  • Go to your Spotify Developer Dashboard and log in.
  • Click Create an App.
  • Fill out the name and description and click create.
  • Click Show Client Secret.
  • Save your Client ID and Client Secret.
  • Click Edit Settings.
  • Add http://localhost:3000 as a redirect URI.

All done! You now have a properly configured Spotify application and the correct credentials to make requests.

Authentication

We will only need permission granted once therefore we can use below method.

https://accounts.spotify.com/authorize?client_id=<client_id>&response_type=code&redirect_uri=http://localhost:3000&scope=user-read-currently-playing%20user-top-read

You need to <client_id> copy your Client ID here. Please remove the <> arrows.

After authorizing, you'll be redirected back to your redirect_uri. In the URL, there's a code query parameter. Save this value.

http://localhost:3000/callback?code=<your code will be displayed here>

Next, we'll need to get the refresh token. You'll need to generate a Base 64 encoded string containing the client ID and secret from earlier. You can use this tool to encode it online. The format should be client_id:client_secret.

You can use this online tool to send curl request below. You should copy <base64 encoded client_id:client_secret> and <code> of you created earlier. Please remove the <> arrows.

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

This will return a JSON response containing a refresh_token. This token is valid indefinitely unless you revoke access, you can copy and paste it to your .env file.

You can find my other post about how to using this API to show currently playing song on Spotify to Next.js website.