Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

Unable to obtain a refresh token

Solved!

Unable to obtain a refresh token

I would like to get a refresh_token in Next.js, but no matter what I do, I cannot get one.

I would like to know how to do this.

Plan

Premium

Country

Japan

Device

PC

Operating System

Windows 10

 

My Question or Issue

The code is as follows

 

 

 

 

 

import { redirect_uri, client_id, client_secret, encode } from "@/module/env";

export default async function handle(req, res) {
  if (req.method === "POST") {
    const { code } = req.body;
    const url = "https://accounts.spotify.com/api/token";
    const params = new URLSearchParams();
    params.append("grant_type", "authorization_code");
    params.append("code", code);
    params.append("client_id", client_id || "");
    params.append("client_secret", client_secret || "");
    params.append("redirect_uri", redirect_uri || "/callback");
    const payload = {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: params
    };
    const body = await fetch(url, payload);
    const response = await body.json();
    res.status(200).json(response);
  } else {
    res.status(405).json({ message: "We only support POST" }).end;
  }
}

export const config = {
  api: {
    externalResolver: true,
  },
};

 

 

 

 

 

 

Reply

Accepted Solutions
Marked as solution

11 Replies

I mean based off of just that code, it doesn't seem like you are including all the necessary information, like the redirect_url, client secret, etc

import { redirect_uri, client_id, client_secret } from "@/module/env";

export default async function handle(req, res) {
if (req.method === "POST") {
try {
const { code } = req.body;
const url = "https://accounts.spotify.com/api/token";
const params = new URLSearchParams();
params.append("grant_type", "authorization_code");
params.append("code", code);
params.append("client_id", client_id);
params.append("client_secret", client_secret);
params.append("redirect_uri", redirect_uri);

const payload = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: params
};

const response = await fetch(url, payload);
const data = await response.json();

if (data.refresh_token) {
// Handle successful response
res.status(200).json(data);
} else {
// Handle missing refresh token
res.status(500).json({ message: "Refresh token not received", data });
}
} catch (error) {
// Handle any errors that occurred during the request
res.status(500).json({ message: "Error occurred", error: error.message });
}
} else {
res.status(405).json({ message: "We only support POST" });
}
}

export const config = {
api: {
externalResolver: true,
},
};

I ran your code after making sure that client_id, client_secret, redirect_uri, code all exist, but I get the following error.

{
"error":"invalid_grant",
"error_description":"Invalid authorization code"
}

 

Double check everything in the Spotify Developer Dashboard matches up. Auth codes only last like a minute, so you need to make sure you're getting the access token correctly.

Also I hope you didn't run that code as is lol

'params.append("grant_type", "authorization_code");' wont work 

I apologize for my ignorance, but how do I get a refresh token?
I ran the code immediately after getting it and got the latest client_id and client_secret from the dashboard

Do I have to rebuild the app.....๏ผŸ

I have no idea. .....

You have to remove the following line:

params.append("grant_type", "authorization_code");

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Thanks for the reply.

I removed params.append("grant_type", "authorization_code"); and ran the following code I get the same error.....

I tried to recreate the app 3 times to try, but no luck.....

    let code = req.body.code;
    const params = new URLSearchParams();
    params.append("redirect_uri", redirect_uri || "");
    params.append("code", code);
    params.append("grant_type", "authorization_code");
    params.append("client_id", public_client_id || "");
    const url = "https://accounts.spotify.com/api/token";
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": "Basic " + Buffer.from(public_client_id + ":" + client_secret).toString("base64"),
      },
      body: params
    });

Edit: Ignore me. I didn't scroll down enough to see that line of code, and the search function couldn't find it also for some reason.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.
Marked as solution

didn't resolve

I'm new to this so apologies if this is obvious but what tripped me up is that the /refresh_token route expects a refresh_token query as a parameter. I tried manually copying and pasting the refresh token in the URL like this to make sure the code works:

 

Suggested posts

Type a product name