Announcements

Help Wizard

Step 1

NEXT STEP

500 (Internal Server Error) when I try to refresh token: Authorization code with PKCE extension

500 (Internal Server Error) when I try to refresh token: Authorization code with PKCE extension

Plan

Free

Country
Colombia

 

Device

HP LAPTOP-O1445JB9

Operating System

(Windows 11)

 

My Question or Issue:
when the first token expires, I try to use the refresh token to generate a new one without needing to authorize the user again. But I get an error 500 (Internal Server Error) in the function in charge of making the POST request:

async getRefreshToken() {  
        try {
            const response = await fetch(tokenEndpoint, {
                method: 'POST',
                headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                grant_type: 'refresh_token',
                refresh_token: this.currentToken.refresh_token,
                client_id: clientID
                }),
            });
            if(!response.ok){
                throw new Error('Failed to refresh token');
            }
            const token = await response.json();
            this.currentToken.save(token)
            return this.currentToken.access_token;
        } catch (error){
            console.error('Error refreshing token:', error);
            this.redirectToauthorize();
        }          
    },
and here I store the token

currentToken: {
        get access_token(){
            return localStorage.getItem('access_token')
        },
        get refresh_token(){
            return localStorage.getItem('refresh_token')
        },
        get expires_in(){
            return localStorage.getItem('expires_in')
        },
        get expires(){
            const expiryTimeString = localStorage.getItem('expires');
            return expiryTimeString ? new Date(parseInt(expiryTimeString)) : null;
        },

        save(response){
            const { access_token, refresh_token, expires_in } = response;
            localStorage.setItem('access_token', access_token);
            localStorage.setItem('refresh_token', refresh_token);
            localStorage.setItem('expires_in', expires_in);

            const now = new Date();
            const expiry = now.getTime() + (expires_in * 1000);
            localStorage.setItem('expires', expiry);
        }
    },



 

Reply
0 Replies

Suggested posts

Let's introduce ourselves!

Hey there you,   Yeah, you! 😁   Welcome - we're glad you joined the Spotify Community!   While you here, let's have a fun game and get…

ModeratorStaff / Moderator/ 4 years ago  in Social & Random