This package contains components interacting with the Spotify API.
npm install astro-spotify
pnpm add astro-spotify
yarn add astro-spotify
To use this package, you need a Spotify Developer account. Create an app there to get a Client ID
and Client secret
.
Make sure to set the redirect URI to http://localhost:3000
. Currently, the package only uses Web API
.
Once you have your Client ID
and Client secret
, save them in your project's .env
file as:
SPOTIFY_CLIENT_ID
SPOTIFY_CLIENT_SECRET
.
To get access to your Spotify data, you need to authorize the app.
First, you'll need to get the authorization code. Open the following link in the browser, replacing:
<CLIENT_ID>
with your credentials:<SCOPE>
depending on your usage:- for <CurrentlyPlaying> Component:
user-read-currently-playing
- for <CurrentlyPlaying> Component:
You'll be promopted by Spotify to allow access to your data. Once you do it, you'll be redirected to you localhost:
http://localhost:3000/?code=<AUTHORIZATION_CODE>
Copy the code
from the URL and save it. You'll need it in the next step.
The next step is getting the refresh token. The package contains a helper function to assist you with that.
import { getRefreshToken } from "astro-spotify";
const refreshToken = await getRefreshToken(
import.meta.env.SPOTIFY_CLIENT_ID,
import.meta.env.SPOTIFY_CLIENT_SECRET,
"<AUTHORIZATION_CODE>"
);
console.log(refreshToken);
Save the token in your project's .env
file as SPOTIFY_REFRESH_TOKEN
and remove the getRefreshToken
call from your code as you won't need it anymore.
⚠️ You can only rungetRefreshToken()
once. Subsequent runs will return an error and you'd need to request a new authorization code from the previous step.
Your project's .env
file should contain following properties:
SPOTIFY_CLIENT_ID=
SPOTIFY_CLIENT_SECRET=
SPOTIFY_REFRESH_TOKEN=
If it does, you're ready to go!
⚠️ This component requires theuser-read-currently-playing
scope.
The component allows you to display the currently playing song.
import { CurrentlyPlaying } from "astro-spotify";
<CurrentlyPlaying
clientID={import.meta.env.SPOTIFY_CLIENT_ID}
clientSecret={import.meta.env.SPOTIFY_CLIENT_SECRET}
refreshToken={import.meta.env.SPOTIFY_REFRESH_TOKEN}
/>
Your website was probably rendered using SSG (Static Site Generation). This means that it was rendered once at build time and shows the state at that time.
To fix this, you need to use SSR (Server Side Rendering) either on your entire website (server
rendering mode) or at the path containing the component (hybrid
).
You can read more about it in Astro Docs.