I’m building a music portfolio site using NextJS and Spotify API. I need to implement OAuth authentication so users can play music through the website. However, when I try to authenticate, I keep getting a 405 HTTP error status.
The issue happens when the login button is clicked. I tested the same endpoint in Postman and got the identical error. I think it might be related to HTTP method handling but I’m not sure how to fix it.
Here’s my authentication handler in app/api/auth:
export async function AuthHandler(req: NextApiRequest, res: NextApiResponse) {
const randomState = createRandomString(16);
const SPOTIFY_CLIENT_ID = process.env.NEXT_PUBLIC_SPOTIFY_CLIENT_ID;
const permissions = "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: SPOTIFY_CLIENT_ID,
scope: permissions,
redirect_uri: `${CALLBACK_URL}/api/redirect`,
state: randomState,
})
);
}
I’m using Next.js router for navigation:
<button
onClick={() => {
router.push("/api/auth");
}}
>
And here’s my token retrieval functions:
export const fetchAccessToken = () => {
return axios<TokenResponse>({
method: "POST",
url: SPOTIFY_TOKEN_ENDPOINT,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Basic " + Buffer.from(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString("base64"),
},
data: {
grant_type: "client_credentials",
},
});
};
export const fetchAuthToken = (authCode: string) => {
return axios<AuthResponse>({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic ' + Buffer.from(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString('base64'),
},
data: {
code: authCode,
redirect_uri: CALLBACK_URL + '/api/redirect',
grant_type: 'authorization_code',
},
});
}
What could be causing this 405 error and how can I resolve it?