NextJS Spotify OAuth integration returns 405 error

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?

You’re getting a 405 error because your API route doesn’t handle the HTTP method properly. router.push() sends a GET request, but your handler isn’t exported as a GET method. In the app directory, you need to export named functions like export async function GET(request) instead of a generic handler. Also double-check your file structure - it should be app/api/auth/route.js, not just auth.js. I ran into this exact same thing when I migrated from pages router to app router, and fixing the export method solved it instantly. Your current setup doesn’t explicitly handle GET requests in the new Next.js format.

you’re mixing old pages router syntax with app router. the 405 error happens because next.js expects named exports like GET, POST, etc. change AuthHandler to GET and use return NextResponse.redirect(url) instead of res.redirect. don’t forget to import NextResponse from next/server. just ran into this same issue last week.

you’re missing the HTTP method exports in your API route. next.js 13+ app router requires you to export GET, POST, etc. functions directly. rename AuthHandler to GET and export it. also make sure your file is named route.js, not auth.js, in the API folder.

You’re getting a 405 error because Next.js app router handles API routes differently than pages router. Your AuthHandler function needs to be exported as GET since router.push makes a GET request. Change your export to export async function GET(request) and update the function signature. The request object works differently in app router compared to NextApiRequest, so you’ll need to adjust your response handling. Instead of res.redirect, return a Response object with a redirect like return Response.redirect(yourSpotifyUrl). I ran into the same thing switching from pages to app router - the HTTP method naming is way stricter now.