I’m having trouble with the Spotify authentication flow. Every time I try to exchange my authorization code for an access token, I get a 400 bad request error back from their API. I’ve double checked all my parameters and they seem correct but something must be wrong.
async function fetchSpotifyToken(appId, authCode) {
const codeVerifier = localStorage.getItem("pkce_verifier");
const requestBody = new URLSearchParams();
requestBody.append("client_id", appId);
requestBody.append("grant_type", "authorization_code");
requestBody.append("code", authCode);
requestBody.append("redirect_uri", "http://localhost:5173/callback");
requestBody.append("code_verifier", codeVerifier);
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: requestBody
});
const tokenData = await response.json();
return tokenData.access_token;
}
I’ve verified that the appId, authCode, and codeVerifier all have values when the function runs. What could be causing this 400 error?
Had this same problem a few months ago - it’s usually a timing issue. Auth codes expire fast, like within 10 minutes. Any delay between the user finishing auth and your code trying to exchange it will throw that 400 error. Also, check if your code_verifier got wiped from localStorage - browsers do this randomly during dev. Add some console logs to make sure the code_verifier value is actually correct, not just present.
Been down this rabbit hole way too many times. The problem’s usually juggling all the moving pieces - code verifier, timing windows, redirect URIs that need to match exactly.
Debugging OAuth flows manually sucks. You’ve got temporary codes, PKCE verification, exact URL matching, and tight timing windows. One tiny mistake and boom - 400 error.
I ditched the manual wrestling and automated the whole Spotify auth flow instead. Built a workflow that handles the OAuth dance, manages token refreshes, and retries failed requests with proper backoff.
Best part? You can test different scenarios without constantly going through browser auth. It catches edge cases like expired verifiers or malformed requests automatically.
Check it out: https://latenode.com
totally get it! had a similar prob before. just remember that your redirect_uri must be spot on with what’s in the dev console. even a tiny mismatch like a trailing slash can mess things up. also, make sure your pkce_verifier is still valid!