--- import { SPOTIFY_CLIENT_SECRET } from "astro:env/server"; import { SPOTIFY_CLIENT_ID, SPOTIFY_REDIRECT_URI } from "astro:env/server"; import fs from "node:fs/promises"; // make a 404 if accidentally left in prod if (import.meta.env.PROD) return Astro.redirect("/404", 404); const userAuthCode = Astro.url.searchParams.get("code") ?? undefined; if (userAuthCode) { fetch("https://accounts.spotify.com/api/token", { method: "post", headers: { "content-type": "application/x-www-form-urlencoded", Authorization: "Basic " + Buffer.from(SPOTIFY_CLIENT_ID + ":" + SPOTIFY_CLIENT_SECRET).toString( "base64", ), }, body: new URLSearchParams({ code: userAuthCode, redirect_uri: SPOTIFY_REDIRECT_URI, grant_type: "authorization_code", }).toString(), }) .then((res) => res.json()) .then((token) => token.refresh_token) .then((token) => fs.writeFile("./.refreshToken", String(token), { encoding: "utf-8", }), ) .catch((err) => console.error(err)); } const href = `https://accounts.spotify.com/authorize?response_type=code&client_id=${SPOTIFY_CLIENT_ID}&scope=user-read-currently-playing user-top-read&redirect_uri=${SPOTIFY_REDIRECT_URI}`; ---
This endpoint is avaliable at /callback when the _ is removed from the start of the filename.
This endpoint is to gain the first access token and refresh token.
Opening the endpoint with no query parameters will provide a link to authorize the configured application
This should redirect back here where it gains an access token and shows a sucess method
The refresh token is automatically stored for later requests.