I am in the process of creating a music website portfolio using Spotify and NextJS. I want to incorporate music playback on the website, but I am encountering issues with Spotify authentication. When I click the login button, I receive a 405 HTTP status error. I tried checking it using Postman and encountered the same error. After some research, I believe it might be related to GET/POST problems, but I am unsure about how to resolve it.
Below is the code snippet for the login part:
export async function LoginHandler (req: NextApiRequest, res: NextApiResponse) {
const state = generateRandomString(16);
const CLIENT_ID = process.env.NEXT_PUBLIC_SPOTIFY_CLIENT_ID;
const scope =
"user-read-private user-read-email user-read-playback-state user-modify-playback-state streaming";
res.redirect(
"https://accounts.spotify.com/authorize?"+
qs.stringify({
response_type: "code",
client_id: CLIENT_ID,
scope: scope,
redirect_uri: `${REDIRECT_URL}/api/callback`,
state: state,
})
);
I am utilizing useRouter from Next.js for routing:
<button
onClick={() => {
router.push("/api/login");
}}
>
Here is the code snippet to obtain the access token:
export const getAccessTokenData = () => {
return axios<AccessTokenData>({
method: "POST",
url: SPOTIFY_ACCESS_TOKEN_URL,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization:
"Basic " +
Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64"),
},
data: {
grant_type: "client_credentials",
},
});
};
export const getAuthorizationTokenData = (code: string) => {
return axios<AuthorizationTokenData>({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
'Basic ' +
Buffer.from(
`${CLIENT_ID}:${CLIENT_SECRET}`
).toString('base64'),
},
data: {
code: code,
redirect_uri: REDIRECT_URL + '/api/callback',
grant_type: 'authorization_code',
},
});
}