Readme

getSpotifyAccess Token

Request an access token for use with the Spotify Web API.

Requires environment variables from your Spotify Developers account.

  • SPOTIFY_CLIENT_ID
  • SPOTIFY_CLIENT_SECRET

Uses Blob storage to cache the spotify_accessToken based on when the expires_in value in the Spotify Access Token response.

Example

import { getSpotifyAccessToken } from "https://esm.town/v/dthyresson/getSpotifyAccessToken"; const accessToken = await getSpotifyAccessToken(); console.debug(accessToken)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { blob } from "https://esm.town/v/std/blob";
export type SpotifyAccessToken = {
access_token: string;
token_type: string;
expires_in: number;
expires_at: number;
};
export async function getSpotifyAccessToken(): Promise<SpotifyAccessToken> {
const KEY = "spotify_accessToken";
const clientId = Deno.env.get("SPOTIFY_CLIENT_ID");
const clientSecret = Deno.env.get("SPOTIFY_CLIENT_SECRET");
if (!clientId || !clientSecret) {
throw Error("A SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET is required.");
}
let spotifyAccessToken = await blob.getJSON(KEY) as SpotifyAccessToken;
if (spotifyAccessToken) {
console.debug(spotifyAccessToken);
console.debug("Now", Date.now());
if (spotifyAccessToken.expires_at) {
const hasExpired = Date.now() > spotifyAccessToken.expires_at;
console.debug("Has access token expired?", hasExpired, Date.now() - spotifyAccessToken.expires_at);
if (!hasExpired) {
console.debug("Returned Spotify Access token from cache", spotifyAccessToken);
return { ...spotifyAccessToken, expires_at: Date.now() + spotifyAccessToken.expires_in * 1000 };
}
}
else {
console.debug("Spotify Access token expired", spotifyAccessToken);
}
}
try {
// Get access token
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`,
});
if (response.status === 200) {
const accessTokenResponse = await response.json();
const accessToken = { ...accessTokenResponse, expires_at: Date.now() + accessTokenResponse.expires_in * 1000 };
console.debug("accessToken", accessToken);
await blob.delete(KEY);
await blob.setJSON(KEY, accessToken);
return accessToken;
}
} catch (e) {
console.error("Unable to request Spotify Access Token", e);
throw Error("Unable to request Spotify Access Token");
}
}
// await getSpotifyAccessToken();
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 26, 2024