const clientId = "your_client_id";
const params = new URLSearchParams(window.location.search);
const code = params.get("code");
if (!code) {
redirectToAuthCodeFlow(clientId);
} else {
const accessToken = await getAccessToken(clientId, code);
const profile = await fetchProfile(accessToken);
populateUI(profile);
}
In order to make sure that the token exchange works, we need to write the getAccessToken function.
TypeScript
JavaScript
export async function getAccessToken(clientId: string, code: string): Promise {
const verifier = localStorage.getItem("verifier");
const params = new URLSearchParams();
params.append("client_id", clientId);
params.append("grant_type", "authorization_code");
params.append("code", code);
params.append("redirect_uri", "http://127.0.0.1:5173/callback");
params.append("code_verifier", verifier!);
const result = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: params
});
const { access_token } = await result.json();
return access_token;
}